From db4d82cc7d82bd5de314525ef6b5b77ef1e53384 Mon Sep 17 00:00:00 2001 From: SDKAuto Date: Wed, 30 Nov 2022 03:18:21 +0000 Subject: [PATCH] CodeGen from PR 21706 in Azure/azure-rest-api-specs Update readme.python.md (#21706) --- .../azure-mgmt-digitaltwins/_meta.json | 12 +- .../azure/mgmt/digitaltwins/__init__.py | 4 + .../_azure_digital_twins_management_client.py | 53 +- .../azure/mgmt/digitaltwins/_configuration.py | 18 +- .../azure/mgmt/digitaltwins/_serialization.py | 1967 +++++++++++++++++ .../_azure_digital_twins_management_client.py | 40 +- .../mgmt/digitaltwins/aio/_configuration.py | 6 +- .../azure/mgmt/digitaltwins/models.py | 2 +- .../v2020_03_01_preview/__init__.py | 18 +- .../_azure_digital_twins_management_client.py | 40 +- .../v2020_03_01_preview/_configuration.py | 51 +- .../v2020_03_01_preview/_metadata.json | 24 +- .../v2020_03_01_preview/_patch.py | 2 +- .../v2020_03_01_preview/_vendor.py | 6 +- .../v2020_03_01_preview/_version.py | 2 +- .../v2020_03_01_preview/aio/__init__.py | 18 +- .../_azure_digital_twins_management_client.py | 31 +- .../v2020_03_01_preview/aio/_configuration.py | 50 +- .../v2020_03_01_preview/aio/_patch.py | 2 +- .../aio/operations/__init__.py | 12 +- .../_digital_twins_endpoint_operations.py | 506 +++-- .../operations/_digital_twins_operations.py | 865 +++++--- .../aio/operations/_operations.py | 110 +- .../aio/operations/_patch.py | 20 + .../v2020_03_01_preview/models/__init__.py | 66 +- ...e_digital_twins_management_client_enums.py | 30 +- .../v2020_03_01_preview/models/_models_py3.py | 548 +++-- .../v2020_03_01_preview/models/_patch.py | 20 + .../operations/__init__.py | 12 +- .../_digital_twins_endpoint_operations.py | 714 +++--- .../operations/_digital_twins_operations.py | 1201 ++++++---- .../operations/_operations.py | 145 +- .../v2020_03_01_preview/operations/_patch.py | 20 + .../mgmt/digitaltwins/v2020_10_31/__init__.py | 18 +- .../_azure_digital_twins_management_client.py | 40 +- .../v2020_10_31/_configuration.py | 51 +- .../digitaltwins/v2020_10_31/_metadata.json | 24 +- .../mgmt/digitaltwins/v2020_10_31/_patch.py | 2 +- .../mgmt/digitaltwins/v2020_10_31/_vendor.py | 6 +- .../mgmt/digitaltwins/v2020_10_31/_version.py | 2 +- .../digitaltwins/v2020_10_31/aio/__init__.py | 18 +- .../_azure_digital_twins_management_client.py | 31 +- .../v2020_10_31/aio/_configuration.py | 50 +- .../digitaltwins/v2020_10_31/aio/_patch.py | 2 +- .../v2020_10_31/aio/operations/__init__.py | 12 +- .../_digital_twins_endpoint_operations.py | 498 +++-- .../operations/_digital_twins_operations.py | 777 +++++-- .../v2020_10_31/aio/operations/_operations.py | 108 +- .../v2020_10_31/aio/operations/_patch.py | 20 + .../v2020_10_31/models/__init__.py | 60 +- ...e_digital_twins_management_client_enums.py | 24 +- .../v2020_10_31/models/_models_py3.py | 521 ++--- .../digitaltwins/v2020_10_31/models/_patch.py | 20 + .../v2020_10_31/operations/__init__.py | 12 +- .../_digital_twins_endpoint_operations.py | 753 ++++--- .../operations/_digital_twins_operations.py | 1143 ++++++---- .../v2020_10_31/operations/_operations.py | 148 +- .../v2020_10_31/operations/_patch.py | 20 + .../mgmt/digitaltwins/v2020_12_01/__init__.py | 18 +- .../_azure_digital_twins_management_client.py | 58 +- .../v2020_12_01/_configuration.py | 51 +- .../digitaltwins/v2020_12_01/_metadata.json | 24 +- .../mgmt/digitaltwins/v2020_12_01/_patch.py | 2 +- .../mgmt/digitaltwins/v2020_12_01/_vendor.py | 6 +- .../mgmt/digitaltwins/v2020_12_01/_version.py | 2 +- .../digitaltwins/v2020_12_01/aio/__init__.py | 18 +- .../_azure_digital_twins_management_client.py | 49 +- .../v2020_12_01/aio/_configuration.py | 50 +- .../digitaltwins/v2020_12_01/aio/_patch.py | 2 +- .../v2020_12_01/aio/operations/__init__.py | 16 +- .../_digital_twins_endpoint_operations.py | 498 +++-- .../operations/_digital_twins_operations.py | 853 ++++--- .../v2020_12_01/aio/operations/_operations.py | 108 +- .../v2020_12_01/aio/operations/_patch.py | 20 + ...private_endpoint_connections_operations.py | 470 ++-- .../_private_link_resources_operations.py | 149 +- .../v2020_12_01/models/__init__.py | 108 +- ...e_digital_twins_management_client_enums.py | 51 +- .../v2020_12_01/models/_models_py3.py | 873 ++++---- .../digitaltwins/v2020_12_01/models/_patch.py | 20 + .../v2020_12_01/operations/__init__.py | 16 +- .../_digital_twins_endpoint_operations.py | 753 ++++--- .../operations/_digital_twins_operations.py | 1227 ++++++---- .../v2020_12_01/operations/_operations.py | 148 +- .../v2020_12_01/operations/_patch.py | 20 + ...private_endpoint_connections_operations.py | 684 +++--- .../_private_link_resources_operations.py | 260 ++- .../v2021_06_30_preview/__init__.py | 18 +- .../_azure_digital_twins_management_client.py | 63 +- .../v2021_06_30_preview/_configuration.py | 51 +- .../v2021_06_30_preview/_metadata.json | 24 +- .../v2021_06_30_preview/_patch.py | 2 +- .../v2021_06_30_preview/_vendor.py | 6 +- .../v2021_06_30_preview/_version.py | 2 +- .../v2021_06_30_preview/aio/__init__.py | 18 +- .../_azure_digital_twins_management_client.py | 54 +- .../v2021_06_30_preview/aio/_configuration.py | 50 +- .../v2021_06_30_preview/aio/_patch.py | 2 +- .../aio/operations/__init__.py | 18 +- .../_digital_twins_endpoint_operations.py | 508 +++-- .../operations/_digital_twins_operations.py | 873 +++++--- .../aio/operations/_operations.py | 110 +- .../aio/operations/_patch.py | 20 + ...private_endpoint_connections_operations.py | 480 ++-- .../_private_link_resources_operations.py | 153 +- ..._series_database_connections_operations.py | 509 +++-- .../v2021_06_30_preview/models/__init__.py | 124 +- ...e_digital_twins_management_client_enums.py | 66 +- .../v2021_06_30_preview/models/_models_py3.py | 1047 +++++---- .../v2021_06_30_preview/models/_patch.py | 20 + .../operations/__init__.py | 18 +- .../_digital_twins_endpoint_operations.py | 759 ++++--- .../operations/_digital_twins_operations.py | 1237 +++++++---- .../operations/_operations.py | 145 +- .../v2021_06_30_preview/operations/_patch.py | 20 + ...private_endpoint_connections_operations.py | 702 +++--- .../_private_link_resources_operations.py | 264 ++- ..._series_database_connections_operations.py | 748 ++++--- .../mgmt/digitaltwins/v2022_05_31/__init__.py | 18 +- .../_azure_digital_twins_management_client.py | 63 +- .../v2022_05_31/_configuration.py | 51 +- .../digitaltwins/v2022_05_31/_metadata.json | 24 +- .../mgmt/digitaltwins/v2022_05_31/_patch.py | 2 +- .../mgmt/digitaltwins/v2022_05_31/_vendor.py | 6 +- .../mgmt/digitaltwins/v2022_05_31/_version.py | 2 +- .../digitaltwins/v2022_05_31/aio/__init__.py | 18 +- .../_azure_digital_twins_management_client.py | 54 +- .../v2022_05_31/aio/_configuration.py | 50 +- .../digitaltwins/v2022_05_31/aio/_patch.py | 2 +- .../v2022_05_31/aio/operations/__init__.py | 18 +- .../_digital_twins_endpoint_operations.py | 498 +++-- .../operations/_digital_twins_operations.py | 853 ++++--- .../v2022_05_31/aio/operations/_operations.py | 108 +- .../v2022_05_31/aio/operations/_patch.py | 20 + ...private_endpoint_connections_operations.py | 470 ++-- .../_private_link_resources_operations.py | 149 +- ..._series_database_connections_operations.py | 499 +++-- .../v2022_05_31/models/__init__.py | 124 +- ...e_digital_twins_management_client_enums.py | 66 +- .../v2022_05_31/models/_models_py3.py | 1047 +++++---- .../digitaltwins/v2022_05_31/models/_patch.py | 20 + .../v2022_05_31/operations/__init__.py | 18 +- .../_digital_twins_endpoint_operations.py | 753 ++++--- .../operations/_digital_twins_operations.py | 1227 ++++++---- .../v2022_05_31/operations/_operations.py | 148 +- .../v2022_05_31/operations/_patch.py | 20 + ...private_endpoint_connections_operations.py | 684 +++--- .../_private_link_resources_operations.py | 260 ++- ..._series_database_connections_operations.py | 730 +++--- .../mgmt/digitaltwins/v2022_10_31/__init__.py | 26 + .../_azure_digital_twins_management_client.py | 125 ++ .../v2022_10_31/_configuration.py | 72 + .../digitaltwins/v2022_10_31/_metadata.json | 107 + .../mgmt/digitaltwins/v2022_10_31/_patch.py | 20 + .../mgmt/digitaltwins/v2022_10_31/_vendor.py | 27 + .../mgmt/digitaltwins/v2022_10_31/_version.py | 9 + .../digitaltwins/v2022_10_31/aio/__init__.py | 23 + .../_azure_digital_twins_management_client.py | 126 ++ .../v2022_10_31/aio/_configuration.py | 72 + .../digitaltwins/v2022_10_31/aio/_patch.py | 20 + .../v2022_10_31/aio/operations/__init__.py | 29 + .../_digital_twins_endpoint_operations.py | 600 +++++ .../operations/_digital_twins_operations.py | 1029 +++++++++ .../v2022_10_31/aio/operations/_operations.py | 138 ++ .../v2022_10_31/aio/operations/_patch.py | 20 + ...private_endpoint_connections_operations.py | 555 +++++ .../_private_link_resources_operations.py | 187 ++ ..._series_database_connections_operations.py | 600 +++++ .../v2022_10_31/models/__init__.py | 115 + ...e_digital_twins_management_client_enums.py | 142 ++ .../v2022_10_31/models/_models_py3.py | 1873 ++++++++++++++++ .../digitaltwins/v2022_10_31/models/_patch.py | 20 + .../v2022_10_31/operations/__init__.py | 29 + .../_digital_twins_endpoint_operations.py | 784 +++++++ .../operations/_digital_twins_operations.py | 1274 +++++++++++ .../v2022_10_31/operations/_operations.py | 159 ++ .../v2022_10_31/operations/_patch.py | 20 + ...private_endpoint_connections_operations.py | 737 ++++++ .../_private_link_resources_operations.py | 269 +++ ..._series_database_connections_operations.py | 796 +++++++ .../mgmt/digitaltwins/v2022_10_31/py.typed | 1 + 181 files changed, 31253 insertions(+), 12393 deletions(-) create mode 100644 sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/_serialization.py create mode 100644 sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/aio/operations/_patch.py create mode 100644 sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/models/_patch.py create mode 100644 sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/operations/_patch.py create mode 100644 sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/aio/operations/_patch.py create mode 100644 sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/models/_patch.py create mode 100644 sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/operations/_patch.py create mode 100644 sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/aio/operations/_patch.py create mode 100644 sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/models/_patch.py create mode 100644 sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/operations/_patch.py create mode 100644 sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/aio/operations/_patch.py create mode 100644 sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/models/_patch.py create mode 100644 sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/operations/_patch.py create mode 100644 sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/aio/operations/_patch.py create mode 100644 sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/models/_patch.py create mode 100644 sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/operations/_patch.py create mode 100644 sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/__init__.py create mode 100644 sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/_azure_digital_twins_management_client.py create mode 100644 sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/_configuration.py create mode 100644 sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/_metadata.json create mode 100644 sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/_patch.py create mode 100644 sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/_vendor.py create mode 100644 sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/_version.py create mode 100644 sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/aio/__init__.py create mode 100644 sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/aio/_azure_digital_twins_management_client.py create mode 100644 sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/aio/_configuration.py create mode 100644 sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/aio/_patch.py create mode 100644 sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/aio/operations/__init__.py create mode 100644 sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/aio/operations/_digital_twins_endpoint_operations.py create mode 100644 sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/aio/operations/_digital_twins_operations.py create mode 100644 sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/aio/operations/_operations.py create mode 100644 sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/aio/operations/_patch.py create mode 100644 sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/aio/operations/_private_endpoint_connections_operations.py create mode 100644 sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/aio/operations/_private_link_resources_operations.py create mode 100644 sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/aio/operations/_time_series_database_connections_operations.py create mode 100644 sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/models/__init__.py create mode 100644 sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/models/_azure_digital_twins_management_client_enums.py create mode 100644 sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/models/_models_py3.py create mode 100644 sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/models/_patch.py create mode 100644 sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/operations/__init__.py create mode 100644 sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/operations/_digital_twins_endpoint_operations.py create mode 100644 sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/operations/_digital_twins_operations.py create mode 100644 sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/operations/_operations.py create mode 100644 sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/operations/_patch.py create mode 100644 sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/operations/_private_endpoint_connections_operations.py create mode 100644 sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/operations/_private_link_resources_operations.py create mode 100644 sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/operations/_time_series_database_connections_operations.py create mode 100644 sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/py.typed diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/_meta.json b/sdk/digitaltwins/azure-mgmt-digitaltwins/_meta.json index afcfbf049f789..efbe620b559f9 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/_meta.json +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/_meta.json @@ -1,11 +1,11 @@ { - "autorest": "3.7.2", + "commit": "2f2e48923cebd95f7d184608a29bcd06d9cb3653", + "repository_url": "https://github.com/Azure/azure-rest-api-specs", + "autorest": "3.9.2", "use": [ - "@autorest/python@5.13.0", - "@autorest/modelerfour@4.19.3" + "@autorest/python@6.2.7", + "@autorest/modelerfour@4.24.3" ], - "commit": "2eff0ce269e651478a36712c6edcd51a82842141", - "repository_url": "https://github.com/Azure/azure-rest-api-specs", - "autorest_command": "autorest specification/digitaltwins/resource-manager/readme.md --python --python-sdks-folder=/home/vsts/work/1/azure-sdk-for-python/sdk --python3-only --use=@autorest/python@5.13.0 --use=@autorest/modelerfour@4.19.3 --version=3.7.2", + "autorest_command": "autorest specification/digitaltwins/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.7 --use=@autorest/modelerfour@4.24.3 --version=3.9.2 --version-tolerant=False", "readme": "specification/digitaltwins/resource-manager/readme.md" } \ No newline at end of file diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/__init__.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/__init__.py index 85ac57a09d407..2a8346ceded28 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/__init__.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/__init__.py @@ -14,3 +14,7 @@ patch_sdk() except ImportError: pass + +from ._version import VERSION + +__version__ = VERSION diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/_azure_digital_twins_management_client.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/_azure_digital_twins_management_client.py index f7e0647a12da4..eda9512b92bc7 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/_azure_digital_twins_management_client.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/_azure_digital_twins_management_client.py @@ -9,20 +9,17 @@ # regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING - -from msrest import Deserializer, Serializer +from typing import Any, Optional, TYPE_CHECKING from azure.mgmt.core import ARMPipelineClient from azure.profiles import KnownProfiles, ProfileDefinition from azure.profiles.multiapiclient import MultiApiClientMixin from ._configuration import AzureDigitalTwinsManagementClientConfiguration +from ._serialization import Deserializer, Serializer if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Optional - from azure.core.credentials import TokenCredential class _SDKClient(object): @@ -43,9 +40,9 @@ class AzureDigitalTwinsManagementClient(MultiApiClientMixin, _SDKClient): The api-version parameter sets the default API version if the operation group is not described in the profile. - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: The subscription identifier. + :param subscription_id: The subscription identifier. Required. :type subscription_id: str :param api_version: API version to use if no profile is provided, or if missing in profile. :type api_version: str @@ -56,7 +53,7 @@ class AzureDigitalTwinsManagementClient(MultiApiClientMixin, _SDKClient): :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. """ - DEFAULT_API_VERSION = '2022-05-31' + DEFAULT_API_VERSION = '2022-10-31' _PROFILE_TAG = "azure.mgmt.digitaltwins.AzureDigitalTwinsManagementClient" LATEST_PROFILE = ProfileDefinition({ _PROFILE_TAG: { @@ -67,12 +64,12 @@ class AzureDigitalTwinsManagementClient(MultiApiClientMixin, _SDKClient): def __init__( self, - credential, # type: "TokenCredential" - subscription_id, # type: str - api_version=None, # type: Optional[str] - base_url="https://management.azure.com", # type: str - profile=KnownProfiles.default, # type: KnownProfiles - **kwargs # type: Any + credential: "TokenCredential", + subscription_id: str, + api_version: Optional[str]=None, + base_url: str = "https://management.azure.com", + profile: KnownProfiles=KnownProfiles.default, + **kwargs: Any ): self._config = AzureDigitalTwinsManagementClientConfiguration(credential, subscription_id, **kwargs) self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) @@ -94,6 +91,7 @@ def models(cls, api_version=DEFAULT_API_VERSION): * 2020-12-01: :mod:`v2020_12_01.models` * 2021-06-30-preview: :mod:`v2021_06_30_preview.models` * 2022-05-31: :mod:`v2022_05_31.models` + * 2022-10-31: :mod:`v2022_10_31.models` """ if api_version == '2020-03-01-preview': from .v2020_03_01_preview import models @@ -110,6 +108,9 @@ def models(cls, api_version=DEFAULT_API_VERSION): elif api_version == '2022-05-31': from .v2022_05_31 import models return models + elif api_version == '2022-10-31': + from .v2022_10_31 import models + return models raise ValueError("API version {} is not available".format(api_version)) @property @@ -121,6 +122,7 @@ def digital_twins(self): * 2020-12-01: :class:`DigitalTwinsOperations` * 2021-06-30-preview: :class:`DigitalTwinsOperations` * 2022-05-31: :class:`DigitalTwinsOperations` + * 2022-10-31: :class:`DigitalTwinsOperations` """ api_version = self._get_api_version('digital_twins') if api_version == '2020-03-01-preview': @@ -133,8 +135,11 @@ def digital_twins(self): from .v2021_06_30_preview.operations import DigitalTwinsOperations as OperationClass elif api_version == '2022-05-31': from .v2022_05_31.operations import DigitalTwinsOperations as OperationClass + elif api_version == '2022-10-31': + from .v2022_10_31.operations import DigitalTwinsOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'digital_twins'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property @@ -146,6 +151,7 @@ def digital_twins_endpoint(self): * 2020-12-01: :class:`DigitalTwinsEndpointOperations` * 2021-06-30-preview: :class:`DigitalTwinsEndpointOperations` * 2022-05-31: :class:`DigitalTwinsEndpointOperations` + * 2022-10-31: :class:`DigitalTwinsEndpointOperations` """ api_version = self._get_api_version('digital_twins_endpoint') if api_version == '2020-03-01-preview': @@ -158,8 +164,11 @@ def digital_twins_endpoint(self): from .v2021_06_30_preview.operations import DigitalTwinsEndpointOperations as OperationClass elif api_version == '2022-05-31': from .v2022_05_31.operations import DigitalTwinsEndpointOperations as OperationClass + elif api_version == '2022-10-31': + from .v2022_10_31.operations import DigitalTwinsEndpointOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'digital_twins_endpoint'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property @@ -171,6 +180,7 @@ def operations(self): * 2020-12-01: :class:`Operations` * 2021-06-30-preview: :class:`Operations` * 2022-05-31: :class:`Operations` + * 2022-10-31: :class:`Operations` """ api_version = self._get_api_version('operations') if api_version == '2020-03-01-preview': @@ -183,8 +193,11 @@ def operations(self): from .v2021_06_30_preview.operations import Operations as OperationClass elif api_version == '2022-05-31': from .v2022_05_31.operations import Operations as OperationClass + elif api_version == '2022-10-31': + from .v2022_10_31.operations import Operations as OperationClass else: raise ValueError("API version {} does not have operation group 'operations'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property @@ -194,6 +207,7 @@ def private_endpoint_connections(self): * 2020-12-01: :class:`PrivateEndpointConnectionsOperations` * 2021-06-30-preview: :class:`PrivateEndpointConnectionsOperations` * 2022-05-31: :class:`PrivateEndpointConnectionsOperations` + * 2022-10-31: :class:`PrivateEndpointConnectionsOperations` """ api_version = self._get_api_version('private_endpoint_connections') if api_version == '2020-12-01': @@ -202,8 +216,11 @@ def private_endpoint_connections(self): from .v2021_06_30_preview.operations import PrivateEndpointConnectionsOperations as OperationClass elif api_version == '2022-05-31': from .v2022_05_31.operations import PrivateEndpointConnectionsOperations as OperationClass + elif api_version == '2022-10-31': + from .v2022_10_31.operations import PrivateEndpointConnectionsOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'private_endpoint_connections'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property @@ -213,6 +230,7 @@ def private_link_resources(self): * 2020-12-01: :class:`PrivateLinkResourcesOperations` * 2021-06-30-preview: :class:`PrivateLinkResourcesOperations` * 2022-05-31: :class:`PrivateLinkResourcesOperations` + * 2022-10-31: :class:`PrivateLinkResourcesOperations` """ api_version = self._get_api_version('private_link_resources') if api_version == '2020-12-01': @@ -221,8 +239,11 @@ def private_link_resources(self): from .v2021_06_30_preview.operations import PrivateLinkResourcesOperations as OperationClass elif api_version == '2022-05-31': from .v2022_05_31.operations import PrivateLinkResourcesOperations as OperationClass + elif api_version == '2022-10-31': + from .v2022_10_31.operations import PrivateLinkResourcesOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'private_link_resources'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property @@ -231,14 +252,18 @@ def time_series_database_connections(self): * 2021-06-30-preview: :class:`TimeSeriesDatabaseConnectionsOperations` * 2022-05-31: :class:`TimeSeriesDatabaseConnectionsOperations` + * 2022-10-31: :class:`TimeSeriesDatabaseConnectionsOperations` """ api_version = self._get_api_version('time_series_database_connections') if api_version == '2021-06-30-preview': from .v2021_06_30_preview.operations import TimeSeriesDatabaseConnectionsOperations as OperationClass elif api_version == '2022-05-31': from .v2022_05_31.operations import TimeSeriesDatabaseConnectionsOperations as OperationClass + elif api_version == '2022-10-31': + from .v2022_10_31.operations import TimeSeriesDatabaseConnectionsOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'time_series_database_connections'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) def close(self): diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/_configuration.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/_configuration.py index 5688fda759102..a46b6e69bf481 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/_configuration.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/_configuration.py @@ -8,7 +8,7 @@ # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING +from typing import Any, TYPE_CHECKING from azure.core.configuration import Configuration from azure.core.pipeline import policies @@ -18,8 +18,6 @@ if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports - from typing import Any - from azure.core.credentials import TokenCredential class AzureDigitalTwinsManagementClientConfiguration(Configuration): @@ -28,19 +26,18 @@ class AzureDigitalTwinsManagementClientConfiguration(Configuration): Note that all parameters used to create this instance are saved as instance attributes. - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: The subscription identifier. + :param subscription_id: The subscription identifier. Required. :type subscription_id: str """ def __init__( self, - credential, # type: "TokenCredential" - subscription_id, # type: str - **kwargs # type: Any + credential: "TokenCredential", + subscription_id: str, + **kwargs: Any ): - # type: (...) -> None if credential is None: raise ValueError("Parameter 'credential' must not be None.") if subscription_id is None: @@ -55,9 +52,8 @@ def __init__( def _configure( self, - **kwargs # type: Any + **kwargs: Any ): - # type: (...) -> None self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/_serialization.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/_serialization.py new file mode 100644 index 0000000000000..2c170e28dbca2 --- /dev/null +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/_serialization.py @@ -0,0 +1,1967 @@ +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- + +# pylint: skip-file +# pyright: reportUnnecessaryTypeIgnoreComment=false + +from base64 import b64decode, b64encode +import calendar +import datetime +import decimal +import email +from enum import Enum +import json +import logging +import re +import sys +import codecs +from typing import Optional, Union, AnyStr, IO, Mapping + +try: + from urllib import quote # type: ignore +except ImportError: + from urllib.parse import quote +import xml.etree.ElementTree as ET + +import isodate # type: ignore + +from typing import Dict, Any, cast + +from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback + +_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") + + +class RawDeserializer: + + # Accept "text" because we're open minded people... + JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") + + # Name used in context + CONTEXT_NAME = "deserialized_data" + + @classmethod + def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: Optional[str] = None) -> Any: + """Decode data according to content-type. + + Accept a stream of data as well, but will be load at once in memory for now. + + If no content-type, will return the string version (not bytes, not stream) + + :param data: Input, could be bytes or stream (will be decoded with UTF8) or text + :type data: str or bytes or IO + :param str content_type: The content type. + """ + if hasattr(data, "read"): + # Assume a stream + data = cast(IO, data).read() + + if isinstance(data, bytes): + data_as_str = data.decode(encoding="utf-8-sig") + else: + # Explain to mypy the correct type. + data_as_str = cast(str, data) + + # Remove Byte Order Mark if present in string + data_as_str = data_as_str.lstrip(_BOM) + + if content_type is None: + return data + + if cls.JSON_REGEXP.match(content_type): + try: + return json.loads(data_as_str) + except ValueError as err: + raise DeserializationError("JSON is invalid: {}".format(err), err) + elif "xml" in (content_type or []): + try: + + try: + if isinstance(data, unicode): # type: ignore + # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string + data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore + except NameError: + pass + + return ET.fromstring(data_as_str) # nosec + except ET.ParseError: + # It might be because the server has an issue, and returned JSON with + # content-type XML.... + # So let's try a JSON load, and if it's still broken + # let's flow the initial exception + def _json_attemp(data): + try: + return True, json.loads(data) + except ValueError: + return False, None # Don't care about this one + + success, json_result = _json_attemp(data) + if success: + return json_result + # If i'm here, it's not JSON, it's not XML, let's scream + # and raise the last context in this block (the XML exception) + # The function hack is because Py2.7 messes up with exception + # context otherwise. + _LOGGER.critical("Wasn't XML not JSON, failing") + raise_with_traceback(DeserializationError, "XML is invalid") + raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) + + @classmethod + def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], headers: Mapping) -> Any: + """Deserialize from HTTP response. + + Use bytes and headers to NOT use any requests/aiohttp or whatever + specific implementation. + Headers will tested for "content-type" + """ + # Try to use content-type from headers if available + content_type = None + if "content-type" in headers: + content_type = headers["content-type"].split(";")[0].strip().lower() + # Ouch, this server did not declare what it sent... + # Let's guess it's JSON... + # Also, since Autorest was considering that an empty body was a valid JSON, + # need that test as well.... + else: + content_type = "application/json" + + if body_bytes: + return cls.deserialize_from_text(body_bytes, content_type) + return None + + +try: + basestring # type: ignore + unicode_str = unicode # type: ignore +except NameError: + basestring = str + unicode_str = str + +_LOGGER = logging.getLogger(__name__) + +try: + _long_type = long # type: ignore +except NameError: + _long_type = int + + +class UTC(datetime.tzinfo): + """Time Zone info for handling UTC""" + + def utcoffset(self, dt): + """UTF offset for UTC is 0.""" + return datetime.timedelta(0) + + def tzname(self, dt): + """Timestamp representation.""" + return "Z" + + def dst(self, dt): + """No daylight saving for UTC.""" + return datetime.timedelta(hours=1) + + +try: + from datetime import timezone as _FixedOffset # type: ignore +except ImportError: # Python 2.7 + + class _FixedOffset(datetime.tzinfo): # type: ignore + """Fixed offset in minutes east from UTC. + Copy/pasted from Python doc + :param datetime.timedelta offset: offset in timedelta format + """ + + def __init__(self, offset): + self.__offset = offset + + def utcoffset(self, dt): + return self.__offset + + def tzname(self, dt): + return str(self.__offset.total_seconds() / 3600) + + def __repr__(self): + return "".format(self.tzname(None)) + + def dst(self, dt): + return datetime.timedelta(0) + + def __getinitargs__(self): + return (self.__offset,) + + +try: + from datetime import timezone + + TZ_UTC = timezone.utc +except ImportError: + TZ_UTC = UTC() # type: ignore + +_FLATTEN = re.compile(r"(? 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) # type: ignore + continue + if xml_desc.get("text", False): + serialized.text = new_attr # type: ignore + continue + if isinstance(new_attr, list): + serialized.extend(new_attr) # type: ignore + elif isinstance(new_attr, ET.Element): + # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. + if "name" not in getattr(orig_attr, "_xml_map", {}): + splitted_tag = new_attr.tag.split("}") + if len(splitted_tag) == 2: # Namespace + new_attr.tag = "}".join([splitted_tag[0], xml_name]) + else: + new_attr.tag = xml_name + serialized.append(new_attr) # type: ignore + else: # That's a basic type + # Integrate namespace if necessary + local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) + local_node.text = unicode_str(new_attr) + serialized.append(local_node) # type: ignore + else: # JSON + for k in reversed(keys): # type: ignore + unflattened = {k: new_attr} + new_attr = unflattened + + _new_attr = new_attr + _serialized = serialized + for k in keys: # type: ignore + if k not in _serialized: + _serialized.update(_new_attr) # type: ignore + _new_attr = _new_attr[k] # type: ignore + _serialized = _serialized[k] + except ValueError: + continue + + except (AttributeError, KeyError, TypeError) as err: + msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) + raise_with_traceback(SerializationError, msg, err) + else: + return serialized + + def body(self, data, data_type, **kwargs): + """Serialize data intended for a request body. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: dict + :raises: SerializationError if serialization fails. + :raises: ValueError if data is None + """ + + # Just in case this is a dict + internal_data_type = 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 = [ # type: ignore + attribute_key_case_insensitive_extractor, + ] + else: + deserializer.key_extractors = [ + rest_key_case_insensitive_extractor, + attribute_key_case_insensitive_extractor, + last_rest_key_case_insensitive_extractor, + ] + data = deserializer._deserialize(data_type, data) + except DeserializationError as err: + raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) + + return self._serialize(data, data_type, **kwargs) + + def url(self, name, data, data_type, **kwargs): + """Serialize data intended for a URL path. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :raises: TypeError if serialization fails. + :raises: ValueError if data is None + """ + try: + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + + if kwargs.get("skip_quote") is True: + output = str(output) + else: + output = quote(str(output), safe="") + except SerializationError: + raise TypeError("{} must be type {}.".format(name, data_type)) + else: + return output + + def query(self, name, data, data_type, **kwargs): + """Serialize data intended for a URL query. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :raises: TypeError if serialization fails. + :raises: ValueError if data is None + """ + try: + # Treat the list aside, since we don't want to encode the div separator + if data_type.startswith("["): + internal_data_type = data_type[1:-1] + data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] + if not kwargs.get("skip_quote", False): + data = [quote(str(d), safe="") for d in data] + return str(self.serialize_iter(data, internal_data_type, **kwargs)) + + # Not a list, regular serialization + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + if kwargs.get("skip_quote") is True: + output = str(output) + else: + output = quote(str(output), safe="") + except SerializationError: + raise TypeError("{} must be type {}.".format(name, data_type)) + else: + return str(output) + + def header(self, name, data, data_type, **kwargs): + """Serialize data intended for a request header. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :raises: TypeError if serialization fails. + :raises: ValueError if data is None + """ + try: + if data_type in ["[str]"]: + data = ["" if d is None else d for d in data] + + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + except SerializationError: + raise TypeError("{} must be type {}.".format(name, data_type)) + else: + return str(output) + + def serialize_data(self, data, data_type, **kwargs): + """Serialize generic data according to supplied data type. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :param bool required: Whether it's essential that the data not be + empty or None + :raises: AttributeError if required data is None. + :raises: ValueError if data is None + :raises: SerializationError if serialization fails. + """ + if data is None: + raise ValueError("No value for given attribute") + + try: + if data_type in self.basic_types.values(): + return self.serialize_basic(data, data_type, **kwargs) + + elif data_type in self.serialize_type: + return self.serialize_type[data_type](data, **kwargs) + + # If dependencies is empty, try with current data class + # It has to be a subclass of Enum anyway + enum_type = self.dependencies.get(data_type, data.__class__) + if issubclass(enum_type, Enum): + return Serializer.serialize_enum(data, enum_obj=enum_type) + + iter_type = data_type[0] + data_type[-1] + if iter_type in self.serialize_type: + return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) + + except (ValueError, TypeError) as err: + msg = "Unable to serialize value: {!r} as type: {!r}." + raise_with_traceback(SerializationError, msg.format(data, data_type), err) + else: + return self._serialize(data, **kwargs) + + @classmethod + def _get_custom_serializers(cls, data_type, **kwargs): + custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) + if custom_serializer: + return custom_serializer + if kwargs.get("is_xml", False): + return cls._xml_basic_types_serializers.get(data_type) + + @classmethod + def serialize_basic(cls, data, data_type, **kwargs): + """Serialize basic builting data type. + Serializes objects to str, int, float or bool. + + Possible kwargs: + - basic_types_serializers dict[str, callable] : If set, use the callable as serializer + - is_xml bool : If set, use xml_basic_types_serializers + + :param data: Object to be serialized. + :param str data_type: Type of object in the iterable. + """ + custom_serializer = cls._get_custom_serializers(data_type, **kwargs) + if custom_serializer: + return custom_serializer(data) + if data_type == "str": + return cls.serialize_unicode(data) + return eval(data_type)(data) # nosec + + @classmethod + def serialize_unicode(cls, data): + """Special handling for serializing unicode strings in Py2. + Encode to UTF-8 if unicode, otherwise handle as a str. + + :param data: Object to be serialized. + :rtype: str + """ + try: # If I received an enum, return its value + return data.value + except AttributeError: + pass + + try: + if isinstance(data, unicode): # type: ignore + # Don't change it, JSON and XML ElementTree are totally able + # to serialize correctly u'' strings + return data + except NameError: + return str(data) + else: + return str(data) + + def serialize_iter(self, data, iter_type, div=None, **kwargs): + """Serialize iterable. + + Supported kwargs: + - serialization_ctxt dict : The current entry of _attribute_map, or same format. + serialization_ctxt['type'] should be same as data_type. + - is_xml bool : If set, serialize as XML + + :param list attr: Object to be serialized. + :param str iter_type: Type of object in the iterable. + :param bool required: Whether the objects in the iterable must + not be None or empty. + :param str div: If set, this str will be used to combine the elements + in the iterable into a combined string. Default is 'None'. + :rtype: list, str + """ + if isinstance(data, str): + raise SerializationError("Refuse str type as a valid iter type.") + + serialization_ctxt = kwargs.get("serialization_ctxt", {}) + is_xml = kwargs.get("is_xml", False) + + serialized = [] + for d in data: + try: + serialized.append(self.serialize_data(d, iter_type, **kwargs)) + except ValueError: + serialized.append(None) + + if div: + serialized = ["" if s is None else str(s) for s in serialized] + serialized = div.join(serialized) + + if "xml" in serialization_ctxt or is_xml: + # XML serialization is more complicated + xml_desc = serialization_ctxt.get("xml", {}) + xml_name = xml_desc.get("name") + if not xml_name: + xml_name = serialization_ctxt["key"] + + # Create a wrap node if necessary (use the fact that Element and list have "append") + is_wrapped = xml_desc.get("wrapped", False) + node_name = xml_desc.get("itemsName", xml_name) + if is_wrapped: + final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + else: + final_result = [] + # All list elements to "local_node" + for el in serialized: + if isinstance(el, ET.Element): + el_node = el + else: + el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + if el is not None: # Otherwise it writes "None" :-p + el_node.text = str(el) + final_result.append(el_node) + return final_result + return serialized + + def serialize_dict(self, attr, dict_type, **kwargs): + """Serialize a dictionary of objects. + + :param dict attr: Object to be serialized. + :param str dict_type: Type of object in the dictionary. + :param bool required: Whether the objects in the dictionary must + not be None or empty. + :rtype: dict + """ + serialization_ctxt = kwargs.get("serialization_ctxt", {}) + serialized = {} + for key, value in attr.items(): + try: + serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) + except ValueError: + serialized[self.serialize_unicode(key)] = None + + if "xml" in serialization_ctxt: + # XML serialization is more complicated + xml_desc = serialization_ctxt["xml"] + xml_name = xml_desc["name"] + + final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + for key, value in serialized.items(): + ET.SubElement(final_result, key).text = value + return final_result + + return serialized + + def serialize_object(self, attr, **kwargs): + """Serialize a generic object. + This will be handled as a dictionary. If object passed in is not + a basic type (str, int, float, dict, list) it will simply be + cast to str. + + :param dict attr: Object to be serialized. + :rtype: dict or str + """ + if attr is None: + return None + if isinstance(attr, ET.Element): + return attr + obj_type = type(attr) + if obj_type in self.basic_types: + return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) + if obj_type is _long_type: + return self.serialize_long(attr) + if obj_type is unicode_str: + return self.serialize_unicode(attr) + if obj_type is datetime.datetime: + return self.serialize_iso(attr) + if obj_type is datetime.date: + return self.serialize_date(attr) + if obj_type is datetime.time: + return self.serialize_time(attr) + if obj_type is datetime.timedelta: + return self.serialize_duration(attr) + if obj_type is decimal.Decimal: + return self.serialize_decimal(attr) + + # If it's a model or I know this dependency, serialize as a Model + elif obj_type in self.dependencies.values() or isinstance(attr, Model): + return self._serialize(attr) + + if obj_type == dict: + serialized = {} + for key, value in attr.items(): + try: + serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) + except ValueError: + serialized[self.serialize_unicode(key)] = None + return serialized + + if obj_type == list: + serialized = [] + for obj in attr: + try: + serialized.append(self.serialize_object(obj, **kwargs)) + except ValueError: + pass + return serialized + return str(attr) + + @staticmethod + def serialize_enum(attr, enum_obj=None): + try: + result = attr.value + except AttributeError: + result = attr + try: + enum_obj(result) # type: ignore + return result + except ValueError: + for enum_value in enum_obj: # type: ignore + if enum_value.value.lower() == str(attr).lower(): + return enum_value.value + error = "{!r} is not valid value for enum {!r}" + raise SerializationError(error.format(attr, enum_obj)) + + @staticmethod + def serialize_bytearray(attr, **kwargs): + """Serialize bytearray into base-64 string. + + :param attr: Object to be serialized. + :rtype: str + """ + return b64encode(attr).decode() + + @staticmethod + def serialize_base64(attr, **kwargs): + """Serialize str into base-64 string. + + :param attr: Object to be serialized. + :rtype: str + """ + encoded = b64encode(attr).decode("ascii") + return encoded.strip("=").replace("+", "-").replace("/", "_") + + @staticmethod + def serialize_decimal(attr, **kwargs): + """Serialize Decimal object to float. + + :param attr: Object to be serialized. + :rtype: float + """ + return float(attr) + + @staticmethod + def serialize_long(attr, **kwargs): + """Serialize long (Py2) or int (Py3). + + :param attr: Object to be serialized. + :rtype: int/long + """ + return _long_type(attr) + + @staticmethod + def serialize_date(attr, **kwargs): + """Serialize Date object into ISO-8601 formatted string. + + :param Date attr: Object to be serialized. + :rtype: str + """ + if isinstance(attr, str): + attr = isodate.parse_date(attr) + t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) + return t + + @staticmethod + def serialize_time(attr, **kwargs): + """Serialize Time object into ISO-8601 formatted string. + + :param datetime.time attr: Object to be serialized. + :rtype: str + """ + if isinstance(attr, str): + attr = isodate.parse_time(attr) + t = "{:02}:{:02}:{:02}".format(attr.hour, attr.minute, attr.second) + if attr.microsecond: + t += ".{:02}".format(attr.microsecond) + return t + + @staticmethod + def serialize_duration(attr, **kwargs): + """Serialize TimeDelta object into ISO-8601 formatted string. + + :param TimeDelta attr: Object to be serialized. + :rtype: str + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + return isodate.duration_isoformat(attr) + + @staticmethod + def serialize_rfc(attr, **kwargs): + """Serialize Datetime object into RFC-1123 formatted string. + + :param Datetime attr: Object to be serialized. + :rtype: str + :raises: TypeError if format invalid. + """ + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + utc = attr.utctimetuple() + except AttributeError: + raise TypeError("RFC1123 object must be valid Datetime object.") + + return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( + Serializer.days[utc.tm_wday], + utc.tm_mday, + Serializer.months[utc.tm_mon], + utc.tm_year, + utc.tm_hour, + utc.tm_min, + utc.tm_sec, + ) + + @staticmethod + def serialize_iso(attr, **kwargs): + """Serialize Datetime object into ISO-8601 formatted string. + + :param Datetime attr: Object to be serialized. + :rtype: str + :raises: SerializationError if format invalid. + """ + if isinstance(attr, str): + attr = isodate.parse_datetime(attr) + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + utc = attr.utctimetuple() + if utc.tm_year > 9999 or utc.tm_year < 1: + raise OverflowError("Hit max or min date") + + microseconds = str(attr.microsecond).rjust(6, "0").rstrip("0").ljust(3, "0") + if microseconds: + microseconds = "." + microseconds + date = "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}".format( + utc.tm_year, utc.tm_mon, utc.tm_mday, utc.tm_hour, utc.tm_min, utc.tm_sec + ) + return date + microseconds + "Z" + except (ValueError, OverflowError) as err: + msg = "Unable to serialize datetime object." + raise_with_traceback(SerializationError, msg, err) + except AttributeError as err: + msg = "ISO-8601 object must be valid Datetime object." + raise_with_traceback(TypeError, msg, err) + + @staticmethod + def serialize_unix(attr, **kwargs): + """Serialize Datetime object into IntTime format. + This is represented as seconds. + + :param Datetime attr: Object to be serialized. + :rtype: int + :raises: SerializationError if format invalid + """ + if isinstance(attr, int): + return attr + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + return int(calendar.timegm(attr.utctimetuple())) + except AttributeError: + raise TypeError("Unix time object must be valid Datetime object.") + + +def rest_key_extractor(attr, attr_desc, data): + key = attr_desc["key"] + working_data = data + + while "." in key: + 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 # type: ignore + d_attrs = {} + for attr, attr_desc in attributes.items(): + # Check empty string. If it's not empty, someone has a real "additionalProperties"... + if attr == "additional_properties" and attr_desc["key"] == "": + continue + raw_value = None + # Enhance attr_desc with some dynamic data + attr_desc = attr_desc.copy() # Do a copy, do not change the real one + internal_data_type = attr_desc["type"].strip("[]{}") + if internal_data_type in self.dependencies: + attr_desc["internalType"] = self.dependencies[internal_data_type] + + for key_extractor in self.key_extractors: + found_value = key_extractor(attr, attr_desc, data) + if found_value is not None: + if raw_value is not None and raw_value != found_value: + msg = ( + "Ignoring extracted value '%s' from %s for key '%s'" + " (duplicate extraction, follow extractors order)" + ) + _LOGGER.warning(msg, found_value, key_extractor, attr) + continue + raw_value = found_value + + value = self.deserialize_data(raw_value, attr_desc["type"]) + d_attrs[attr] = value + except (AttributeError, TypeError, KeyError) as err: + msg = "Unable to deserialize to object: " + class_name # type: ignore + raise_with_traceback(DeserializationError, msg, err) + else: + additional_properties = self._build_additional_properties(attributes, data) + return self._instantiate_model(response, d_attrs, additional_properties) + + def _build_additional_properties(self, attribute_map, data): + if not self.additional_properties_detection: + return None + if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": + # Check empty string. If it's not empty, someone has a real "additionalProperties" + return None + if isinstance(data, ET.Element): + data = {el.tag: el.text for el in data} + + known_keys = { + _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) + for desc in attribute_map.values() + if desc["key"] != "" + } + present_keys = set(data.keys()) + missing_keys = present_keys - known_keys + return {key: data[key] for key in missing_keys} + + def _classify_target(self, target, data): + """Check to see whether the deserialization target object can + be classified into a subclass. + Once classification has been determined, initialize object. + + :param str target: The target object type to deserialize to. + :param str/dict data: The response data to 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) # type: ignore + return raw_data + + def _instantiate_model(self, response, attrs, additional_properties=None): + """Instantiate a response model passing in deserialized args. + + :param response: The response model class. + :param d_attrs: The deserialized response attributes. + """ + if callable(response): + subtype = getattr(response, "_subtype_map", {}) + try: + readonly = [k for k, v in response._validation.items() if v.get("readonly")] + const = [k for k, v in response._validation.items() if v.get("constant")] + kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} + response_obj = response(**kwargs) + for attr in readonly: + setattr(response_obj, attr, attrs.get(attr)) + if additional_properties: + response_obj.additional_properties = additional_properties + return response_obj + except TypeError as err: + msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) # type: ignore + raise DeserializationError(msg + str(err)) + else: + try: + for attr, value in attrs.items(): + setattr(response, attr, value) + return response + except Exception as exp: + msg = "Unable to populate response model. " + msg += "Type: {}, Error: {}".format(type(response), exp) + raise DeserializationError(msg) + + def deserialize_data(self, data, data_type): + """Process data for deserialization according to data type. + + :param str data: The response string to be deserialized. + :param str data_type: The type to deserialize to. + :raises: DeserializationError if deserialization fails. + :return: Deserialized object. + """ + if data is None: + return data + + try: + if not data_type: + return data + if data_type in self.basic_types.values(): + return self.deserialize_basic(data, data_type) + if data_type in self.deserialize_type: + if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): + return data + + is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] + if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: + return None + data_val = self.deserialize_type[data_type](data) + return data_val + + iter_type = data_type[0] + data_type[-1] + if iter_type in self.deserialize_type: + return self.deserialize_type[iter_type](data, data_type[1:-1]) + + obj_type = self.dependencies[data_type] + if issubclass(obj_type, Enum): + if isinstance(data, ET.Element): + data = data.text + return self.deserialize_enum(data, obj_type) + + except (ValueError, TypeError, AttributeError) as err: + msg = "Unable to deserialize response data." + msg += " Data: {}, {}".format(data, data_type) + raise_with_traceback(DeserializationError, msg, err) + else: + return self._deserialize(obj_type, data) + + def deserialize_iter(self, attr, iter_type): + """Deserialize an iterable. + + :param list attr: Iterable to be deserialized. + :param str iter_type: The type of object in the iterable. + :rtype: list + """ + if attr is None: + return None + if isinstance(attr, ET.Element): # If I receive an element here, get the children + attr = list(attr) + if not isinstance(attr, (list, set)): + raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) + return [self.deserialize_data(a, iter_type) for a in attr] + + def deserialize_dict(self, attr, dict_type): + """Deserialize a dictionary. + + :param dict/list attr: Dictionary to be deserialized. Also accepts + a list of key, value pairs. + :param str dict_type: The object type of the items in the dictionary. + :rtype: dict + """ + if isinstance(attr, list): + return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} + + if isinstance(attr, ET.Element): + # Transform value into {"Key": "value"} + attr = {el.tag: el.text for el in attr} + return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} + + def deserialize_object(self, attr, **kwargs): + """Deserialize a generic object. + This will be handled as a dictionary. + + :param dict attr: Dictionary to be deserialized. + :rtype: dict + :raises: TypeError if non-builtin datatype encountered. + """ + if attr is None: + return None + if isinstance(attr, ET.Element): + # Do no recurse on XML, just return the tree as-is + return attr + if isinstance(attr, basestring): + return self.deserialize_basic(attr, "str") + obj_type = type(attr) + if obj_type in self.basic_types: + return self.deserialize_basic(attr, self.basic_types[obj_type]) + if obj_type is _long_type: + return self.deserialize_long(attr) + + if obj_type == dict: + deserialized = {} + for key, value in attr.items(): + try: + deserialized[key] = self.deserialize_object(value, **kwargs) + except ValueError: + deserialized[key] = None + return deserialized + + if obj_type == list: + deserialized = [] + for obj in attr: + try: + deserialized.append(self.deserialize_object(obj, **kwargs)) + except ValueError: + pass + return deserialized + + else: + error = "Cannot deserialize generic object with type: " + raise TypeError(error + str(obj_type)) + + def deserialize_basic(self, attr, data_type): + """Deserialize basic builtin data type from string. + Will attempt to convert to str, int, float and bool. + This function will also accept '1', '0', 'true' and 'false' as + valid bool values. + + :param str attr: response string to be deserialized. + :param str data_type: deserialization data type. + :rtype: str, int, float or bool + :raises: TypeError if string format is not valid. + """ + # If we're here, data is supposed to be a basic type. + # If it's still an XML node, take the text + if isinstance(attr, ET.Element): + attr = attr.text + if not attr: + if data_type == "str": + # None or '', node is empty string. + return "" + else: + # None or '', node with a strong type is None. + # Don't try to model "empty bool" or "empty int" + return None + + if data_type == "bool": + if attr in [True, False, 1, 0]: + return bool(attr) + elif isinstance(attr, basestring): + if attr.lower() in ["true", "1"]: + return True + elif attr.lower() in ["false", "0"]: + return False + raise TypeError("Invalid boolean value: {}".format(attr)) + + if data_type == "str": + return self.deserialize_unicode(attr) + return eval(data_type)(attr) # nosec + + @staticmethod + def deserialize_unicode(data): + """Preserve unicode objects in Python 2, otherwise return data + as a string. + + :param str data: response string to be deserialized. + :rtype: str or unicode + """ + # We might be here because we have an enum modeled as string, + # and we try to deserialize a partial dict with enum inside + if isinstance(data, Enum): + return data + + # Consider this is real string + try: + if isinstance(data, unicode): # type: ignore + return data + except NameError: + return str(data) + else: + return str(data) + + @staticmethod + def deserialize_enum(data, enum_obj): + """Deserialize string into enum object. + + If the string is not a valid enum value it will be returned as-is + and a warning will be logged. + + :param str data: Response string to be deserialized. If this value is + None or invalid it will be returned as-is. + :param Enum enum_obj: Enum object to deserialize to. + :rtype: Enum + """ + if isinstance(data, enum_obj) or data is None: + return data + if isinstance(data, Enum): + data = data.value + if isinstance(data, int): + # Workaround. We might consider remove it in the future. + # https://github.com/Azure/azure-rest-api-specs/issues/141 + try: + return list(enum_obj.__members__.values())[data] + except IndexError: + error = "{!r} is not a valid index for enum {!r}" + raise DeserializationError(error.format(data, enum_obj)) + try: + return enum_obj(str(data)) + except ValueError: + for enum_value in enum_obj: + if enum_value.value.lower() == str(data).lower(): + return enum_value + # We don't fail anymore for unknown value, we deserialize as a string + _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) + return Deserializer.deserialize_unicode(data) + + @staticmethod + def deserialize_bytearray(attr): + """Deserialize string into bytearray. + + :param str attr: response string to be deserialized. + :rtype: bytearray + :raises: TypeError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + return bytearray(b64decode(attr)) # type: ignore + + @staticmethod + def deserialize_base64(attr): + """Deserialize base64 encoded string into string. + + :param str attr: response string to be deserialized. + :rtype: bytearray + :raises: TypeError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + padding = "=" * (3 - (len(attr) + 3) % 4) # type: ignore + attr = attr + padding # type: ignore + encoded = attr.replace("-", "+").replace("_", "/") + return b64decode(encoded) + + @staticmethod + def deserialize_decimal(attr): + """Deserialize string into Decimal object. + + :param str attr: response string to be deserialized. + :rtype: Decimal + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + return decimal.Decimal(attr) # type: ignore + except decimal.DecimalException as err: + msg = "Invalid decimal {}".format(attr) + raise_with_traceback(DeserializationError, msg, err) + + @staticmethod + def deserialize_long(attr): + """Deserialize string into long (Py2) or int (Py3). + + :param str attr: response string to be deserialized. + :rtype: long or int + :raises: ValueError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + return _long_type(attr) # type: ignore + + @staticmethod + def deserialize_duration(attr): + """Deserialize ISO-8601 formatted string into TimeDelta object. + + :param str attr: response string to be deserialized. + :rtype: TimeDelta + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = isodate.parse_duration(attr) + except (ValueError, OverflowError, AttributeError) as err: + msg = "Cannot deserialize duration object." + raise_with_traceback(DeserializationError, msg, err) + else: + return duration + + @staticmethod + def deserialize_date(attr): + """Deserialize ISO-8601 formatted string into Date object. + + :param str attr: response string to be deserialized. + :rtype: Date + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore + raise DeserializationError("Date must have only digits and -. Received: %s" % attr) + # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. + return isodate.parse_date(attr, defaultmonth=None, defaultday=None) + + @staticmethod + def deserialize_time(attr): + """Deserialize ISO-8601 formatted string into time object. + + :param str attr: response string to be deserialized. + :rtype: datetime.time + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore + raise DeserializationError("Date must have only digits and -. Received: %s" % attr) + return isodate.parse_time(attr) + + @staticmethod + def deserialize_rfc(attr): + """Deserialize RFC-1123 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: Datetime + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + parsed_date = email.utils.parsedate_tz(attr) # type: ignore + date_obj = datetime.datetime( + *parsed_date[:6], tzinfo=_FixedOffset(datetime.timedelta(minutes=(parsed_date[9] or 0) / 60)) + ) + if not date_obj.tzinfo: + date_obj = date_obj.astimezone(tz=TZ_UTC) + except ValueError as err: + msg = "Cannot deserialize to rfc datetime object." + raise_with_traceback(DeserializationError, msg, err) + else: + return date_obj + + @staticmethod + def deserialize_iso(attr): + """Deserialize ISO-8601 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: Datetime + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + attr = attr.upper() # type: ignore + match = Deserializer.valid_date.match(attr) + if not match: + raise ValueError("Invalid datetime string: " + attr) + + check_decimal = attr.split(".") + if len(check_decimal) > 1: + decimal_str = "" + for digit in check_decimal[1]: + if digit.isdigit(): + decimal_str += digit + else: + break + if len(decimal_str) > 6: + attr = attr.replace(decimal_str, decimal_str[0:6]) + + date_obj = isodate.parse_datetime(attr) + test_utc = date_obj.utctimetuple() + if test_utc.tm_year > 9999 or test_utc.tm_year < 1: + raise OverflowError("Hit max or min date") + except (ValueError, OverflowError, AttributeError) as err: + msg = "Cannot deserialize datetime object." + raise_with_traceback(DeserializationError, msg, err) + else: + return date_obj + + @staticmethod + def deserialize_unix(attr): + """Serialize Datetime object into IntTime format. + This is represented as seconds. + + :param int attr: Object to be serialized. + :rtype: Datetime + :raises: DeserializationError if format invalid + """ + if isinstance(attr, ET.Element): + attr = int(attr.text) # type: ignore + try: + date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) + except ValueError as err: + msg = "Cannot deserialize to unix datetime object." + raise_with_traceback(DeserializationError, msg, err) + else: + return date_obj diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/aio/_azure_digital_twins_management_client.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/aio/_azure_digital_twins_management_client.py index b15601ce9fcc6..c19d2e1904b2c 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/aio/_azure_digital_twins_management_client.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/aio/_azure_digital_twins_management_client.py @@ -11,17 +11,15 @@ from typing import Any, Optional, TYPE_CHECKING -from msrest import Deserializer, Serializer - from azure.mgmt.core import AsyncARMPipelineClient from azure.profiles import KnownProfiles, ProfileDefinition from azure.profiles.multiapiclient import MultiApiClientMixin +from .._serialization import Deserializer, Serializer from ._configuration import AzureDigitalTwinsManagementClientConfiguration if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports - from azure.core.credentials import TokenCredential from azure.core.credentials_async import AsyncTokenCredential class _SDKClient(object): @@ -42,9 +40,9 @@ class AzureDigitalTwinsManagementClient(MultiApiClientMixin, _SDKClient): The api-version parameter sets the default API version if the operation group is not described in the profile. - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: The subscription identifier. + :param subscription_id: The subscription identifier. Required. :type subscription_id: str :param api_version: API version to use if no profile is provided, or if missing in profile. :type api_version: str @@ -55,7 +53,7 @@ class AzureDigitalTwinsManagementClient(MultiApiClientMixin, _SDKClient): :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. """ - DEFAULT_API_VERSION = '2022-05-31' + DEFAULT_API_VERSION = '2022-10-31' _PROFILE_TAG = "azure.mgmt.digitaltwins.AzureDigitalTwinsManagementClient" LATEST_PROFILE = ProfileDefinition({ _PROFILE_TAG: { @@ -71,7 +69,7 @@ def __init__( api_version: Optional[str] = None, base_url: str = "https://management.azure.com", profile: KnownProfiles = KnownProfiles.default, - **kwargs # type: Any + **kwargs: Any ) -> None: self._config = AzureDigitalTwinsManagementClientConfiguration(credential, subscription_id, **kwargs) self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) @@ -93,6 +91,7 @@ def models(cls, api_version=DEFAULT_API_VERSION): * 2020-12-01: :mod:`v2020_12_01.models` * 2021-06-30-preview: :mod:`v2021_06_30_preview.models` * 2022-05-31: :mod:`v2022_05_31.models` + * 2022-10-31: :mod:`v2022_10_31.models` """ if api_version == '2020-03-01-preview': from ..v2020_03_01_preview import models @@ -109,6 +108,9 @@ def models(cls, api_version=DEFAULT_API_VERSION): elif api_version == '2022-05-31': from ..v2022_05_31 import models return models + elif api_version == '2022-10-31': + from ..v2022_10_31 import models + return models raise ValueError("API version {} is not available".format(api_version)) @property @@ -120,6 +122,7 @@ def digital_twins(self): * 2020-12-01: :class:`DigitalTwinsOperations` * 2021-06-30-preview: :class:`DigitalTwinsOperations` * 2022-05-31: :class:`DigitalTwinsOperations` + * 2022-10-31: :class:`DigitalTwinsOperations` """ api_version = self._get_api_version('digital_twins') if api_version == '2020-03-01-preview': @@ -132,8 +135,11 @@ def digital_twins(self): from ..v2021_06_30_preview.aio.operations import DigitalTwinsOperations as OperationClass elif api_version == '2022-05-31': from ..v2022_05_31.aio.operations import DigitalTwinsOperations as OperationClass + elif api_version == '2022-10-31': + from ..v2022_10_31.aio.operations import DigitalTwinsOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'digital_twins'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property @@ -145,6 +151,7 @@ def digital_twins_endpoint(self): * 2020-12-01: :class:`DigitalTwinsEndpointOperations` * 2021-06-30-preview: :class:`DigitalTwinsEndpointOperations` * 2022-05-31: :class:`DigitalTwinsEndpointOperations` + * 2022-10-31: :class:`DigitalTwinsEndpointOperations` """ api_version = self._get_api_version('digital_twins_endpoint') if api_version == '2020-03-01-preview': @@ -157,8 +164,11 @@ def digital_twins_endpoint(self): from ..v2021_06_30_preview.aio.operations import DigitalTwinsEndpointOperations as OperationClass elif api_version == '2022-05-31': from ..v2022_05_31.aio.operations import DigitalTwinsEndpointOperations as OperationClass + elif api_version == '2022-10-31': + from ..v2022_10_31.aio.operations import DigitalTwinsEndpointOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'digital_twins_endpoint'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property @@ -170,6 +180,7 @@ def operations(self): * 2020-12-01: :class:`Operations` * 2021-06-30-preview: :class:`Operations` * 2022-05-31: :class:`Operations` + * 2022-10-31: :class:`Operations` """ api_version = self._get_api_version('operations') if api_version == '2020-03-01-preview': @@ -182,8 +193,11 @@ def operations(self): from ..v2021_06_30_preview.aio.operations import Operations as OperationClass elif api_version == '2022-05-31': from ..v2022_05_31.aio.operations import Operations as OperationClass + elif api_version == '2022-10-31': + from ..v2022_10_31.aio.operations import Operations as OperationClass else: raise ValueError("API version {} does not have operation group 'operations'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property @@ -193,6 +207,7 @@ def private_endpoint_connections(self): * 2020-12-01: :class:`PrivateEndpointConnectionsOperations` * 2021-06-30-preview: :class:`PrivateEndpointConnectionsOperations` * 2022-05-31: :class:`PrivateEndpointConnectionsOperations` + * 2022-10-31: :class:`PrivateEndpointConnectionsOperations` """ api_version = self._get_api_version('private_endpoint_connections') if api_version == '2020-12-01': @@ -201,8 +216,11 @@ def private_endpoint_connections(self): from ..v2021_06_30_preview.aio.operations import PrivateEndpointConnectionsOperations as OperationClass elif api_version == '2022-05-31': from ..v2022_05_31.aio.operations import PrivateEndpointConnectionsOperations as OperationClass + elif api_version == '2022-10-31': + from ..v2022_10_31.aio.operations import PrivateEndpointConnectionsOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'private_endpoint_connections'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property @@ -212,6 +230,7 @@ def private_link_resources(self): * 2020-12-01: :class:`PrivateLinkResourcesOperations` * 2021-06-30-preview: :class:`PrivateLinkResourcesOperations` * 2022-05-31: :class:`PrivateLinkResourcesOperations` + * 2022-10-31: :class:`PrivateLinkResourcesOperations` """ api_version = self._get_api_version('private_link_resources') if api_version == '2020-12-01': @@ -220,8 +239,11 @@ def private_link_resources(self): from ..v2021_06_30_preview.aio.operations import PrivateLinkResourcesOperations as OperationClass elif api_version == '2022-05-31': from ..v2022_05_31.aio.operations import PrivateLinkResourcesOperations as OperationClass + elif api_version == '2022-10-31': + from ..v2022_10_31.aio.operations import PrivateLinkResourcesOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'private_link_resources'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) @property @@ -230,14 +252,18 @@ def time_series_database_connections(self): * 2021-06-30-preview: :class:`TimeSeriesDatabaseConnectionsOperations` * 2022-05-31: :class:`TimeSeriesDatabaseConnectionsOperations` + * 2022-10-31: :class:`TimeSeriesDatabaseConnectionsOperations` """ api_version = self._get_api_version('time_series_database_connections') if api_version == '2021-06-30-preview': from ..v2021_06_30_preview.aio.operations import TimeSeriesDatabaseConnectionsOperations as OperationClass elif api_version == '2022-05-31': from ..v2022_05_31.aio.operations import TimeSeriesDatabaseConnectionsOperations as OperationClass + elif api_version == '2022-10-31': + from ..v2022_10_31.aio.operations import TimeSeriesDatabaseConnectionsOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'time_series_database_connections'".format(api_version)) + self._config.api_version = api_version return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) async def close(self): diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/aio/_configuration.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/aio/_configuration.py index f939a52d1443e..2da0dcb0a8aa8 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/aio/_configuration.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/aio/_configuration.py @@ -26,9 +26,9 @@ class AzureDigitalTwinsManagementClientConfiguration(Configuration): Note that all parameters used to create this instance are saved as instance attributes. - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: The subscription identifier. + :param subscription_id: The subscription identifier. Required. :type subscription_id: str """ @@ -36,7 +36,7 @@ def __init__( self, credential: "AsyncTokenCredential", subscription_id: str, - **kwargs # type: Any + **kwargs: Any ) -> None: if credential is None: raise ValueError("Parameter 'credential' must not be None.") diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/models.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/models.py index 835ebd50bd3f3..5a61022de96a6 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/models.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/models.py @@ -4,4 +4,4 @@ # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- -from .v2022_05_31.models import * +from .v2022_10_31.models import * diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/__init__.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/__init__.py index 36b558a96cdfd..3d416a868dd25 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/__init__.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/__init__.py @@ -10,9 +10,17 @@ from ._version import VERSION __version__ = VERSION -__all__ = ['AzureDigitalTwinsManagementClient'] -# `._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 * # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "AzureDigitalTwinsManagementClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/_azure_digital_twins_management_client.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/_azure_digital_twins_management_client.py index 1113adf17a6c2..7be0cc594bb11 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/_azure_digital_twins_management_client.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/_azure_digital_twins_management_client.py @@ -9,12 +9,11 @@ from copy import deepcopy from typing import Any, TYPE_CHECKING -from msrest import Deserializer, Serializer - from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient -from . import models +from . import models as _models +from .._serialization import Deserializer, Serializer from ._configuration import AzureDigitalTwinsManagementClientConfiguration from .operations import DigitalTwinsEndpointOperations, DigitalTwinsOperations, Operations @@ -22,7 +21,8 @@ # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class AzureDigitalTwinsManagementClient: + +class AzureDigitalTwinsManagementClient: # pylint: disable=client-accepts-api-version-keyword """Azure Digital Twins Client for managing DigitalTwinsInstance. :ivar digital_twins: DigitalTwinsOperations operations @@ -33,9 +33,9 @@ class AzureDigitalTwinsManagementClient: azure.mgmt.digitaltwins.v2020_03_01_preview.operations.DigitalTwinsEndpointOperations :ivar operations: Operations operations :vartype operations: azure.mgmt.digitaltwins.v2020_03_01_preview.operations.Operations - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: The subscription identifier. + :param subscription_id: The subscription identifier. Required. :type subscription_id: str :param base_url: Service URL. Default value is "https://management.azure.com". :type base_url: str @@ -53,23 +53,22 @@ def __init__( base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: - self._config = AzureDigitalTwinsManagementClientConfiguration(credential=credential, subscription_id=subscription_id, **kwargs) + self._config = AzureDigitalTwinsManagementClientConfiguration( + credential=credential, subscription_id=subscription_id, **kwargs + ) self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) - client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) self._deserialize = Deserializer(client_models) self._serialize.client_side_validation = False self.digital_twins = DigitalTwinsOperations(self._client, self._config, self._serialize, self._deserialize) - self.digital_twins_endpoint = DigitalTwinsEndpointOperations(self._client, self._config, self._serialize, self._deserialize) + self.digital_twins_endpoint = DigitalTwinsEndpointOperations( + self._client, self._config, self._serialize, self._deserialize + ) self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) - - def _send_request( - self, - request: HttpRequest, - **kwargs: Any - ) -> HttpResponse: + 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 @@ -78,7 +77,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 @@ -91,15 +90,12 @@ def _send_request( request_copy.url = self._client.format_url(request_copy.url) return self._client.send_request(request_copy, **kwargs) - def close(self): - # type: () -> None + def close(self) -> None: self._client.close() - def __enter__(self): - # type: () -> AzureDigitalTwinsManagementClient + def __enter__(self) -> "AzureDigitalTwinsManagementClient": self._client.__enter__() return self - def __exit__(self, *exc_details): - # type: (Any) -> None + def __exit__(self, *exc_details) -> None: self._client.__exit__(*exc_details) diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/_configuration.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/_configuration.py index ac4e40e9b07aa..ec39bf7f644a3 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/_configuration.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/_configuration.py @@ -6,6 +6,7 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, TYPE_CHECKING from azure.core.configuration import Configuration @@ -14,6 +15,11 @@ from ._version import VERSION +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports + if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential @@ -25,23 +31,18 @@ class AzureDigitalTwinsManagementClientConfiguration(Configuration): # pylint: Note that all parameters used to create this instance are saved as instance attributes. - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: The subscription identifier. + :param subscription_id: The subscription identifier. Required. :type subscription_id: str :keyword api_version: Api Version. Default value is "2020-03-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(AzureDigitalTwinsManagementClientConfiguration, self).__init__(**kwargs) - api_version = kwargs.pop('api_version', "2020-03-01-preview") # type: str + api_version: Literal["2020-03-01-preview"] = kwargs.pop("api_version", "2020-03-01-preview") if credential is None: raise ValueError("Parameter 'credential' must not be None.") @@ -51,23 +52,21 @@ def __init__( self.credential = credential self.subscription_id = subscription_id self.api_version = api_version - self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'mgmt-digitaltwins/{}'.format(VERSION)) + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-digitaltwins/{}".format(VERSION)) self._configure(**kwargs) - def _configure( - self, - **kwargs # type: Any - ): - # type: (...) -> None - self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get('retry_policy') or policies.RetryPolicy(**kwargs) - self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get('redirect_policy') or policies.RedirectPolicy(**kwargs) - self.authentication_policy = kwargs.get('authentication_policy') + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: - self.authentication_policy = ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs) + self.authentication_policy = ARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/_metadata.json b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/_metadata.json index 7cb5856bc6708..44f92e7c1c115 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/_metadata.json +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/_metadata.json @@ -10,20 +10,20 @@ "azure_arm": true, "has_lro_operations": true, "client_side_validation": false, - "sync_imports": "{\"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}, \"regular\": {\"azurecore\": {\"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"], \"azure.mgmt.core\": [\"ARMPipelineClient\"]}, \"local\": {\"._configuration\": [\"AzureDigitalTwinsManagementClientConfiguration\"]}, \"thirdparty\": {\"msrest\": [\"Deserializer\", \"Serializer\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}}", - "async_imports": "{\"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"], \"azure.core.credentials\": [\"TokenCredential\"]}}, \"regular\": {\"azurecore\": {\"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"], \"azure.mgmt.core\": [\"AsyncARMPipelineClient\"]}, \"local\": {\"._configuration\": [\"AzureDigitalTwinsManagementClientConfiguration\"]}, \"thirdparty\": {\"msrest\": [\"Deserializer\", \"Serializer\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}}" + "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"AzureDigitalTwinsManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"AzureDigitalTwinsManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "global_parameters": { "sync": { "credential": { - "signature": "credential, # type: \"TokenCredential\"", - "description": "Credential needed for the client to connect to Azure.", + "signature": "credential: \"TokenCredential\",", + "description": "Credential needed for the client to connect to Azure. Required.", "docstring_type": "~azure.core.credentials.TokenCredential", "required": true }, "subscription_id": { - "signature": "subscription_id, # type: str", - "description": "The subscription identifier.", + "signature": "subscription_id: str,", + "description": "The subscription identifier. Required.", "docstring_type": "str", "required": true } @@ -31,13 +31,13 @@ "async": { "credential": { "signature": "credential: \"AsyncTokenCredential\",", - "description": "Credential needed for the client to connect to Azure.", + "description": "Credential needed for the client to connect to Azure. Required.", "docstring_type": "~azure.core.credentials_async.AsyncTokenCredential", "required": true }, "subscription_id": { "signature": "subscription_id: str,", - "description": "The subscription identifier.", + "description": "The subscription identifier. Required.", "docstring_type": "str", "required": true } @@ -48,19 +48,19 @@ "service_client_specific": { "sync": { "api_version": { - "signature": "api_version=None, # type: Optional[str]", + "signature": "api_version: Optional[str]=None,", "description": "API version to use if no profile is provided, or if missing in profile.", "docstring_type": "str", "required": false }, "base_url": { - "signature": "base_url=\"https://management.azure.com\", # type: str", + "signature": "base_url: str = \"https://management.azure.com\",", "description": "Service URL", "docstring_type": "str", "required": false }, "profile": { - "signature": "profile=KnownProfiles.default, # type: KnownProfiles", + "signature": "profile: KnownProfiles=KnownProfiles.default,", "description": "A profile definition, from KnownProfiles to dict.", "docstring_type": "azure.profiles.KnownProfiles", "required": false @@ -101,4 +101,4 @@ "digital_twins_endpoint": "DigitalTwinsEndpointOperations", "operations": "Operations" } -} \ No newline at end of file +} diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/_patch.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/_patch.py index 74e48ecd07cf3..f99e77fef9861 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/_patch.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/_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/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/_vendor.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/_vendor.py index 138f663c53a4e..9aad73fc743e7 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/_vendor.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/_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/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/_version.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/_version.py index a55d01326aa81..e5754a47ce68f 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/_version.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "6.2.0" +VERSION = "1.0.0b1" diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/aio/__init__.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/aio/__init__.py index 20a6435cbbdb2..e4da5a5dc30c1 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/aio/__init__.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/aio/__init__.py @@ -7,9 +7,17 @@ # -------------------------------------------------------------------------- from ._azure_digital_twins_management_client import AzureDigitalTwinsManagementClient -__all__ = ['AzureDigitalTwinsManagementClient'] -# `._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 * # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "AzureDigitalTwinsManagementClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/aio/_azure_digital_twins_management_client.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/aio/_azure_digital_twins_management_client.py index 5c2709b53f278..a560dd0313f38 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/aio/_azure_digital_twins_management_client.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/aio/_azure_digital_twins_management_client.py @@ -9,12 +9,11 @@ from copy import deepcopy from typing import Any, Awaitable, TYPE_CHECKING -from msrest import Deserializer, Serializer - from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient -from .. import models +from .. import models as _models +from ..._serialization import Deserializer, Serializer from ._configuration import AzureDigitalTwinsManagementClientConfiguration from .operations import DigitalTwinsEndpointOperations, DigitalTwinsOperations, Operations @@ -22,7 +21,8 @@ # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class AzureDigitalTwinsManagementClient: + +class AzureDigitalTwinsManagementClient: # pylint: disable=client-accepts-api-version-keyword """Azure Digital Twins Client for managing DigitalTwinsInstance. :ivar digital_twins: DigitalTwinsOperations operations @@ -33,9 +33,9 @@ class AzureDigitalTwinsManagementClient: azure.mgmt.digitaltwins.v2020_03_01_preview.aio.operations.DigitalTwinsEndpointOperations :ivar operations: Operations operations :vartype operations: azure.mgmt.digitaltwins.v2020_03_01_preview.aio.operations.Operations - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: The subscription identifier. + :param subscription_id: The subscription identifier. Required. :type subscription_id: str :param base_url: Service URL. Default value is "https://management.azure.com". :type base_url: str @@ -53,23 +53,22 @@ def __init__( base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: - self._config = AzureDigitalTwinsManagementClientConfiguration(credential=credential, subscription_id=subscription_id, **kwargs) + self._config = AzureDigitalTwinsManagementClientConfiguration( + credential=credential, subscription_id=subscription_id, **kwargs + ) self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) - client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) self._deserialize = Deserializer(client_models) self._serialize.client_side_validation = False self.digital_twins = DigitalTwinsOperations(self._client, self._config, self._serialize, self._deserialize) - self.digital_twins_endpoint = DigitalTwinsEndpointOperations(self._client, self._config, self._serialize, self._deserialize) + self.digital_twins_endpoint = DigitalTwinsEndpointOperations( + self._client, self._config, self._serialize, self._deserialize + ) self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) - - def _send_request( - self, - request: HttpRequest, - **kwargs: Any - ) -> Awaitable[AsyncHttpResponse]: + 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 @@ -78,7 +77,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/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/aio/_configuration.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/aio/_configuration.py index e9b9559297ff2..5debe005e234d 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/aio/_configuration.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/aio/_configuration.py @@ -6,6 +6,7 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, TYPE_CHECKING from azure.core.configuration import Configuration @@ -14,6 +15,11 @@ from .._version import VERSION +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports + if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential @@ -25,23 +31,18 @@ class AzureDigitalTwinsManagementClientConfiguration(Configuration): # pylint: Note that all parameters used to create this instance are saved as instance attributes. - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: The subscription identifier. + :param subscription_id: The subscription identifier. Required. :type subscription_id: str :keyword api_version: Api Version. Default value is "2020-03-01-preview". Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str """ - def __init__( - self, - credential: "AsyncTokenCredential", - subscription_id: str, - **kwargs: Any - ) -> None: + def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: super(AzureDigitalTwinsManagementClientConfiguration, self).__init__(**kwargs) - api_version = kwargs.pop('api_version', "2020-03-01-preview") # type: str + api_version: Literal["2020-03-01-preview"] = kwargs.pop("api_version", "2020-03-01-preview") if credential is None: raise ValueError("Parameter 'credential' must not be None.") @@ -51,22 +52,21 @@ def __init__( self.credential = credential self.subscription_id = subscription_id self.api_version = api_version - self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'mgmt-digitaltwins/{}'.format(VERSION)) + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-digitaltwins/{}".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/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/aio/_patch.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/aio/_patch.py index 74e48ecd07cf3..f99e77fef9861 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/aio/_patch.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/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/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/aio/operations/__init__.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/aio/operations/__init__.py index a9cda9c99062e..a2f402ab0c76f 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/aio/operations/__init__.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/aio/operations/__init__.py @@ -10,8 +10,14 @@ from ._digital_twins_endpoint_operations import DigitalTwinsEndpointOperations from ._operations import Operations +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + __all__ = [ - 'DigitalTwinsOperations', - 'DigitalTwinsEndpointOperations', - 'Operations', + "DigitalTwinsOperations", + "DigitalTwinsEndpointOperations", + "Operations", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/aio/operations/_digital_twins_endpoint_operations.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/aio/operations/_digital_twins_endpoint_operations.py index dc101f870178b..f10f6650296d9 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/aio/operations/_digital_twins_endpoint_operations.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/aio/operations/_digital_twins_endpoint_operations.py @@ -6,96 +6,126 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar, Union +import sys +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models from ..._vendor import _convert_request -from ...operations._digital_twins_endpoint_operations import build_create_or_update_request_initial, build_delete_request_initial, build_get_request, build_list_request -T = TypeVar('T') +from ...operations._digital_twins_endpoint_operations import ( + build_create_or_update_request, + build_delete_request, + build_get_request, + build_list_request, +) + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class DigitalTwinsEndpointOperations: - """DigitalTwinsEndpointOperations 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 DigitalTwinsEndpointOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.digitaltwins.v2020_03_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.digitaltwins.v2020_03_01_preview.aio.AzureDigitalTwinsManagementClient`'s + :attr:`digital_twins_endpoint` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list( - self, - resource_group_name: str, - resource_name: str, - **kwargs: Any - ) -> AsyncIterable["_models.DigitalTwinsEndpointResourceListResult"]: + self, resource_group_name: str, resource_name: str, **kwargs: Any + ) -> AsyncIterable["_models.DigitalTwinsEndpointResource"]: """Get DigitalTwinsInstance Endpoints. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either DigitalTwinsEndpointResourceListResult or the - result of cls(response) + :return: An iterator like instance of either DigitalTwinsEndpointResource or the result of + cls(response) :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.digitaltwins.v2020_03_01_preview.models.DigitalTwinsEndpointResourceListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.digitaltwins.v2020_03_01_preview.models.DigitalTwinsEndpointResource] + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2020-03-01-preview") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2020-03-01-preview") + ) + cls: ClsType[_models.DigitalTwinsEndpointResourceListResult] = kwargs.pop("cls", None) - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsEndpointResourceListResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list.metadata['url'], + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: - - request = build_list_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - resource_name=resource_name, - api_version=api_version, - template_url=next_link, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) @@ -106,16 +136,14 @@ async def extract_data(pipeline_response): deserialized = self._deserialize("DigitalTwinsEndpointResourceListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -126,59 +154,63 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints"} # type: ignore + list.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints" + } @distributed_trace_async async def get( - self, - resource_group_name: str, - resource_name: str, - endpoint_name: str, - **kwargs: Any - ) -> "_models.DigitalTwinsEndpointResource": + self, resource_group_name: str, resource_name: str, endpoint_name: str, **kwargs: Any + ) -> _models.DigitalTwinsEndpointResource: """Get DigitalTwinsInstances Endpoint. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param endpoint_name: Name of Endpoint Resource. + :param endpoint_name: Name of Endpoint Resource. Required. :type endpoint_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: DigitalTwinsEndpointResource, or the result of cls(response) + :return: DigitalTwinsEndpointResource or the result of cls(response) :rtype: ~azure.mgmt.digitaltwins.v2020_03_01_preview.models.DigitalTwinsEndpointResource - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsEndpointResource"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2020-03-01-preview") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2020-03-01-preview") + ) + cls: ClsType[_models.DigitalTwinsEndpointResource] = kwargs.pop("cls", None) - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, endpoint_name=endpoint_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -186,72 +218,174 @@ async def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('DigitalTwinsEndpointResource', pipeline_response) + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}"} # type: ignore - + get.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}" + } async def _create_or_update_initial( self, resource_group_name: str, resource_name: str, endpoint_name: str, - endpoint_description: "_models.DigitalTwinsEndpointResource", + endpoint_description: Union[_models.DigitalTwinsEndpointResource, IO], **kwargs: Any - ) -> "_models.DigitalTwinsEndpointResource": - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsEndpointResource"] + ) -> _models.DigitalTwinsEndpointResource: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2020-03-01-preview") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(endpoint_description, 'DigitalTwinsEndpointResource') - - request = build_create_or_update_request_initial( - subscription_id=self._config.subscription_id, + api_version: Literal["2020-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2020-03-01-preview") + ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DigitalTwinsEndpointResource] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(endpoint_description, (IO, bytes)): + _content = endpoint_description + else: + _json = self._serialize.body(endpoint_description, "DigitalTwinsEndpointResource") + + request = build_create_or_update_request( resource_group_name=resource_group_name, resource_name=resource_name, 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_initial.metadata['url'], + content=_content, + template_url=self._create_or_update_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('DigitalTwinsEndpointResource', pipeline_response) + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('DigitalTwinsEndpointResource', pipeline_response) + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized + return deserialized # type: ignore + + _create_or_update_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}" + } + + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + endpoint_name: str, + endpoint_description: _models.DigitalTwinsEndpointResource, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.DigitalTwinsEndpointResource]: + """Create or update DigitalTwinsInstance endpoint. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param endpoint_name: Name of Endpoint Resource. Required. + :type endpoint_name: str + :param endpoint_description: The DigitalTwinsInstance endpoint metadata and security metadata. + Required. + :type endpoint_description: + ~azure.mgmt.digitaltwins.v2020_03_01_preview.models.DigitalTwinsEndpointResource + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either DigitalTwinsEndpointResource or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2020_03_01_preview.models.DigitalTwinsEndpointResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ - _create_or_update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}"} # type: ignore + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + endpoint_name: str, + endpoint_description: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.DigitalTwinsEndpointResource]: + """Create or update DigitalTwinsInstance endpoint. + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param endpoint_name: Name of Endpoint Resource. Required. + :type endpoint_name: str + :param endpoint_description: The DigitalTwinsInstance endpoint metadata and security metadata. + Required. + :type endpoint_description: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either DigitalTwinsEndpointResource or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2020_03_01_preview.models.DigitalTwinsEndpointResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace_async async def begin_create_or_update( @@ -259,21 +393,25 @@ async def begin_create_or_update( resource_group_name: str, resource_name: str, endpoint_name: str, - endpoint_description: "_models.DigitalTwinsEndpointResource", + endpoint_description: Union[_models.DigitalTwinsEndpointResource, IO], **kwargs: Any - ) -> AsyncLROPoller["_models.DigitalTwinsEndpointResource"]: + ) -> AsyncLROPoller[_models.DigitalTwinsEndpointResource]: """Create or update DigitalTwinsInstance endpoint. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param endpoint_name: Name of Endpoint Resource. + :param endpoint_name: Name of Endpoint Resource. Required. :type endpoint_name: str :param endpoint_description: The DigitalTwinsInstance endpoint metadata and security metadata. + Is either a model type or a IO type. Required. :type endpoint_description: - ~azure.mgmt.digitaltwins.v2020_03_01_preview.models.DigitalTwinsEndpointResource + ~azure.mgmt.digitaltwins.v2020_03_01_preview.models.DigitalTwinsEndpointResource or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for @@ -286,17 +424,19 @@ async def begin_create_or_update( result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2020_03_01_preview.models.DigitalTwinsEndpointResource] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2020-03-01-preview") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsEndpointResource"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2020-03-01-preview") ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DigitalTwinsEndpointResource] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = await self._create_or_update_initial( resource_group_name=resource_group_name, @@ -305,99 +445,106 @@ async def begin_create_or_update( endpoint_description=endpoint_description, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('DigitalTwinsEndpointResource', pipeline_response) + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - begin_create_or_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}"} # type: ignore + begin_create_or_update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}" + } async def _delete_initial( - self, - resource_group_name: str, - resource_name: str, - endpoint_name: str, - **kwargs: Any - ) -> Optional["_models.DigitalTwinsEndpointResource"]: - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.DigitalTwinsEndpointResource"]] + self, resource_group_name: str, resource_name: str, endpoint_name: str, **kwargs: Any + ) -> Optional[_models.DigitalTwinsEndpointResource]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2020-03-01-preview") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - request = build_delete_request_initial( - subscription_id=self._config.subscription_id, + api_version: Literal["2020-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2020-03-01-preview") + ) + cls: ClsType[Optional[_models.DigitalTwinsEndpointResource]] = kwargs.pop("cls", None) + + request = build_delete_request( resource_group_name=resource_group_name, resource_name=resource_name, endpoint_name=endpoint_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._delete_initial.metadata['url'], + template_url=self._delete_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 202: - deserialized = self._deserialize('DigitalTwinsEndpointResource', pipeline_response) + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _delete_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}"} # type: ignore - + _delete_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}" + } @distributed_trace_async async def begin_delete( - self, - resource_group_name: str, - resource_name: str, - endpoint_name: str, - **kwargs: Any - ) -> AsyncLROPoller["_models.DigitalTwinsEndpointResource"]: + self, resource_group_name: str, resource_name: str, endpoint_name: str, **kwargs: Any + ) -> AsyncLROPoller[None]: """Delete a DigitalTwinsInstance endpoint. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param endpoint_name: Name of Endpoint Resource. + :param endpoint_name: Name of Endpoint Resource. Required. :type endpoint_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. @@ -411,45 +558,52 @@ async def begin_delete( result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2020_03_01_preview.models.DigitalTwinsEndpointResource] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2020-03-01-preview") # type: str - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsEndpointResource"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2020-03-01-preview") ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = await self._delete_initial( resource_group_name=resource_group_name, resource_name=resource_name, endpoint_name=endpoint_name, api_version=api_version, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('DigitalTwinsEndpointResource', pipeline_response) + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - begin_delete.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}"} # type: ignore + begin_delete.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}" + } diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/aio/operations/_digital_twins_operations.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/aio/operations/_digital_twins_operations.py index c7e7719838408..880be3a75e371 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/aio/operations/_digital_twins_operations.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/aio/operations/_digital_twins_operations.py @@ -6,90 +6,114 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar, Union +import sys +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models from ..._vendor import _convert_request -from ...operations._digital_twins_operations import build_check_name_availability_request, build_create_or_update_request_initial, build_delete_request_initial, build_get_request, build_list_by_resource_group_request, build_list_request, build_update_request_initial -T = TypeVar('T') +from ...operations._digital_twins_operations import ( + build_check_name_availability_request, + build_create_or_update_request, + build_delete_request, + build_get_request, + build_list_by_resource_group_request, + build_list_request, + build_update_request, +) + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class DigitalTwinsOperations: - """DigitalTwinsOperations 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 DigitalTwinsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.digitaltwins.v2020_03_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.digitaltwins.v2020_03_01_preview.aio.AzureDigitalTwinsManagementClient`'s + :attr:`digital_twins` 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, - resource_group_name: str, - resource_name: str, - **kwargs: Any - ) -> "_models.DigitalTwinsDescription": + async def get(self, resource_group_name: str, resource_name: str, **kwargs: Any) -> _models.DigitalTwinsDescription: """Get DigitalTwinsInstances resource. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: DigitalTwinsDescription, or the result of cls(response) + :return: DigitalTwinsDescription or the result of cls(response) :rtype: ~azure.mgmt.digitaltwins.v2020_03_01_preview.models.DigitalTwinsDescription - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescription"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2020-03-01-preview") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2020-03-01-preview") + ) + cls: ClsType[_models.DigitalTwinsDescription] = kwargs.pop("cls", None) - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -97,91 +121,193 @@ async def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}"} # type: ignore - + get.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } async def _create_or_update_initial( self, resource_group_name: str, resource_name: str, - digital_twins_create: "_models.DigitalTwinsDescription", + digital_twins_create: Union[_models.DigitalTwinsDescription, IO], **kwargs: Any - ) -> "_models.DigitalTwinsDescription": - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescription"] + ) -> _models.DigitalTwinsDescription: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - api_version = kwargs.pop('api_version', "2020-03-01-preview") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + error_map.update(kwargs.pop("error_map", {}) or {}) - _json = self._serialize.body(digital_twins_create, 'DigitalTwinsDescription') + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - request = build_create_or_update_request_initial( - subscription_id=self._config.subscription_id, + api_version: Literal["2020-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2020-03-01-preview") + ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DigitalTwinsDescription] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(digital_twins_create, (IO, bytes)): + _content = digital_twins_create + else: + _json = self._serialize.body(digital_twins_create, "DigitalTwinsDescription") + + request = build_create_or_update_request( resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._create_or_update_initial.metadata['url'], + content=_content, + template_url=self._create_or_update_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized + return deserialized # type: ignore + + _create_or_update_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } - _create_or_update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}"} # type: ignore + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + digital_twins_create: _models.DigitalTwinsDescription, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.DigitalTwinsDescription]: + """Create or update the metadata of a DigitalTwinsInstance. The usual pattern to modify a property + is to retrieve the DigitalTwinsInstance and security metadata, and then combine them with the + modified values in a new body to update the DigitalTwinsInstance. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param digital_twins_create: The DigitalTwinsInstance and security metadata. Required. + :type digital_twins_create: + ~azure.mgmt.digitaltwins.v2020_03_01_preview.models.DigitalTwinsDescription + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either DigitalTwinsDescription or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2020_03_01_preview.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + digital_twins_create: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.DigitalTwinsDescription]: + """Create or update the metadata of a DigitalTwinsInstance. The usual pattern to modify a property + is to retrieve the DigitalTwinsInstance and security metadata, and then combine them with the + modified values in a new body to update the DigitalTwinsInstance. + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param digital_twins_create: The DigitalTwinsInstance and security metadata. Required. + :type digital_twins_create: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either DigitalTwinsDescription or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2020_03_01_preview.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace_async async def begin_create_or_update( self, resource_group_name: str, resource_name: str, - digital_twins_create: "_models.DigitalTwinsDescription", + digital_twins_create: Union[_models.DigitalTwinsDescription, IO], **kwargs: Any - ) -> AsyncLROPoller["_models.DigitalTwinsDescription"]: + ) -> AsyncLROPoller[_models.DigitalTwinsDescription]: """Create or update the metadata of a DigitalTwinsInstance. The usual pattern to modify a property is to retrieve the DigitalTwinsInstance and security metadata, and then combine them with the modified values in a new body to update the DigitalTwinsInstance. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param digital_twins_create: The DigitalTwinsInstance and security metadata. + :param digital_twins_create: The DigitalTwinsInstance and security metadata. Is either a model + type or a IO type. Required. :type digital_twins_create: - ~azure.mgmt.digitaltwins.v2020_03_01_preview.models.DigitalTwinsDescription + ~azure.mgmt.digitaltwins.v2020_03_01_preview.models.DigitalTwinsDescription or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for @@ -194,17 +320,19 @@ async def begin_create_or_update( result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2020_03_01_preview.models.DigitalTwinsDescription] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2020-03-01-preview") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescription"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2020-03-01-preview") ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DigitalTwinsDescription] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = await self._create_or_update_initial( resource_group_name=resource_group_name, @@ -212,104 +340,171 @@ async def begin_create_or_update( digital_twins_create=digital_twins_create, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - begin_create_or_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}"} # type: ignore + begin_create_or_update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } async def _update_initial( self, resource_group_name: str, resource_name: str, - digital_twins_patch_description: "_models.DigitalTwinsPatchDescription", + digital_twins_patch_description: Union[_models.DigitalTwinsPatchDescription, IO], **kwargs: Any - ) -> Optional["_models.DigitalTwinsDescription"]: - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.DigitalTwinsDescription"]] + ) -> Optional[_models.DigitalTwinsDescription]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - api_version = kwargs.pop('api_version', "2020-03-01-preview") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + error_map.update(kwargs.pop("error_map", {}) or {}) - _json = self._serialize.body(digital_twins_patch_description, 'DigitalTwinsPatchDescription') + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - request = build_update_request_initial( - subscription_id=self._config.subscription_id, + api_version: Literal["2020-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2020-03-01-preview") + ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Optional[_models.DigitalTwinsDescription]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(digital_twins_patch_description, (IO, bytes)): + _content = digital_twins_patch_description + else: + _json = self._serialize.body(digital_twins_patch_description, "DigitalTwinsPatchDescription") + + request = build_update_request( resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._update_initial.metadata['url'], + content=_content, + template_url=self._update_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}"} # type: ignore - + _update_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } - @distributed_trace_async + @overload async def begin_update( self, resource_group_name: str, resource_name: str, - digital_twins_patch_description: "_models.DigitalTwinsPatchDescription", + digital_twins_patch_description: _models.DigitalTwinsPatchDescription, + *, + content_type: str = "application/json", **kwargs: Any - ) -> AsyncLROPoller["_models.DigitalTwinsDescription"]: + ) -> AsyncLROPoller[_models.DigitalTwinsDescription]: """Update metadata of DigitalTwinsInstance. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str :param digital_twins_patch_description: The DigitalTwinsInstance and security metadata. + Required. :type digital_twins_patch_description: ~azure.mgmt.digitaltwins.v2020_03_01_preview.models.DigitalTwinsPatchDescription + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either DigitalTwinsDescription or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2020_03_01_preview.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_update( + self, + resource_group_name: str, + resource_name: str, + digital_twins_patch_description: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.DigitalTwinsDescription]: + """Update metadata of DigitalTwinsInstance. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param digital_twins_patch_description: The DigitalTwinsInstance and security metadata. + Required. + :type digital_twins_patch_description: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for @@ -322,17 +517,56 @@ async def begin_update( result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2020_03_01_preview.models.DigitalTwinsDescription] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2020-03-01-preview") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescription"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval + + @distributed_trace_async + async def begin_update( + self, + resource_group_name: str, + resource_name: str, + digital_twins_patch_description: Union[_models.DigitalTwinsPatchDescription, IO], + **kwargs: Any + ) -> AsyncLROPoller[_models.DigitalTwinsDescription]: + """Update metadata of DigitalTwinsInstance. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param digital_twins_patch_description: The DigitalTwinsInstance and security metadata. Is + either a model type or a IO type. Required. + :type digital_twins_patch_description: + ~azure.mgmt.digitaltwins.v2020_03_01_preview.models.DigitalTwinsPatchDescription or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either DigitalTwinsDescription or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2020_03_01_preview.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2020-03-01-preview") ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DigitalTwinsDescription] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = await self._update_initial( resource_group_name=resource_group_name, @@ -340,94 +574,101 @@ async def begin_update( digital_twins_patch_description=digital_twins_patch_description, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - begin_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}"} # type: ignore + begin_update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } async def _delete_initial( - self, - resource_group_name: str, - resource_name: str, - **kwargs: Any - ) -> Optional["_models.DigitalTwinsDescription"]: - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.DigitalTwinsDescription"]] + self, resource_group_name: str, resource_name: str, **kwargs: Any + ) -> Optional[_models.DigitalTwinsDescription]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2020-03-01-preview") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - request = build_delete_request_initial( - subscription_id=self._config.subscription_id, + api_version: Literal["2020-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2020-03-01-preview") + ) + cls: ClsType[Optional[_models.DigitalTwinsDescription]] = kwargs.pop("cls", None) + + request = build_delete_request( resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._delete_initial.metadata['url'], + template_url=self._delete_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 202: - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _delete_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}"} # type: ignore - + _delete_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } @distributed_trace_async - async def begin_delete( - self, - resource_group_name: str, - resource_name: str, - **kwargs: Any - ) -> AsyncLROPoller["_models.DigitalTwinsDescription"]: + async def begin_delete(self, resource_group_name: str, resource_name: str, **kwargs: Any) -> AsyncLROPoller[None]: """Delete a DigitalTwinsInstance. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. @@ -441,86 +682,107 @@ async def begin_delete( result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2020_03_01_preview.models.DigitalTwinsDescription] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2020-03-01-preview") # type: str - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescription"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2020-03-01-preview") ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = await self._delete_initial( resource_group_name=resource_group_name, resource_name=resource_name, api_version=api_version, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - begin_delete.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}"} # type: ignore + begin_delete.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } @distributed_trace - def list( - self, - **kwargs: Any - ) -> AsyncIterable["_models.DigitalTwinsDescriptionListResult"]: + def list(self, **kwargs: Any) -> AsyncIterable["_models.DigitalTwinsDescription"]: """Get all the DigitalTwinsInstances in a subscription. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either DigitalTwinsDescriptionListResult or the result of + :return: An iterator like instance of either DigitalTwinsDescription or the result of cls(response) :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.digitaltwins.v2020_03_01_preview.models.DigitalTwinsDescriptionListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.digitaltwins.v2020_03_01_preview.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2020-03-01-preview") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2020-03-01-preview") + ) + cls: ClsType[_models.DigitalTwinsDescriptionListResult] = kwargs.pop("cls", None) - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescriptionListResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list.metadata['url'], + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: - - request = build_list_request( - subscription_id=self._config.subscription_id, - api_version=api_version, - template_url=next_link, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) @@ -531,16 +793,14 @@ async def extract_data(pipeline_response): deserialized = self._deserialize("DigitalTwinsDescriptionListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -551,56 +811,68 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.DigitalTwins/digitalTwinsInstances"} # type: ignore + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.DigitalTwins/digitalTwinsInstances"} @distributed_trace def list_by_resource_group( - self, - resource_group_name: str, - **kwargs: Any - ) -> AsyncIterable["_models.DigitalTwinsDescriptionListResult"]: + self, resource_group_name: str, **kwargs: Any + ) -> AsyncIterable["_models.DigitalTwinsDescription"]: """Get all the DigitalTwinsInstances in a resource group. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. 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 DigitalTwinsDescriptionListResult or the result of + :return: An iterator like instance of either DigitalTwinsDescription or the result of cls(response) :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.digitaltwins.v2020_03_01_preview.models.DigitalTwinsDescriptionListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.digitaltwins.v2020_03_01_preview.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2020-03-01-preview") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2020-03-01-preview") + ) + cls: ClsType[_models.DigitalTwinsDescriptionListResult] = kwargs.pop("cls", None) - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescriptionListResult"] 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( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata['url'], + template_url=self.list_by_resource_group.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: - - request = build_list_by_resource_group_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - api_version=api_version, - template_url=next_link, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) @@ -611,16 +883,14 @@ async def extract_data(pipeline_response): deserialized = self._deserialize("DigitalTwinsDescriptionListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -631,59 +901,129 @@ 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.DigitalTwins/digitalTwinsInstances"} # type: ignore + list_by_resource_group.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances" + } - @distributed_trace_async + @overload async def check_name_availability( self, location: str, - digital_twins_instance_check_name: "_models.CheckNameRequest", + digital_twins_instance_check_name: _models.CheckNameRequest, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.CheckNameResult": + ) -> _models.CheckNameResult: """Check if a DigitalTwinsInstance name is available. - :param location: Location of DigitalTwinsInstance. + :param location: Location of DigitalTwinsInstance. Required. :type location: str :param digital_twins_instance_check_name: Set the name parameter in the DigitalTwinsInstanceCheckName structure to the name of the DigitalTwinsInstance to check. + Required. :type digital_twins_instance_check_name: ~azure.mgmt.digitaltwins.v2020_03_01_preview.models.CheckNameRequest + :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: CheckNameResult, or the result of cls(response) + :return: CheckNameResult or the result of cls(response) :rtype: ~azure.mgmt.digitaltwins.v2020_03_01_preview.models.CheckNameResult - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def check_name_availability( + self, + location: str, + digital_twins_instance_check_name: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.CheckNameResult: + """Check if a DigitalTwinsInstance name is available. + + :param location: Location of DigitalTwinsInstance. Required. + :type location: str + :param digital_twins_instance_check_name: Set the name parameter in the + DigitalTwinsInstanceCheckName structure to the name of the DigitalTwinsInstance to check. + Required. + :type digital_twins_instance_check_name: 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: CheckNameResult or the result of cls(response) + :rtype: ~azure.mgmt.digitaltwins.v2020_03_01_preview.models.CheckNameResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def check_name_availability( + self, location: str, digital_twins_instance_check_name: Union[_models.CheckNameRequest, IO], **kwargs: Any + ) -> _models.CheckNameResult: + """Check if a DigitalTwinsInstance name is available. + + :param location: Location of DigitalTwinsInstance. Required. + :type location: str + :param digital_twins_instance_check_name: Set the name parameter in the + DigitalTwinsInstanceCheckName structure to the name of the DigitalTwinsInstance to check. Is + either a model type or a IO type. Required. + :type digital_twins_instance_check_name: + ~azure.mgmt.digitaltwins.v2020_03_01_preview.models.CheckNameRequest 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: CheckNameResult or the result of cls(response) + :rtype: ~azure.mgmt.digitaltwins.v2020_03_01_preview.models.CheckNameResult + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.CheckNameResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2020-03-01-preview") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(digital_twins_instance_check_name, 'CheckNameRequest') + api_version: Literal["2020-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2020-03-01-preview") + ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.CheckNameResult] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(digital_twins_instance_check_name, (IO, bytes)): + _content = digital_twins_instance_check_name + else: + _json = self._serialize.body(digital_twins_instance_check_name, "CheckNameRequest") request = build_check_name_availability_request( - subscription_id=self._config.subscription_id, location=location, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self.check_name_availability.metadata['url'], + content=_content, + template_url=self.check_name_availability.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -691,12 +1031,13 @@ async def check_name_availability( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('CheckNameResult', pipeline_response) + deserialized = self._deserialize("CheckNameResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - check_name_availability.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.DigitalTwins/locations/{location}/checkNameAvailability"} # type: ignore - + check_name_availability.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.DigitalTwins/locations/{location}/checkNameAvailability" + } diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/aio/operations/_operations.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/aio/operations/_operations.py index 370d2ee80d851..3b829ac1ab386 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/aio/operations/_operations.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/aio/operations/_operations.py @@ -6,79 +6,107 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models from ..._vendor import _convert_request from ...operations._operations import build_list_request -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class Operations: - """Operations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class Operations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.digitaltwins.v2020_03_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.digitaltwins.v2020_03_01_preview.aio.AzureDigitalTwinsManagementClient`'s + :attr:`operations` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace - def list( - self, - **kwargs: Any - ) -> AsyncIterable["_models.OperationListResult"]: + def list(self, **kwargs: Any) -> AsyncIterable["_models.Operation"]: """Lists all of the available DigitalTwins service REST API operations. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either OperationListResult or the result of cls(response) + :return: An iterator like instance of either Operation or the result of cls(response) :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.digitaltwins.v2020_03_01_preview.models.OperationListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.digitaltwins.v2020_03_01_preview.models.Operation] + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2020-03-01-preview") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2020-03-01-preview") + ) + cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) - cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationListResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( api_version=api_version, - template_url=self.list.metadata['url'], + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: - - request = build_list_request( - api_version=api_version, - template_url=next_link, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) @@ -89,16 +117,14 @@ async def extract_data(pipeline_response): deserialized = self._deserialize("OperationListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -109,8 +135,6 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/providers/Microsoft.DigitalTwins/operations"} # type: ignore + list.metadata = {"url": "/providers/Microsoft.DigitalTwins/operations"} diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/aio/operations/_patch.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/aio/operations/_patch.py new file mode 100644 index 0000000000000..f7dd32510333d --- /dev/null +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/aio/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/models/__init__.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/models/__init__.py index 74c4dba9eb0e6..b8f3dc91ee165 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/models/__init__.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/models/__init__.py @@ -26,38 +26,40 @@ from ._models_py3 import OperationListResult from ._models_py3 import ServiceBus - -from ._azure_digital_twins_management_client_enums import ( - DigitalTwinsSku, - EndpointProvisioningState, - EndpointType, - ProvisioningState, - Reason, -) +from ._azure_digital_twins_management_client_enums import DigitalTwinsSku +from ._azure_digital_twins_management_client_enums import EndpointProvisioningState +from ._azure_digital_twins_management_client_enums import EndpointType +from ._azure_digital_twins_management_client_enums import ProvisioningState +from ._azure_digital_twins_management_client_enums import Reason +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk __all__ = [ - 'CheckNameRequest', - 'CheckNameResult', - 'DigitalTwinsDescription', - 'DigitalTwinsDescriptionListResult', - 'DigitalTwinsEndpointResource', - 'DigitalTwinsEndpointResourceListResult', - 'DigitalTwinsEndpointResourceProperties', - 'DigitalTwinsPatchDescription', - 'DigitalTwinsResource', - 'DigitalTwinsSkuInfo', - 'ErrorDefinition', - 'ErrorResponse', - 'EventGrid', - 'EventHub', - 'ExternalResource', - 'Operation', - 'OperationDisplay', - 'OperationListResult', - 'ServiceBus', - 'DigitalTwinsSku', - 'EndpointProvisioningState', - 'EndpointType', - 'ProvisioningState', - 'Reason', + "CheckNameRequest", + "CheckNameResult", + "DigitalTwinsDescription", + "DigitalTwinsDescriptionListResult", + "DigitalTwinsEndpointResource", + "DigitalTwinsEndpointResourceListResult", + "DigitalTwinsEndpointResourceProperties", + "DigitalTwinsPatchDescription", + "DigitalTwinsResource", + "DigitalTwinsSkuInfo", + "ErrorDefinition", + "ErrorResponse", + "EventGrid", + "EventHub", + "ExternalResource", + "Operation", + "OperationDisplay", + "OperationListResult", + "ServiceBus", + "DigitalTwinsSku", + "EndpointProvisioningState", + "EndpointType", + "ProvisioningState", + "Reason", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/models/_azure_digital_twins_management_client_enums.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/models/_azure_digital_twins_management_client_enums.py index 43b1d758999d5..7d58368fe69b9 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/models/_azure_digital_twins_management_client_enums.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/models/_azure_digital_twins_management_client_enums.py @@ -7,19 +7,17 @@ # -------------------------------------------------------------------------- from enum import Enum -from six import with_metaclass from azure.core import CaseInsensitiveEnumMeta -class DigitalTwinsSku(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The name of the SKU. - """ +class DigitalTwinsSku(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The name of the SKU.""" F1 = "F1" -class EndpointProvisioningState(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The provisioning state. - """ + +class EndpointProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The provisioning state.""" PROVISIONING = "Provisioning" DELETING = "Deleting" @@ -27,17 +25,17 @@ class EndpointProvisioningState(with_metaclass(CaseInsensitiveEnumMeta, str, Enu FAILED = "Failed" CANCELED = "Canceled" -class EndpointType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The type of Digital Twins endpoint - """ + +class EndpointType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of Digital Twins endpoint.""" EVENT_HUB = "EventHub" EVENT_GRID = "EventGrid" SERVICE_BUS = "ServiceBus" -class ProvisioningState(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The provisioning state. - """ + +class ProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The provisioning state.""" PROVISIONING = "Provisioning" DELETING = "Deleting" @@ -45,9 +43,9 @@ class ProvisioningState(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): FAILED = "Failed" CANCELED = "Canceled" -class Reason(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """Message providing the reason why the given name is invalid. - """ + +class Reason(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Message providing the reason why the given name is invalid.""" INVALID = "Invalid" ALREADY_EXISTS = "AlreadyExists" diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/models/_models_py3.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/models/_models_py3.py index 11d41f95dddd7..ffb0bfad9769d 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/models/_models_py3.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/models/_models_py3.py @@ -1,4 +1,5 @@ # coding=utf-8 +# pylint: disable=too-many-lines # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. @@ -6,55 +7,51 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Dict, List, Optional, Union +from typing import Dict, List, Optional, TYPE_CHECKING, Union -from azure.core.exceptions import HttpResponseError -import msrest.serialization +from ... import _serialization -from ._azure_digital_twins_management_client_enums import * +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from .. import models as _models -class CheckNameRequest(msrest.serialization.Model): +class CheckNameRequest(_serialization.Model): """The result returned from a database check name availability request. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. - :ivar name: Required. Resource name. + :ivar name: Resource name. Required. :vartype name: str :ivar type: The type of resource, for instance Microsoft.DigitalTwins/digitalTwinsInstances. - Has constant value: "Microsoft.DigitalTwins/digitalTwinsInstances". + Required. Default value is "Microsoft.DigitalTwins/digitalTwinsInstances". :vartype type: str """ _validation = { - 'name': {'required': True}, - 'type': {'required': True, 'constant': True}, + "name": {"required": True}, + "type": {"required": True, "constant": True}, } _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, } type = "Microsoft.DigitalTwins/digitalTwinsInstances" - def __init__( - self, - *, - name: str, - **kwargs - ): + def __init__(self, *, name: str, **kwargs): """ - :keyword name: Required. Resource name. + :keyword name: Resource name. Required. :paramtype name: str """ - super(CheckNameRequest, self).__init__(**kwargs) + super().__init__(**kwargs) self.name = name -class CheckNameResult(msrest.serialization.Model): +class CheckNameResult(_serialization.Model): """The result returned from a check name availability request. :ivar name_available: Specifies a Boolean value that indicates if the name is available. @@ -64,16 +61,16 @@ class CheckNameResult(msrest.serialization.Model): :ivar message: Message indicating an unavailable name due to a conflict, or a description of the naming rules that are violated. :vartype message: str - :ivar reason: Message providing the reason why the given name is invalid. Possible values - include: "Invalid", "AlreadyExists". + :ivar reason: Message providing the reason why the given name is invalid. Known values are: + "Invalid" and "AlreadyExists". :vartype reason: str or ~azure.mgmt.digitaltwins.v2020_03_01_preview.models.Reason """ _attribute_map = { - 'name_available': {'key': 'nameAvailable', 'type': 'bool'}, - 'name': {'key': 'name', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, - 'reason': {'key': 'reason', 'type': 'str'}, + "name_available": {"key": "nameAvailable", "type": "bool"}, + "name": {"key": "name", "type": "str"}, + "message": {"key": "message", "type": "str"}, + "reason": {"key": "reason", "type": "str"}, } def __init__( @@ -82,7 +79,7 @@ def __init__( name_available: Optional[bool] = None, name: Optional[str] = None, message: Optional[str] = None, - reason: Optional[Union[str, "Reason"]] = None, + reason: Optional[Union[str, "_models.Reason"]] = None, **kwargs ): """ @@ -93,18 +90,18 @@ def __init__( :keyword message: Message indicating an unavailable name due to a conflict, or a description of the naming rules that are violated. :paramtype message: str - :keyword reason: Message providing the reason why the given name is invalid. Possible values - include: "Invalid", "AlreadyExists". + :keyword reason: Message providing the reason why the given name is invalid. Known values are: + "Invalid" and "AlreadyExists". :paramtype reason: str or ~azure.mgmt.digitaltwins.v2020_03_01_preview.models.Reason """ - super(CheckNameResult, self).__init__(**kwargs) + super().__init__(**kwargs) self.name_available = name_available self.name = name self.message = message self.reason = reason -class DigitalTwinsResource(msrest.serialization.Model): +class DigitalTwinsResource(_serialization.Model): """The common properties of a DigitalTwinsInstance. Variables are only populated by the server, and will be ignored when sending a request. @@ -117,28 +114,28 @@ class DigitalTwinsResource(msrest.serialization.Model): :vartype name: str :ivar type: The resource type. :vartype type: str - :ivar location: Required. The resource location. + :ivar location: The resource location. Required. :vartype location: str - :ivar tags: A set of tags. The resource tags. + :ivar tags: The resource tags. :vartype tags: dict[str, str] :ivar sku: This property is reserved for future use, and will be ignored/omitted. :vartype sku: ~azure.mgmt.digitaltwins.v2020_03_01_preview.models.DigitalTwinsSkuInfo """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True, 'pattern': r'^(?![0-9]+$)(?!-)[a-zA-Z0-9-]{2,49}[a-zA-Z0-9]$'}, - 'type': {'readonly': True}, - 'location': {'required': True}, + "id": {"readonly": True}, + "name": {"readonly": True, "pattern": r"^(?![0-9]+$)(?!-)[a-zA-Z0-9-]{2,49}[a-zA-Z0-9]$"}, + "type": {"readonly": True}, + "location": {"required": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'location': {'key': 'location', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - 'sku': {'key': 'sku', 'type': 'DigitalTwinsSkuInfo'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "sku": {"key": "sku", "type": "DigitalTwinsSkuInfo"}, } def __init__( @@ -146,18 +143,18 @@ def __init__( *, location: str, tags: Optional[Dict[str, str]] = None, - sku: Optional["DigitalTwinsSkuInfo"] = None, + sku: Optional["_models.DigitalTwinsSkuInfo"] = None, **kwargs ): """ - :keyword location: Required. The resource location. + :keyword location: The resource location. Required. :paramtype location: str - :keyword tags: A set of tags. The resource tags. + :keyword tags: The resource tags. :paramtype tags: dict[str, str] :keyword sku: This property is reserved for future use, and will be ignored/omitted. :paramtype sku: ~azure.mgmt.digitaltwins.v2020_03_01_preview.models.DigitalTwinsSkuInfo """ - super(DigitalTwinsResource, self).__init__(**kwargs) + super().__init__(**kwargs) self.id = None self.name = None self.type = None @@ -179,9 +176,9 @@ class DigitalTwinsDescription(DigitalTwinsResource): :vartype name: str :ivar type: The resource type. :vartype type: str - :ivar location: Required. The resource location. + :ivar location: The resource location. Required. :vartype location: str - :ivar tags: A set of tags. The resource tags. + :ivar tags: The resource tags. :vartype tags: dict[str, str] :ivar sku: This property is reserved for future use, and will be ignored/omitted. :vartype sku: ~azure.mgmt.digitaltwins.v2020_03_01_preview.models.DigitalTwinsSkuInfo @@ -189,8 +186,8 @@ class DigitalTwinsDescription(DigitalTwinsResource): :vartype created_time: ~datetime.datetime :ivar last_updated_time: Time when DigitalTwinsInstance was created. :vartype last_updated_time: ~datetime.datetime - :ivar provisioning_state: The provisioning state. Possible values include: "Provisioning", - "Deleting", "Succeeded", "Failed", "Canceled". + :ivar provisioning_state: The provisioning state. Known values are: "Provisioning", "Deleting", + "Succeeded", "Failed", and "Canceled". :vartype provisioning_state: str or ~azure.mgmt.digitaltwins.v2020_03_01_preview.models.ProvisioningState :ivar host_name: Api endpoint to work with DigitalTwinsInstance. @@ -198,27 +195,27 @@ class DigitalTwinsDescription(DigitalTwinsResource): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True, 'pattern': r'^(?![0-9]+$)(?!-)[a-zA-Z0-9-]{2,49}[a-zA-Z0-9]$'}, - 'type': {'readonly': True}, - 'location': {'required': True}, - 'created_time': {'readonly': True}, - 'last_updated_time': {'readonly': True}, - 'provisioning_state': {'readonly': True}, - 'host_name': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True, "pattern": r"^(?![0-9]+$)(?!-)[a-zA-Z0-9-]{2,49}[a-zA-Z0-9]$"}, + "type": {"readonly": True}, + "location": {"required": True}, + "created_time": {"readonly": True}, + "last_updated_time": {"readonly": True}, + "provisioning_state": {"readonly": True}, + "host_name": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'location': {'key': 'location', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - 'sku': {'key': 'sku', 'type': 'DigitalTwinsSkuInfo'}, - 'created_time': {'key': 'properties.createdTime', 'type': 'iso-8601'}, - 'last_updated_time': {'key': 'properties.lastUpdatedTime', 'type': 'iso-8601'}, - 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, - 'host_name': {'key': 'properties.hostName', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "sku": {"key": "sku", "type": "DigitalTwinsSkuInfo"}, + "created_time": {"key": "properties.createdTime", "type": "iso-8601"}, + "last_updated_time": {"key": "properties.lastUpdatedTime", "type": "iso-8601"}, + "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, + "host_name": {"key": "properties.hostName", "type": "str"}, } def __init__( @@ -226,25 +223,25 @@ def __init__( *, location: str, tags: Optional[Dict[str, str]] = None, - sku: Optional["DigitalTwinsSkuInfo"] = None, + sku: Optional["_models.DigitalTwinsSkuInfo"] = None, **kwargs ): """ - :keyword location: Required. The resource location. + :keyword location: The resource location. Required. :paramtype location: str - :keyword tags: A set of tags. The resource tags. + :keyword tags: The resource tags. :paramtype tags: dict[str, str] :keyword sku: This property is reserved for future use, and will be ignored/omitted. :paramtype sku: ~azure.mgmt.digitaltwins.v2020_03_01_preview.models.DigitalTwinsSkuInfo """ - super(DigitalTwinsDescription, self).__init__(location=location, tags=tags, sku=sku, **kwargs) + super().__init__(location=location, tags=tags, sku=sku, **kwargs) self.created_time = None self.last_updated_time = None self.provisioning_state = None self.host_name = None -class DigitalTwinsDescriptionListResult(msrest.serialization.Model): +class DigitalTwinsDescriptionListResult(_serialization.Model): """A list of DigitalTwins description objects with a next link. :ivar next_link: The link used to get the next page of DigitalTwins description objects. @@ -255,15 +252,15 @@ class DigitalTwinsDescriptionListResult(msrest.serialization.Model): """ _attribute_map = { - 'next_link': {'key': 'nextLink', 'type': 'str'}, - 'value': {'key': 'value', 'type': '[DigitalTwinsDescription]'}, + "next_link": {"key": "nextLink", "type": "str"}, + "value": {"key": "value", "type": "[DigitalTwinsDescription]"}, } def __init__( self, *, next_link: Optional[str] = None, - value: Optional[List["DigitalTwinsDescription"]] = None, + value: Optional[List["_models.DigitalTwinsDescription"]] = None, **kwargs ): """ @@ -273,12 +270,12 @@ def __init__( :paramtype value: list[~azure.mgmt.digitaltwins.v2020_03_01_preview.models.DigitalTwinsDescription] """ - super(DigitalTwinsDescriptionListResult, self).__init__(**kwargs) + super().__init__(**kwargs) self.next_link = next_link self.value = value -class ExternalResource(msrest.serialization.Model): +class ExternalResource(_serialization.Model): """Definition of a Resource. Variables are only populated by the server, and will be ignored when sending a request. @@ -292,24 +289,20 @@ class ExternalResource(msrest.serialization.Model): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True, 'pattern': r'^(?![0-9]+$)(?!-)[a-zA-Z0-9-]{2,49}[a-zA-Z0-9]$'}, - 'type': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True, "pattern": r"^(?![0-9]+$)(?!-)[a-zA-Z0-9-]{2,49}[a-zA-Z0-9]$"}, + "type": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(ExternalResource, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.id = None self.name = None self.type = None @@ -332,34 +325,29 @@ class DigitalTwinsEndpointResource(ExternalResource): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True, 'pattern': r'^(?![0-9]+$)(?!-)[a-zA-Z0-9-]{2,49}[a-zA-Z0-9]$'}, - 'type': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True, "pattern": r"^(?![0-9]+$)(?!-)[a-zA-Z0-9-]{2,49}[a-zA-Z0-9]$"}, + "type": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'properties': {'key': 'properties', 'type': 'DigitalTwinsEndpointResourceProperties'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "properties": {"key": "properties", "type": "DigitalTwinsEndpointResourceProperties"}, } - def __init__( - self, - *, - properties: Optional["DigitalTwinsEndpointResourceProperties"] = None, - **kwargs - ): + def __init__(self, *, properties: Optional["_models.DigitalTwinsEndpointResourceProperties"] = None, **kwargs): """ :keyword properties: DigitalTwinsInstance endpoint resource properties. :paramtype properties: ~azure.mgmt.digitaltwins.v2020_03_01_preview.models.DigitalTwinsEndpointResourceProperties """ - super(DigitalTwinsEndpointResource, self).__init__(**kwargs) + super().__init__(**kwargs) self.properties = properties -class DigitalTwinsEndpointResourceListResult(msrest.serialization.Model): +class DigitalTwinsEndpointResourceListResult(_serialization.Model): """A list of DigitalTwinsInstance Endpoints with a next link. :ivar next_link: The link used to get the next page of DigitalTwinsInstance Endpoints. @@ -370,15 +358,15 @@ class DigitalTwinsEndpointResourceListResult(msrest.serialization.Model): """ _attribute_map = { - 'next_link': {'key': 'nextLink', 'type': 'str'}, - 'value': {'key': 'value', 'type': '[DigitalTwinsEndpointResource]'}, + "next_link": {"key": "nextLink", "type": "str"}, + "value": {"key": "value", "type": "[DigitalTwinsEndpointResource]"}, } def __init__( self, *, next_link: Optional[str] = None, - value: Optional[List["DigitalTwinsEndpointResource"]] = None, + value: Optional[List["_models.DigitalTwinsEndpointResource"]] = None, **kwargs ): """ @@ -388,125 +376,108 @@ def __init__( :paramtype value: list[~azure.mgmt.digitaltwins.v2020_03_01_preview.models.DigitalTwinsEndpointResource] """ - super(DigitalTwinsEndpointResourceListResult, self).__init__(**kwargs) + super().__init__(**kwargs) self.next_link = next_link self.value = value -class DigitalTwinsEndpointResourceProperties(msrest.serialization.Model): +class DigitalTwinsEndpointResourceProperties(_serialization.Model): """Properties related to Digital Twins Endpoint. - You probably want to use the sub-classes and not this class directly. Known - sub-classes are: EventGrid, EventHub, ServiceBus. + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + EventGrid, EventHub, ServiceBus Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. - :ivar endpoint_type: Required. The type of Digital Twins endpoint.Constant filled by server. - Possible values include: "EventHub", "EventGrid", "ServiceBus". + :ivar endpoint_type: The type of Digital Twins endpoint. Required. Known values are: + "EventHub", "EventGrid", and "ServiceBus". :vartype endpoint_type: str or ~azure.mgmt.digitaltwins.v2020_03_01_preview.models.EndpointType - :ivar provisioning_state: The provisioning state. Possible values include: "Provisioning", - "Deleting", "Succeeded", "Failed", "Canceled". + :ivar provisioning_state: The provisioning state. Known values are: "Provisioning", "Deleting", + "Succeeded", "Failed", and "Canceled". :vartype provisioning_state: str or ~azure.mgmt.digitaltwins.v2020_03_01_preview.models.EndpointProvisioningState :ivar created_time: Time when the Endpoint was added to DigitalTwinsInstance. :vartype created_time: ~datetime.datetime - :ivar tags: A set of tags. The resource tags. + :ivar tags: The resource tags. :vartype tags: dict[str, str] """ _validation = { - 'endpoint_type': {'required': True}, - 'provisioning_state': {'readonly': True}, - 'created_time': {'readonly': True}, + "endpoint_type": {"required": True}, + "provisioning_state": {"readonly": True}, + "created_time": {"readonly": True}, } _attribute_map = { - 'endpoint_type': {'key': 'endpointType', 'type': 'str'}, - 'provisioning_state': {'key': 'provisioningState', 'type': 'str'}, - 'created_time': {'key': 'createdTime', 'type': 'iso-8601'}, - 'tags': {'key': 'tags', 'type': '{str}'}, + "endpoint_type": {"key": "endpointType", "type": "str"}, + "provisioning_state": {"key": "provisioningState", "type": "str"}, + "created_time": {"key": "createdTime", "type": "iso-8601"}, + "tags": {"key": "tags", "type": "{str}"}, } - _subtype_map = { - 'endpoint_type': {'EventGrid': 'EventGrid', 'EventHub': 'EventHub', 'ServiceBus': 'ServiceBus'} - } + _subtype_map = {"endpoint_type": {"EventGrid": "EventGrid", "EventHub": "EventHub", "ServiceBus": "ServiceBus"}} - def __init__( - self, - *, - tags: Optional[Dict[str, str]] = None, - **kwargs - ): + def __init__(self, *, tags: Optional[Dict[str, str]] = None, **kwargs): """ - :keyword tags: A set of tags. The resource tags. + :keyword tags: The resource tags. :paramtype tags: dict[str, str] """ - super(DigitalTwinsEndpointResourceProperties, self).__init__(**kwargs) - self.endpoint_type = None # type: Optional[str] + super().__init__(**kwargs) + self.endpoint_type: Optional[str] = None self.provisioning_state = None self.created_time = None self.tags = tags -class DigitalTwinsPatchDescription(msrest.serialization.Model): +class DigitalTwinsPatchDescription(_serialization.Model): """The description of the DigitalTwins service. - :ivar tags: A set of tags. Instance tags. + :ivar tags: Instance tags. :vartype tags: dict[str, str] """ _attribute_map = { - 'tags': {'key': 'tags', 'type': '{str}'}, + "tags": {"key": "tags", "type": "{str}"}, } - def __init__( - self, - *, - tags: Optional[Dict[str, str]] = None, - **kwargs - ): + def __init__(self, *, tags: Optional[Dict[str, str]] = None, **kwargs): """ - :keyword tags: A set of tags. Instance tags. + :keyword tags: Instance tags. :paramtype tags: dict[str, str] """ - super(DigitalTwinsPatchDescription, self).__init__(**kwargs) + super().__init__(**kwargs) self.tags = tags -class DigitalTwinsSkuInfo(msrest.serialization.Model): +class DigitalTwinsSkuInfo(_serialization.Model): """Information about the SKU of the DigitalTwinsInstance. All required parameters must be populated in order to send to Azure. - :ivar name: Required. The name of the SKU. Possible values include: "F1". + :ivar name: The name of the SKU. Required. "F1" :vartype name: str or ~azure.mgmt.digitaltwins.v2020_03_01_preview.models.DigitalTwinsSku """ _validation = { - 'name': {'required': True}, + "name": {"required": True}, } _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, + "name": {"key": "name", "type": "str"}, } - def __init__( - self, - *, - name: Union[str, "DigitalTwinsSku"], - **kwargs - ): + def __init__(self, *, name: Union[str, "_models.DigitalTwinsSku"], **kwargs): """ - :keyword name: Required. The name of the SKU. Possible values include: "F1". + :keyword name: The name of the SKU. Required. "F1" :paramtype name: str or ~azure.mgmt.digitaltwins.v2020_03_01_preview.models.DigitalTwinsSku """ - super(DigitalTwinsSkuInfo, self).__init__(**kwargs) + super().__init__(**kwargs) self.name = name -class ErrorDefinition(msrest.serialization.Model): +class ErrorDefinition(_serialization.Model): """Error definition. Variables are only populated by the server, and will be ignored when sending a request. @@ -520,30 +491,26 @@ class ErrorDefinition(msrest.serialization.Model): """ _validation = { - 'code': {'readonly': True}, - 'message': {'readonly': True}, - 'details': {'readonly': True}, + "code": {"readonly": True}, + "message": {"readonly": True}, + "details": {"readonly": True}, } _attribute_map = { - 'code': {'key': 'code', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, - 'details': {'key': 'details', 'type': '[ErrorDefinition]'}, + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, + "details": {"key": "details", "type": "[ErrorDefinition]"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(ErrorDefinition, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.code = None self.message = None self.details = None -class ErrorResponse(msrest.serialization.Model): +class ErrorResponse(_serialization.Model): """Error response. :ivar error: Error description. @@ -551,20 +518,15 @@ class ErrorResponse(msrest.serialization.Model): """ _attribute_map = { - 'error': {'key': 'error', 'type': 'ErrorDefinition'}, + "error": {"key": "error", "type": "ErrorDefinition"}, } - def __init__( - self, - *, - error: Optional["ErrorDefinition"] = None, - **kwargs - ): + def __init__(self, *, error: Optional["_models.ErrorDefinition"] = None, **kwargs): """ :keyword error: Error description. :paramtype error: ~azure.mgmt.digitaltwins.v2020_03_01_preview.models.ErrorDefinition """ - super(ErrorResponse, self).__init__(**kwargs) + super().__init__(**kwargs) self.error = error @@ -575,41 +537,41 @@ class EventGrid(DigitalTwinsEndpointResourceProperties): All required parameters must be populated in order to send to Azure. - :ivar endpoint_type: Required. The type of Digital Twins endpoint.Constant filled by server. - Possible values include: "EventHub", "EventGrid", "ServiceBus". + :ivar endpoint_type: The type of Digital Twins endpoint. Required. Known values are: + "EventHub", "EventGrid", and "ServiceBus". :vartype endpoint_type: str or ~azure.mgmt.digitaltwins.v2020_03_01_preview.models.EndpointType - :ivar provisioning_state: The provisioning state. Possible values include: "Provisioning", - "Deleting", "Succeeded", "Failed", "Canceled". + :ivar provisioning_state: The provisioning state. Known values are: "Provisioning", "Deleting", + "Succeeded", "Failed", and "Canceled". :vartype provisioning_state: str or ~azure.mgmt.digitaltwins.v2020_03_01_preview.models.EndpointProvisioningState :ivar created_time: Time when the Endpoint was added to DigitalTwinsInstance. :vartype created_time: ~datetime.datetime - :ivar tags: A set of tags. The resource tags. + :ivar tags: The resource tags. :vartype tags: dict[str, str] :ivar topic_endpoint: EventGrid Topic Endpoint. :vartype topic_endpoint: str - :ivar access_key1: Required. EventGrid secondary accesskey. Will be obfuscated during read. + :ivar access_key1: EventGrid secondary accesskey. Will be obfuscated during read. Required. :vartype access_key1: str - :ivar access_key2: Required. EventGrid secondary accesskey. Will be obfuscated during read. + :ivar access_key2: EventGrid secondary accesskey. Will be obfuscated during read. Required. :vartype access_key2: str """ _validation = { - 'endpoint_type': {'required': True}, - 'provisioning_state': {'readonly': True}, - 'created_time': {'readonly': True}, - 'access_key1': {'required': True}, - 'access_key2': {'required': True}, + "endpoint_type": {"required": True}, + "provisioning_state": {"readonly": True}, + "created_time": {"readonly": True}, + "access_key1": {"required": True}, + "access_key2": {"required": True}, } _attribute_map = { - 'endpoint_type': {'key': 'endpointType', 'type': 'str'}, - 'provisioning_state': {'key': 'provisioningState', 'type': 'str'}, - 'created_time': {'key': 'createdTime', 'type': 'iso-8601'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - 'topic_endpoint': {'key': 'TopicEndpoint', 'type': 'str'}, - 'access_key1': {'key': 'accessKey1', 'type': 'str'}, - 'access_key2': {'key': 'accessKey2', 'type': 'str'}, + "endpoint_type": {"key": "endpointType", "type": "str"}, + "provisioning_state": {"key": "provisioningState", "type": "str"}, + "created_time": {"key": "createdTime", "type": "iso-8601"}, + "tags": {"key": "tags", "type": "{str}"}, + "topic_endpoint": {"key": "TopicEndpoint", "type": "str"}, + "access_key1": {"key": "accessKey1", "type": "str"}, + "access_key2": {"key": "accessKey2", "type": "str"}, } def __init__( @@ -622,17 +584,17 @@ def __init__( **kwargs ): """ - :keyword tags: A set of tags. The resource tags. + :keyword tags: The resource tags. :paramtype tags: dict[str, str] :keyword topic_endpoint: EventGrid Topic Endpoint. :paramtype topic_endpoint: str - :keyword access_key1: Required. EventGrid secondary accesskey. Will be obfuscated during read. + :keyword access_key1: EventGrid secondary accesskey. Will be obfuscated during read. Required. :paramtype access_key1: str - :keyword access_key2: Required. EventGrid secondary accesskey. Will be obfuscated during read. + :keyword access_key2: EventGrid secondary accesskey. Will be obfuscated during read. Required. :paramtype access_key2: str """ - super(EventGrid, self).__init__(tags=tags, **kwargs) - self.endpoint_type = 'EventGrid' # type: str + super().__init__(tags=tags, **kwargs) + self.endpoint_type: str = "EventGrid" self.topic_endpoint = topic_endpoint self.access_key1 = access_key1 self.access_key2 = access_key2 @@ -645,40 +607,40 @@ class EventHub(DigitalTwinsEndpointResourceProperties): All required parameters must be populated in order to send to Azure. - :ivar endpoint_type: Required. The type of Digital Twins endpoint.Constant filled by server. - Possible values include: "EventHub", "EventGrid", "ServiceBus". + :ivar endpoint_type: The type of Digital Twins endpoint. Required. Known values are: + "EventHub", "EventGrid", and "ServiceBus". :vartype endpoint_type: str or ~azure.mgmt.digitaltwins.v2020_03_01_preview.models.EndpointType - :ivar provisioning_state: The provisioning state. Possible values include: "Provisioning", - "Deleting", "Succeeded", "Failed", "Canceled". + :ivar provisioning_state: The provisioning state. Known values are: "Provisioning", "Deleting", + "Succeeded", "Failed", and "Canceled". :vartype provisioning_state: str or ~azure.mgmt.digitaltwins.v2020_03_01_preview.models.EndpointProvisioningState :ivar created_time: Time when the Endpoint was added to DigitalTwinsInstance. :vartype created_time: ~datetime.datetime - :ivar tags: A set of tags. The resource tags. + :ivar tags: The resource tags. :vartype tags: dict[str, str] - :ivar connection_string_primary_key: Required. PrimaryConnectionString of the endpoint. Will be - obfuscated during read. + :ivar connection_string_primary_key: PrimaryConnectionString of the endpoint. Will be + obfuscated during read. Required. :vartype connection_string_primary_key: str - :ivar connection_string_secondary_key: Required. SecondaryConnectionString of the endpoint. - Will be obfuscated during read. + :ivar connection_string_secondary_key: SecondaryConnectionString of the endpoint. Will be + obfuscated during read. Required. :vartype connection_string_secondary_key: str """ _validation = { - 'endpoint_type': {'required': True}, - 'provisioning_state': {'readonly': True}, - 'created_time': {'readonly': True}, - 'connection_string_primary_key': {'required': True}, - 'connection_string_secondary_key': {'required': True}, + "endpoint_type": {"required": True}, + "provisioning_state": {"readonly": True}, + "created_time": {"readonly": True}, + "connection_string_primary_key": {"required": True}, + "connection_string_secondary_key": {"required": True}, } _attribute_map = { - 'endpoint_type': {'key': 'endpointType', 'type': 'str'}, - 'provisioning_state': {'key': 'provisioningState', 'type': 'str'}, - 'created_time': {'key': 'createdTime', 'type': 'iso-8601'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - 'connection_string_primary_key': {'key': 'connectionString-PrimaryKey', 'type': 'str'}, - 'connection_string_secondary_key': {'key': 'connectionString-SecondaryKey', 'type': 'str'}, + "endpoint_type": {"key": "endpointType", "type": "str"}, + "provisioning_state": {"key": "provisioningState", "type": "str"}, + "created_time": {"key": "createdTime", "type": "iso-8601"}, + "tags": {"key": "tags", "type": "{str}"}, + "connection_string_primary_key": {"key": "connectionString-PrimaryKey", "type": "str"}, + "connection_string_secondary_key": {"key": "connectionString-SecondaryKey", "type": "str"}, } def __init__( @@ -690,22 +652,22 @@ def __init__( **kwargs ): """ - :keyword tags: A set of tags. The resource tags. + :keyword tags: The resource tags. :paramtype tags: dict[str, str] - :keyword connection_string_primary_key: Required. PrimaryConnectionString of the endpoint. Will - be obfuscated during read. + :keyword connection_string_primary_key: PrimaryConnectionString of the endpoint. Will be + obfuscated during read. Required. :paramtype connection_string_primary_key: str - :keyword connection_string_secondary_key: Required. SecondaryConnectionString of the endpoint. - Will be obfuscated during read. + :keyword connection_string_secondary_key: SecondaryConnectionString of the endpoint. Will be + obfuscated during read. Required. :paramtype connection_string_secondary_key: str """ - super(EventHub, self).__init__(tags=tags, **kwargs) - self.endpoint_type = 'EventHub' # type: str + super().__init__(tags=tags, **kwargs) + self.endpoint_type: str = "EventHub" self.connection_string_primary_key = connection_string_primary_key self.connection_string_secondary_key = connection_string_secondary_key -class Operation(msrest.serialization.Model): +class Operation(_serialization.Model): """DigitalTwins service REST API operation. Variables are only populated by the server, and will be ignored when sending a request. @@ -717,30 +679,25 @@ class Operation(msrest.serialization.Model): """ _validation = { - 'name': {'readonly': True}, + "name": {"readonly": True}, } _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'display': {'key': 'display', 'type': 'OperationDisplay'}, + "name": {"key": "name", "type": "str"}, + "display": {"key": "display", "type": "OperationDisplay"}, } - def __init__( - self, - *, - display: Optional["OperationDisplay"] = None, - **kwargs - ): + def __init__(self, *, display: Optional["_models.OperationDisplay"] = None, **kwargs): """ :keyword display: Operation properties display. :paramtype display: ~azure.mgmt.digitaltwins.v2020_03_01_preview.models.OperationDisplay """ - super(Operation, self).__init__(**kwargs) + super().__init__(**kwargs) self.name = None self.display = display -class OperationDisplay(msrest.serialization.Model): +class OperationDisplay(_serialization.Model): """The object that represents the operation. Variables are only populated by the server, and will be ignored when sending a request. @@ -756,33 +713,29 @@ class OperationDisplay(msrest.serialization.Model): """ _validation = { - 'provider': {'readonly': True}, - 'resource': {'readonly': True}, - 'operation': {'readonly': True}, - 'description': {'readonly': True}, + "provider": {"readonly": True}, + "resource": {"readonly": True}, + "operation": {"readonly": True}, + "description": {"readonly": True}, } _attribute_map = { - 'provider': {'key': 'provider', 'type': 'str'}, - 'resource': {'key': 'resource', 'type': 'str'}, - 'operation': {'key': 'operation', 'type': 'str'}, - 'description': {'key': 'description', 'type': 'str'}, + "provider": {"key": "provider", "type": "str"}, + "resource": {"key": "resource", "type": "str"}, + "operation": {"key": "operation", "type": "str"}, + "description": {"key": "description", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(OperationDisplay, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.provider = None self.resource = None self.operation = None self.description = None -class OperationListResult(msrest.serialization.Model): +class OperationListResult(_serialization.Model): """A list of DigitalTwins service operations. It contains a list of operations and a URL link to get the next set of results. Variables are only populated by the server, and will be ignored when sending a request. @@ -795,25 +748,20 @@ class OperationListResult(msrest.serialization.Model): """ _validation = { - 'value': {'readonly': True}, + "value": {"readonly": True}, } _attribute_map = { - 'next_link': {'key': 'nextLink', 'type': 'str'}, - 'value': {'key': 'value', 'type': '[Operation]'}, + "next_link": {"key": "nextLink", "type": "str"}, + "value": {"key": "value", "type": "[Operation]"}, } - def __init__( - self, - *, - next_link: Optional[str] = None, - **kwargs - ): + def __init__(self, *, next_link: Optional[str] = None, **kwargs): """ :keyword next_link: The link used to get the next page of DigitalTwins description objects. :paramtype next_link: str """ - super(OperationListResult, self).__init__(**kwargs) + super().__init__(**kwargs) self.next_link = next_link self.value = None @@ -825,40 +773,40 @@ class ServiceBus(DigitalTwinsEndpointResourceProperties): All required parameters must be populated in order to send to Azure. - :ivar endpoint_type: Required. The type of Digital Twins endpoint.Constant filled by server. - Possible values include: "EventHub", "EventGrid", "ServiceBus". + :ivar endpoint_type: The type of Digital Twins endpoint. Required. Known values are: + "EventHub", "EventGrid", and "ServiceBus". :vartype endpoint_type: str or ~azure.mgmt.digitaltwins.v2020_03_01_preview.models.EndpointType - :ivar provisioning_state: The provisioning state. Possible values include: "Provisioning", - "Deleting", "Succeeded", "Failed", "Canceled". + :ivar provisioning_state: The provisioning state. Known values are: "Provisioning", "Deleting", + "Succeeded", "Failed", and "Canceled". :vartype provisioning_state: str or ~azure.mgmt.digitaltwins.v2020_03_01_preview.models.EndpointProvisioningState :ivar created_time: Time when the Endpoint was added to DigitalTwinsInstance. :vartype created_time: ~datetime.datetime - :ivar tags: A set of tags. The resource tags. + :ivar tags: The resource tags. :vartype tags: dict[str, str] - :ivar primary_connection_string: Required. PrimaryConnectionString of the endpoint. Will be - obfuscated during read. + :ivar primary_connection_string: PrimaryConnectionString of the endpoint. Will be obfuscated + during read. Required. :vartype primary_connection_string: str - :ivar secondary_connection_string: Required. SecondaryConnectionString of the endpoint. Will be - obfuscated during read. + :ivar secondary_connection_string: SecondaryConnectionString of the endpoint. Will be + obfuscated during read. Required. :vartype secondary_connection_string: str """ _validation = { - 'endpoint_type': {'required': True}, - 'provisioning_state': {'readonly': True}, - 'created_time': {'readonly': True}, - 'primary_connection_string': {'required': True}, - 'secondary_connection_string': {'required': True}, + "endpoint_type": {"required": True}, + "provisioning_state": {"readonly": True}, + "created_time": {"readonly": True}, + "primary_connection_string": {"required": True}, + "secondary_connection_string": {"required": True}, } _attribute_map = { - 'endpoint_type': {'key': 'endpointType', 'type': 'str'}, - 'provisioning_state': {'key': 'provisioningState', 'type': 'str'}, - 'created_time': {'key': 'createdTime', 'type': 'iso-8601'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - 'primary_connection_string': {'key': 'primaryConnectionString', 'type': 'str'}, - 'secondary_connection_string': {'key': 'secondaryConnectionString', 'type': 'str'}, + "endpoint_type": {"key": "endpointType", "type": "str"}, + "provisioning_state": {"key": "provisioningState", "type": "str"}, + "created_time": {"key": "createdTime", "type": "iso-8601"}, + "tags": {"key": "tags", "type": "{str}"}, + "primary_connection_string": {"key": "primaryConnectionString", "type": "str"}, + "secondary_connection_string": {"key": "secondaryConnectionString", "type": "str"}, } def __init__( @@ -870,16 +818,16 @@ def __init__( **kwargs ): """ - :keyword tags: A set of tags. The resource tags. + :keyword tags: The resource tags. :paramtype tags: dict[str, str] - :keyword primary_connection_string: Required. PrimaryConnectionString of the endpoint. Will be - obfuscated during read. + :keyword primary_connection_string: PrimaryConnectionString of the endpoint. Will be obfuscated + during read. Required. :paramtype primary_connection_string: str - :keyword secondary_connection_string: Required. SecondaryConnectionString of the endpoint. Will - be obfuscated during read. + :keyword secondary_connection_string: SecondaryConnectionString of the endpoint. Will be + obfuscated during read. Required. :paramtype secondary_connection_string: str """ - super(ServiceBus, self).__init__(tags=tags, **kwargs) - self.endpoint_type = 'ServiceBus' # type: str + super().__init__(tags=tags, **kwargs) + self.endpoint_type: str = "ServiceBus" self.primary_connection_string = primary_connection_string self.secondary_connection_string = secondary_connection_string diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/models/_patch.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/models/_patch.py new file mode 100644 index 0000000000000..f7dd32510333d --- /dev/null +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/models/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/operations/__init__.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/operations/__init__.py index a9cda9c99062e..a2f402ab0c76f 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/operations/__init__.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/operations/__init__.py @@ -10,8 +10,14 @@ from ._digital_twins_endpoint_operations import DigitalTwinsEndpointOperations from ._operations import Operations +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + __all__ = [ - 'DigitalTwinsOperations', - 'DigitalTwinsEndpointOperations', - 'Operations', + "DigitalTwinsOperations", + "DigitalTwinsEndpointOperations", + "Operations", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/operations/_digital_twins_endpoint_operations.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/operations/_digital_twins_endpoint_operations.py index df985a6b8acbf..3a817262064f9 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/operations/_digital_twins_endpoint_operations.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/operations/_digital_twins_endpoint_operations.py @@ -6,257 +6,275 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Iterable, Optional, TypeVar, Union - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import sys +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models +from ..._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') -JSONType = Any + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False + def build_list_request( - subscription_id: str, - resource_group_name: str, - resource_name: str, - **kwargs: Any + resource_group_name: str, resource_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = kwargs.pop('api_version', "2020-03-01-preview") # type: str + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2020-03-01-preview") + ) + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints", + ) # 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', max_length=64, min_length=1), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=64, min_length=1), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=64, min_length=1 + ), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str", max_length=64, min_length=1), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # 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( - subscription_id: str, - resource_group_name: str, - resource_name: str, - endpoint_name: str, - **kwargs: Any + resource_group_name: str, resource_name: str, endpoint_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = kwargs.pop('api_version', "2020-03-01-preview") # type: str + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2020-03-01-preview") + ) + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}", + ) # 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', max_length=64, min_length=1), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=64, min_length=1), - "endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, 'str', max_length=64, min_length=1, pattern=r'^[A-Za-z0-9-._]{1,64}$'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=64, min_length=1 + ), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str", max_length=64, min_length=1), + "endpointName": _SERIALIZER.url( + "endpoint_name", endpoint_name, "str", max_length=64, min_length=1, pattern=r"^[A-Za-z0-9-._]{1,64}$" + ), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # 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_initial( - subscription_id: str, - resource_group_name: str, - resource_name: str, - endpoint_name: str, - *, - json: JSONType = None, - content: Any = None, - **kwargs: Any +def build_create_or_update_request( + resource_group_name: str, resource_name: str, endpoint_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = kwargs.pop('api_version', "2020-03-01-preview") # type: str - content_type = kwargs.pop('content_type', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2020-03-01-preview") + ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}", + ) # 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', max_length=64, min_length=1), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=64, min_length=1), - "endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, 'str', max_length=64, min_length=1, pattern=r'^[A-Za-z0-9-._]{1,64}$'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=64, min_length=1 + ), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str", max_length=64, min_length=1), + "endpointName": _SERIALIZER.url( + "endpoint_name", endpoint_name, "str", max_length=64, min_length=1, pattern=r"^[A-Za-z0-9-._]{1,64}$" + ), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # 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_initial( - subscription_id: str, - resource_group_name: str, - resource_name: str, - endpoint_name: str, - **kwargs: Any + +def build_delete_request( + resource_group_name: str, resource_name: str, endpoint_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = kwargs.pop('api_version', "2020-03-01-preview") # type: str + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2020-03-01-preview") + ) + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}", + ) # 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', max_length=64, min_length=1), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=64, min_length=1), - "endpointName": _SERIALIZER.url("endpoint_name", endpoint_name, 'str', max_length=64, min_length=1, pattern=r'^[A-Za-z0-9-._]{1,64}$'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=64, min_length=1 + ), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str", max_length=64, min_length=1), + "endpointName": _SERIALIZER.url( + "endpoint_name", endpoint_name, "str", max_length=64, min_length=1, pattern=r"^[A-Za-z0-9-._]{1,64}$" + ), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # 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") -class DigitalTwinsEndpointOperations(object): - """DigitalTwinsEndpointOperations operations. + return HttpRequest(method="DELETE", 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.digitaltwins.v2020_03_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. +class DigitalTwinsEndpointOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.digitaltwins.v2020_03_01_preview.AzureDigitalTwinsManagementClient`'s + :attr:`digital_twins_endpoint` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list( - self, - resource_group_name: str, - resource_name: str, - **kwargs: Any - ) -> Iterable["_models.DigitalTwinsEndpointResourceListResult"]: + self, resource_group_name: str, resource_name: str, **kwargs: Any + ) -> Iterable["_models.DigitalTwinsEndpointResource"]: """Get DigitalTwinsInstance Endpoints. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either DigitalTwinsEndpointResourceListResult or the - result of cls(response) + :return: An iterator like instance of either DigitalTwinsEndpointResource or the result of + cls(response) :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.digitaltwins.v2020_03_01_preview.models.DigitalTwinsEndpointResourceListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.paging.ItemPaged[~azure.mgmt.digitaltwins.v2020_03_01_preview.models.DigitalTwinsEndpointResource] + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2020-03-01-preview") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2020-03-01-preview") + ) + cls: ClsType[_models.DigitalTwinsEndpointResourceListResult] = kwargs.pop("cls", None) - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsEndpointResourceListResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list.metadata['url'], + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: - - request = build_list_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - resource_name=resource_name, - api_version=api_version, - template_url=next_link, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) @@ -267,16 +285,14 @@ def extract_data(pipeline_response): deserialized = self._deserialize("DigitalTwinsEndpointResourceListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -287,59 +303,63 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints"} # type: ignore + list.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints" + } @distributed_trace def get( - self, - resource_group_name: str, - resource_name: str, - endpoint_name: str, - **kwargs: Any - ) -> "_models.DigitalTwinsEndpointResource": + self, resource_group_name: str, resource_name: str, endpoint_name: str, **kwargs: Any + ) -> _models.DigitalTwinsEndpointResource: """Get DigitalTwinsInstances Endpoint. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param endpoint_name: Name of Endpoint Resource. + :param endpoint_name: Name of Endpoint Resource. Required. :type endpoint_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: DigitalTwinsEndpointResource, or the result of cls(response) + :return: DigitalTwinsEndpointResource or the result of cls(response) :rtype: ~azure.mgmt.digitaltwins.v2020_03_01_preview.models.DigitalTwinsEndpointResource - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsEndpointResource"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2020-03-01-preview") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2020-03-01-preview") + ) + cls: ClsType[_models.DigitalTwinsEndpointResource] = kwargs.pop("cls", None) - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, endpoint_name=endpoint_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -347,72 +367,174 @@ def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('DigitalTwinsEndpointResource', pipeline_response) + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}"} # type: ignore - + get.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}" + } def _create_or_update_initial( self, resource_group_name: str, resource_name: str, endpoint_name: str, - endpoint_description: "_models.DigitalTwinsEndpointResource", + endpoint_description: Union[_models.DigitalTwinsEndpointResource, IO], **kwargs: Any - ) -> "_models.DigitalTwinsEndpointResource": - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsEndpointResource"] + ) -> _models.DigitalTwinsEndpointResource: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2020-03-01-preview") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(endpoint_description, 'DigitalTwinsEndpointResource') - - request = build_create_or_update_request_initial( - subscription_id=self._config.subscription_id, + api_version: Literal["2020-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2020-03-01-preview") + ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DigitalTwinsEndpointResource] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(endpoint_description, (IO, bytes)): + _content = endpoint_description + else: + _json = self._serialize.body(endpoint_description, "DigitalTwinsEndpointResource") + + request = build_create_or_update_request( resource_group_name=resource_group_name, resource_name=resource_name, 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_initial.metadata['url'], + content=_content, + template_url=self._create_or_update_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('DigitalTwinsEndpointResource', pipeline_response) + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('DigitalTwinsEndpointResource', pipeline_response) + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized + return deserialized # type: ignore + + _create_or_update_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}" + } + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + endpoint_name: str, + endpoint_description: _models.DigitalTwinsEndpointResource, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.DigitalTwinsEndpointResource]: + """Create or update DigitalTwinsInstance endpoint. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param endpoint_name: Name of Endpoint Resource. Required. + :type endpoint_name: str + :param endpoint_description: The DigitalTwinsInstance endpoint metadata and security metadata. + Required. + :type endpoint_description: + ~azure.mgmt.digitaltwins.v2020_03_01_preview.models.DigitalTwinsEndpointResource + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either DigitalTwinsEndpointResource or the + result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2020_03_01_preview.models.DigitalTwinsEndpointResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ - _create_or_update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}"} # type: ignore + @overload + def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + endpoint_name: str, + endpoint_description: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.DigitalTwinsEndpointResource]: + """Create or update DigitalTwinsInstance endpoint. + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param endpoint_name: Name of Endpoint Resource. Required. + :type endpoint_name: str + :param endpoint_description: The DigitalTwinsInstance endpoint metadata and security metadata. + Required. + :type endpoint_description: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either DigitalTwinsEndpointResource or the + result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2020_03_01_preview.models.DigitalTwinsEndpointResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace def begin_create_or_update( @@ -420,21 +542,25 @@ def begin_create_or_update( resource_group_name: str, resource_name: str, endpoint_name: str, - endpoint_description: "_models.DigitalTwinsEndpointResource", + endpoint_description: Union[_models.DigitalTwinsEndpointResource, IO], **kwargs: Any - ) -> LROPoller["_models.DigitalTwinsEndpointResource"]: + ) -> LROPoller[_models.DigitalTwinsEndpointResource]: """Create or update DigitalTwinsInstance endpoint. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param endpoint_name: Name of Endpoint Resource. + :param endpoint_name: Name of Endpoint Resource. Required. :type endpoint_name: str :param endpoint_description: The DigitalTwinsInstance endpoint metadata and security metadata. + Is either a model type or a IO type. Required. :type endpoint_description: - ~azure.mgmt.digitaltwins.v2020_03_01_preview.models.DigitalTwinsEndpointResource + ~azure.mgmt.digitaltwins.v2020_03_01_preview.models.DigitalTwinsEndpointResource or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this @@ -447,17 +573,19 @@ def begin_create_or_update( result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2020_03_01_preview.models.DigitalTwinsEndpointResource] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2020-03-01-preview") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsEndpointResource"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2020-03-01-preview") ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DigitalTwinsEndpointResource] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = self._create_or_update_initial( resource_group_name=resource_group_name, @@ -466,99 +594,106 @@ def begin_create_or_update( endpoint_description=endpoint_description, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('DigitalTwinsEndpointResource', pipeline_response) + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - begin_create_or_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}"} # type: ignore + begin_create_or_update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}" + } def _delete_initial( - self, - resource_group_name: str, - resource_name: str, - endpoint_name: str, - **kwargs: Any - ) -> Optional["_models.DigitalTwinsEndpointResource"]: - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.DigitalTwinsEndpointResource"]] + self, resource_group_name: str, resource_name: str, endpoint_name: str, **kwargs: Any + ) -> Optional[_models.DigitalTwinsEndpointResource]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2020-03-01-preview") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - request = build_delete_request_initial( - subscription_id=self._config.subscription_id, + api_version: Literal["2020-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2020-03-01-preview") + ) + cls: ClsType[Optional[_models.DigitalTwinsEndpointResource]] = kwargs.pop("cls", None) + + request = build_delete_request( resource_group_name=resource_group_name, resource_name=resource_name, endpoint_name=endpoint_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._delete_initial.metadata['url'], + template_url=self._delete_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 202: - deserialized = self._deserialize('DigitalTwinsEndpointResource', pipeline_response) + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _delete_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}"} # type: ignore - + _delete_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}" + } @distributed_trace def begin_delete( - self, - resource_group_name: str, - resource_name: str, - endpoint_name: str, - **kwargs: Any - ) -> LROPoller["_models.DigitalTwinsEndpointResource"]: + self, resource_group_name: str, resource_name: str, endpoint_name: str, **kwargs: Any + ) -> LROPoller[None]: """Delete a DigitalTwinsInstance endpoint. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param endpoint_name: Name of Endpoint Resource. + :param endpoint_name: Name of Endpoint Resource. Required. :type endpoint_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. @@ -572,45 +707,52 @@ def begin_delete( result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2020_03_01_preview.models.DigitalTwinsEndpointResource] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2020-03-01-preview") # type: str - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsEndpointResource"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2020-03-01-preview") ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = self._delete_initial( resource_group_name=resource_group_name, resource_name=resource_name, endpoint_name=endpoint_name, api_version=api_version, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('DigitalTwinsEndpointResource', pipeline_response) + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - begin_delete.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}"} # type: ignore + begin_delete.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}" + } diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/operations/_digital_twins_operations.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/operations/_digital_twins_operations.py index 5f9fc6b4edfd1..22b5357290c9e 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/operations/_digital_twins_operations.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/operations/_digital_twins_operations.py @@ -6,361 +6,345 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Iterable, Optional, TypeVar, Union - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import sys +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models +from ..._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') -JSONType = Any + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_get_request( - subscription_id: str, - resource_group_name: str, - resource_name: str, - **kwargs: Any -) -> HttpRequest: - api_version = kwargs.pop('api_version', "2020-03-01-preview") # type: str - accept = "application/json" +def build_get_request(resource_group_name: str, resource_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2020-03-01-preview") + ) + accept = _headers.pop("Accept", "application/json") + # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}", + ) # 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', max_length=64, min_length=1), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=64, min_length=1), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=64, min_length=1 + ), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str", max_length=64, min_length=1), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # 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_initial( - subscription_id: str, - resource_group_name: str, - resource_name: str, - *, - json: JSONType = None, - content: Any = None, - **kwargs: Any +def build_create_or_update_request( + resource_group_name: str, resource_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = kwargs.pop('api_version', "2020-03-01-preview") # type: str - content_type = kwargs.pop('content_type', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2020-03-01-preview") + ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}", + ) # 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', max_length=64, min_length=1), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=64, min_length=1), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=64, min_length=1 + ), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str", max_length=64, min_length=1), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # 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_update_request_initial( - subscription_id: str, - resource_group_name: str, - resource_name: str, - *, - json: JSONType = None, - content: Any = None, - **kwargs: Any +def build_update_request( + resource_group_name: str, resource_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = kwargs.pop('api_version', "2020-03-01-preview") # type: str - content_type = kwargs.pop('content_type', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2020-03-01-preview") + ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}", + ) # 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', max_length=64, min_length=1), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=64, min_length=1), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=64, min_length=1 + ), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str", max_length=64, min_length=1), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # 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") + + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) -def build_delete_request_initial( - subscription_id: str, - resource_group_name: str, - resource_name: str, - **kwargs: Any +def build_delete_request( + resource_group_name: str, resource_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = kwargs.pop('api_version', "2020-03-01-preview") # type: str + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2020-03-01-preview") + ) + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}", + ) # 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', max_length=64, min_length=1), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=64, min_length=1), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=64, min_length=1 + ), + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str", max_length=64, min_length=1), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # 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_list_request( - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - api_version = kwargs.pop('api_version', "2020-03-01-preview") # type: str - accept = "application/json" +def build_list_request(subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2020-03-01-preview") + ) + accept = _headers.pop("Accept", "application/json") + # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.DigitalTwins/digitalTwinsInstances") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.DigitalTwins/digitalTwinsInstances" + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # 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_resource_group_request( - subscription_id: str, - resource_group_name: str, - **kwargs: Any -) -> HttpRequest: - api_version = kwargs.pop('api_version', "2020-03-01-preview") # type: str - accept = "application/json" +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: Literal["2020-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2020-03-01-preview") + ) + accept = _headers.pop("Accept", "application/json") + # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances", + ) # 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', max_length=64, min_length=1), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=64, min_length=1 + ), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # 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_check_name_availability_request( - subscription_id: str, - location: str, - *, - json: JSONType = None, - content: Any = None, - **kwargs: Any -) -> HttpRequest: - api_version = kwargs.pop('api_version', "2020-03-01-preview") # type: str - content_type = kwargs.pop('content_type', None) # type: Optional[str] - accept = "application/json" +def build_check_name_availability_request(location: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2020-03-01-preview") + ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.DigitalTwins/locations/{location}/checkNameAvailability") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.DigitalTwins/locations/{location}/checkNameAvailability", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), - "location": _SERIALIZER.url("location", location, 'str', min_length=3), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "location": _SERIALIZER.url("location", location, "str", min_length=3), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # 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") -class DigitalTwinsOperations(object): - """DigitalTwinsOperations operations. + return HttpRequest(method="POST", 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.digitaltwins.v2020_03_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. +class DigitalTwinsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.digitaltwins.v2020_03_01_preview.AzureDigitalTwinsManagementClient`'s + :attr:`digital_twins` 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, - resource_group_name: str, - resource_name: str, - **kwargs: Any - ) -> "_models.DigitalTwinsDescription": + def get(self, resource_group_name: str, resource_name: str, **kwargs: Any) -> _models.DigitalTwinsDescription: """Get DigitalTwinsInstances resource. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: DigitalTwinsDescription, or the result of cls(response) + :return: DigitalTwinsDescription or the result of cls(response) :rtype: ~azure.mgmt.digitaltwins.v2020_03_01_preview.models.DigitalTwinsDescription - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescription"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2020-03-01-preview") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2020-03-01-preview") + ) + cls: ClsType[_models.DigitalTwinsDescription] = kwargs.pop("cls", None) - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -368,91 +352,193 @@ def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}"} # type: ignore - + get.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } def _create_or_update_initial( self, resource_group_name: str, resource_name: str, - digital_twins_create: "_models.DigitalTwinsDescription", + digital_twins_create: Union[_models.DigitalTwinsDescription, IO], **kwargs: Any - ) -> "_models.DigitalTwinsDescription": - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescription"] + ) -> _models.DigitalTwinsDescription: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2020-03-01-preview") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(digital_twins_create, 'DigitalTwinsDescription') - - request = build_create_or_update_request_initial( - subscription_id=self._config.subscription_id, + api_version: Literal["2020-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2020-03-01-preview") + ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DigitalTwinsDescription] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(digital_twins_create, (IO, bytes)): + _content = digital_twins_create + else: + _json = self._serialize.body(digital_twins_create, "DigitalTwinsDescription") + + request = build_create_or_update_request( resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._create_or_update_initial.metadata['url'], + content=_content, + template_url=self._create_or_update_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized + return deserialized # type: ignore + + _create_or_update_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + digital_twins_create: _models.DigitalTwinsDescription, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.DigitalTwinsDescription]: + """Create or update the metadata of a DigitalTwinsInstance. The usual pattern to modify a property + is to retrieve the DigitalTwinsInstance and security metadata, and then combine them with the + modified values in a new body to update the DigitalTwinsInstance. - _create_or_update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}"} # type: ignore + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param digital_twins_create: The DigitalTwinsInstance and security metadata. Required. + :type digital_twins_create: + ~azure.mgmt.digitaltwins.v2020_03_01_preview.models.DigitalTwinsDescription + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either DigitalTwinsDescription or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2020_03_01_preview.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + digital_twins_create: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.DigitalTwinsDescription]: + """Create or update the metadata of a DigitalTwinsInstance. The usual pattern to modify a property + is to retrieve the DigitalTwinsInstance and security metadata, and then combine them with the + modified values in a new body to update the DigitalTwinsInstance. + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param digital_twins_create: The DigitalTwinsInstance and security metadata. Required. + :type digital_twins_create: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either DigitalTwinsDescription or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2020_03_01_preview.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace def begin_create_or_update( self, resource_group_name: str, resource_name: str, - digital_twins_create: "_models.DigitalTwinsDescription", + digital_twins_create: Union[_models.DigitalTwinsDescription, IO], **kwargs: Any - ) -> LROPoller["_models.DigitalTwinsDescription"]: + ) -> LROPoller[_models.DigitalTwinsDescription]: """Create or update the metadata of a DigitalTwinsInstance. The usual pattern to modify a property is to retrieve the DigitalTwinsInstance and security metadata, and then combine them with the modified values in a new body to update the DigitalTwinsInstance. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param digital_twins_create: The DigitalTwinsInstance and security metadata. + :param digital_twins_create: The DigitalTwinsInstance and security metadata. Is either a model + type or a IO type. Required. :type digital_twins_create: - ~azure.mgmt.digitaltwins.v2020_03_01_preview.models.DigitalTwinsDescription + ~azure.mgmt.digitaltwins.v2020_03_01_preview.models.DigitalTwinsDescription or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this @@ -465,17 +551,19 @@ def begin_create_or_update( cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2020_03_01_preview.models.DigitalTwinsDescription] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2020-03-01-preview") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescription"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2020-03-01-preview") ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DigitalTwinsDescription] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = self._create_or_update_initial( resource_group_name=resource_group_name, @@ -483,104 +571,133 @@ def begin_create_or_update( digital_twins_create=digital_twins_create, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - begin_create_or_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}"} # type: ignore + begin_create_or_update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } def _update_initial( self, resource_group_name: str, resource_name: str, - digital_twins_patch_description: "_models.DigitalTwinsPatchDescription", + digital_twins_patch_description: Union[_models.DigitalTwinsPatchDescription, IO], **kwargs: Any - ) -> Optional["_models.DigitalTwinsDescription"]: - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.DigitalTwinsDescription"]] + ) -> Optional[_models.DigitalTwinsDescription]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2020-03-01-preview") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(digital_twins_patch_description, 'DigitalTwinsPatchDescription') - - request = build_update_request_initial( - subscription_id=self._config.subscription_id, + api_version: Literal["2020-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2020-03-01-preview") + ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Optional[_models.DigitalTwinsDescription]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(digital_twins_patch_description, (IO, bytes)): + _content = digital_twins_patch_description + else: + _json = self._serialize.body(digital_twins_patch_description, "DigitalTwinsPatchDescription") + + request = build_update_request( resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._update_initial.metadata['url'], + content=_content, + template_url=self._update_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}"} # type: ignore - + _update_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } - @distributed_trace + @overload def begin_update( self, resource_group_name: str, resource_name: str, - digital_twins_patch_description: "_models.DigitalTwinsPatchDescription", + digital_twins_patch_description: _models.DigitalTwinsPatchDescription, + *, + content_type: str = "application/json", **kwargs: Any - ) -> LROPoller["_models.DigitalTwinsDescription"]: + ) -> LROPoller[_models.DigitalTwinsDescription]: """Update metadata of DigitalTwinsInstance. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str :param digital_twins_patch_description: The DigitalTwinsInstance and security metadata. + Required. :type digital_twins_patch_description: ~azure.mgmt.digitaltwins.v2020_03_01_preview.models.DigitalTwinsPatchDescription + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this @@ -593,17 +710,94 @@ def begin_update( cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2020_03_01_preview.models.DigitalTwinsDescription] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2020-03-01-preview") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescription"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval + + @overload + def begin_update( + self, + resource_group_name: str, + resource_name: str, + digital_twins_patch_description: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.DigitalTwinsDescription]: + """Update metadata of DigitalTwinsInstance. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param digital_twins_patch_description: The DigitalTwinsInstance and security metadata. + Required. + :type digital_twins_patch_description: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either DigitalTwinsDescription or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2020_03_01_preview.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_update( + self, + resource_group_name: str, + resource_name: str, + digital_twins_patch_description: Union[_models.DigitalTwinsPatchDescription, IO], + **kwargs: Any + ) -> LROPoller[_models.DigitalTwinsDescription]: + """Update metadata of DigitalTwinsInstance. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param digital_twins_patch_description: The DigitalTwinsInstance and security metadata. Is + either a model type or a IO type. Required. + :type digital_twins_patch_description: + ~azure.mgmt.digitaltwins.v2020_03_01_preview.models.DigitalTwinsPatchDescription or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either DigitalTwinsDescription or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2020_03_01_preview.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2020-03-01-preview") ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DigitalTwinsDescription] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = self._update_initial( resource_group_name=resource_group_name, @@ -611,94 +805,101 @@ def begin_update( digital_twins_patch_description=digital_twins_patch_description, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - begin_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}"} # type: ignore + begin_update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } def _delete_initial( - self, - resource_group_name: str, - resource_name: str, - **kwargs: Any - ) -> Optional["_models.DigitalTwinsDescription"]: - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.DigitalTwinsDescription"]] + self, resource_group_name: str, resource_name: str, **kwargs: Any + ) -> Optional[_models.DigitalTwinsDescription]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2020-03-01-preview") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - request = build_delete_request_initial( - subscription_id=self._config.subscription_id, + api_version: Literal["2020-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2020-03-01-preview") + ) + cls: ClsType[Optional[_models.DigitalTwinsDescription]] = kwargs.pop("cls", None) + + request = build_delete_request( resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._delete_initial.metadata['url'], + template_url=self._delete_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 202: - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _delete_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}"} # type: ignore - + _delete_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } @distributed_trace - def begin_delete( - self, - resource_group_name: str, - resource_name: str, - **kwargs: Any - ) -> LROPoller["_models.DigitalTwinsDescription"]: + def begin_delete(self, resource_group_name: str, resource_name: str, **kwargs: Any) -> LROPoller[None]: """Delete a DigitalTwinsInstance. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. @@ -712,86 +913,107 @@ def begin_delete( cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2020_03_01_preview.models.DigitalTwinsDescription] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2020-03-01-preview") # type: str - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescription"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2020-03-01-preview") ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = self._delete_initial( resource_group_name=resource_group_name, resource_name=resource_name, api_version=api_version, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - begin_delete.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}"} # type: ignore + begin_delete.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } @distributed_trace - def list( - self, - **kwargs: Any - ) -> Iterable["_models.DigitalTwinsDescriptionListResult"]: + def list(self, **kwargs: Any) -> Iterable["_models.DigitalTwinsDescription"]: """Get all the DigitalTwinsInstances in a subscription. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either DigitalTwinsDescriptionListResult or the result of + :return: An iterator like instance of either DigitalTwinsDescription or the result of cls(response) :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.digitaltwins.v2020_03_01_preview.models.DigitalTwinsDescriptionListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.paging.ItemPaged[~azure.mgmt.digitaltwins.v2020_03_01_preview.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2020-03-01-preview") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2020-03-01-preview") + ) + cls: ClsType[_models.DigitalTwinsDescriptionListResult] = kwargs.pop("cls", None) - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescriptionListResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list.metadata['url'], + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: - - request = build_list_request( - subscription_id=self._config.subscription_id, - api_version=api_version, - template_url=next_link, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) @@ -802,16 +1024,14 @@ def extract_data(pipeline_response): deserialized = self._deserialize("DigitalTwinsDescriptionListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -822,56 +1042,68 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.DigitalTwins/digitalTwinsInstances"} # type: ignore + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.DigitalTwins/digitalTwinsInstances"} @distributed_trace def list_by_resource_group( - self, - resource_group_name: str, - **kwargs: Any - ) -> Iterable["_models.DigitalTwinsDescriptionListResult"]: + self, resource_group_name: str, **kwargs: Any + ) -> Iterable["_models.DigitalTwinsDescription"]: """Get all the DigitalTwinsInstances in a resource group. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. 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 DigitalTwinsDescriptionListResult or the result of + :return: An iterator like instance of either DigitalTwinsDescription or the result of cls(response) :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.digitaltwins.v2020_03_01_preview.models.DigitalTwinsDescriptionListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.paging.ItemPaged[~azure.mgmt.digitaltwins.v2020_03_01_preview.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2020-03-01-preview") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2020-03-01-preview") + ) + cls: ClsType[_models.DigitalTwinsDescriptionListResult] = kwargs.pop("cls", None) - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescriptionListResult"] 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( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata['url'], + template_url=self.list_by_resource_group.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: - - request = build_list_by_resource_group_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - api_version=api_version, - template_url=next_link, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) @@ -882,16 +1114,14 @@ def extract_data(pipeline_response): deserialized = self._deserialize("DigitalTwinsDescriptionListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -902,59 +1132,129 @@ 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.DigitalTwins/digitalTwinsInstances"} # type: ignore + list_by_resource_group.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances" + } - @distributed_trace + @overload def check_name_availability( self, location: str, - digital_twins_instance_check_name: "_models.CheckNameRequest", + digital_twins_instance_check_name: _models.CheckNameRequest, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.CheckNameResult": + ) -> _models.CheckNameResult: """Check if a DigitalTwinsInstance name is available. - :param location: Location of DigitalTwinsInstance. + :param location: Location of DigitalTwinsInstance. Required. :type location: str :param digital_twins_instance_check_name: Set the name parameter in the DigitalTwinsInstanceCheckName structure to the name of the DigitalTwinsInstance to check. + Required. :type digital_twins_instance_check_name: ~azure.mgmt.digitaltwins.v2020_03_01_preview.models.CheckNameRequest + :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: CheckNameResult or the result of cls(response) + :rtype: ~azure.mgmt.digitaltwins.v2020_03_01_preview.models.CheckNameResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def check_name_availability( + self, + location: str, + digital_twins_instance_check_name: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.CheckNameResult: + """Check if a DigitalTwinsInstance name is available. + + :param location: Location of DigitalTwinsInstance. Required. + :type location: str + :param digital_twins_instance_check_name: Set the name parameter in the + DigitalTwinsInstanceCheckName structure to the name of the DigitalTwinsInstance to check. + Required. + :type digital_twins_instance_check_name: 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: CheckNameResult or the result of cls(response) + :rtype: ~azure.mgmt.digitaltwins.v2020_03_01_preview.models.CheckNameResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def check_name_availability( + self, location: str, digital_twins_instance_check_name: Union[_models.CheckNameRequest, IO], **kwargs: Any + ) -> _models.CheckNameResult: + """Check if a DigitalTwinsInstance name is available. + + :param location: Location of DigitalTwinsInstance. Required. + :type location: str + :param digital_twins_instance_check_name: Set the name parameter in the + DigitalTwinsInstanceCheckName structure to the name of the DigitalTwinsInstance to check. Is + either a model type or a IO type. Required. + :type digital_twins_instance_check_name: + ~azure.mgmt.digitaltwins.v2020_03_01_preview.models.CheckNameRequest 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: CheckNameResult, or the result of cls(response) + :return: CheckNameResult or the result of cls(response) :rtype: ~azure.mgmt.digitaltwins.v2020_03_01_preview.models.CheckNameResult - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.CheckNameResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', "2020-03-01-preview") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + api_version: Literal["2020-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2020-03-01-preview") + ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.CheckNameResult] = kwargs.pop("cls", None) - _json = self._serialize.body(digital_twins_instance_check_name, 'CheckNameRequest') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(digital_twins_instance_check_name, (IO, bytes)): + _content = digital_twins_instance_check_name + else: + _json = self._serialize.body(digital_twins_instance_check_name, "CheckNameRequest") request = build_check_name_availability_request( - subscription_id=self._config.subscription_id, location=location, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self.check_name_availability.metadata['url'], + content=_content, + template_url=self.check_name_availability.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -962,12 +1262,13 @@ def check_name_availability( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('CheckNameResult', pipeline_response) + deserialized = self._deserialize("CheckNameResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - check_name_availability.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.DigitalTwins/locations/{location}/checkNameAvailability"} # type: ignore - + check_name_availability.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.DigitalTwins/locations/{location}/checkNameAvailability" + } diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/operations/_operations.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/operations/_operations.py index 603ff1bea5550..2d081064683d8 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/operations/_operations.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/operations/_operations.py @@ -6,108 +6,131 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, Callable, Dict, Iterable, Optional, TypeVar - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from ..._serialization import Serializer from .._vendor import _convert_request -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_list_request( - **kwargs: Any -) -> HttpRequest: - api_version = kwargs.pop('api_version', "2020-03-01-preview") # type: str - accept = "application/json" +def build_list_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2020-03-01-preview") + ) + accept = _headers.pop("Accept", "application/json") + # Construct URL _url = kwargs.pop("template_url", "/providers/Microsoft.DigitalTwins/operations") # Construct parameters - _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - _query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - _header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="GET", - url=_url, - params=_query_parameters, - headers=_header_parameters, - **kwargs - ) + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") -class Operations(object): - """Operations operations. + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.digitaltwins.v2020_03_01_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. +class Operations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.digitaltwins.v2020_03_01_preview.AzureDigitalTwinsManagementClient`'s + :attr:`operations` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace - def list( - self, - **kwargs: Any - ) -> Iterable["_models.OperationListResult"]: + def list(self, **kwargs: Any) -> Iterable["_models.Operation"]: """Lists all of the available DigitalTwins service REST API operations. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either OperationListResult or the result of cls(response) + :return: An iterator like instance of either Operation or the result of cls(response) :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.digitaltwins.v2020_03_01_preview.models.OperationListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.paging.ItemPaged[~azure.mgmt.digitaltwins.v2020_03_01_preview.models.Operation] + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2020-03-01-preview") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-03-01-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2020-03-01-preview") + ) + cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) - cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationListResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( api_version=api_version, - template_url=self.list.metadata['url'], + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: - - request = build_list_request( - api_version=api_version, - template_url=next_link, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) @@ -118,16 +141,14 @@ def extract_data(pipeline_response): deserialized = self._deserialize("OperationListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -138,8 +159,6 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/providers/Microsoft.DigitalTwins/operations"} # type: ignore + list.metadata = {"url": "/providers/Microsoft.DigitalTwins/operations"} diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/operations/_patch.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/operations/_patch.py new file mode 100644 index 0000000000000..f7dd32510333d --- /dev/null +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_03_01_preview/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/__init__.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/__init__.py index 36b558a96cdfd..3d416a868dd25 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/__init__.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/__init__.py @@ -10,9 +10,17 @@ from ._version import VERSION __version__ = VERSION -__all__ = ['AzureDigitalTwinsManagementClient'] -# `._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 * # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "AzureDigitalTwinsManagementClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/_azure_digital_twins_management_client.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/_azure_digital_twins_management_client.py index 881f41b741a75..1243aafd13fdc 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/_azure_digital_twins_management_client.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/_azure_digital_twins_management_client.py @@ -9,12 +9,11 @@ from copy import deepcopy from typing import Any, TYPE_CHECKING -from msrest import Deserializer, Serializer - from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient -from . import models +from . import models as _models +from .._serialization import Deserializer, Serializer from ._configuration import AzureDigitalTwinsManagementClientConfiguration from .operations import DigitalTwinsEndpointOperations, DigitalTwinsOperations, Operations @@ -22,7 +21,8 @@ # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class AzureDigitalTwinsManagementClient: + +class AzureDigitalTwinsManagementClient: # pylint: disable=client-accepts-api-version-keyword """Azure Digital Twins Client for managing DigitalTwinsInstance. :ivar digital_twins: DigitalTwinsOperations operations @@ -32,9 +32,9 @@ class AzureDigitalTwinsManagementClient: azure.mgmt.digitaltwins.v2020_10_31.operations.DigitalTwinsEndpointOperations :ivar operations: Operations operations :vartype operations: azure.mgmt.digitaltwins.v2020_10_31.operations.Operations - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: The subscription identifier. + :param subscription_id: The subscription identifier. Required. :type subscription_id: str :param base_url: Service URL. Default value is "https://management.azure.com". :type base_url: str @@ -52,23 +52,22 @@ def __init__( base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: - self._config = AzureDigitalTwinsManagementClientConfiguration(credential=credential, subscription_id=subscription_id, **kwargs) + self._config = AzureDigitalTwinsManagementClientConfiguration( + credential=credential, subscription_id=subscription_id, **kwargs + ) self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) - client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) self._deserialize = Deserializer(client_models) self._serialize.client_side_validation = False self.digital_twins = DigitalTwinsOperations(self._client, self._config, self._serialize, self._deserialize) - self.digital_twins_endpoint = DigitalTwinsEndpointOperations(self._client, self._config, self._serialize, self._deserialize) + self.digital_twins_endpoint = DigitalTwinsEndpointOperations( + self._client, self._config, self._serialize, self._deserialize + ) self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) - - def _send_request( - self, - request: HttpRequest, - **kwargs: Any - ) -> HttpResponse: + 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 @@ -77,7 +76,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 @@ -90,15 +89,12 @@ def _send_request( request_copy.url = self._client.format_url(request_copy.url) return self._client.send_request(request_copy, **kwargs) - def close(self): - # type: () -> None + def close(self) -> None: self._client.close() - def __enter__(self): - # type: () -> AzureDigitalTwinsManagementClient + def __enter__(self) -> "AzureDigitalTwinsManagementClient": self._client.__enter__() return self - def __exit__(self, *exc_details): - # type: (Any) -> None + def __exit__(self, *exc_details) -> None: self._client.__exit__(*exc_details) diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/_configuration.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/_configuration.py index b0e5a36c6ca5d..bb0cf50d4ac17 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/_configuration.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/_configuration.py @@ -6,6 +6,7 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, TYPE_CHECKING from azure.core.configuration import Configuration @@ -14,6 +15,11 @@ from ._version import VERSION +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports + if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential @@ -25,23 +31,18 @@ class AzureDigitalTwinsManagementClientConfiguration(Configuration): # pylint: Note that all parameters used to create this instance are saved as instance attributes. - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: The subscription identifier. + :param subscription_id: The subscription identifier. Required. :type subscription_id: str :keyword api_version: Api Version. Default value is "2020-10-31". 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(AzureDigitalTwinsManagementClientConfiguration, self).__init__(**kwargs) - api_version = kwargs.pop('api_version', "2020-10-31") # type: str + api_version: Literal["2020-10-31"] = kwargs.pop("api_version", "2020-10-31") if credential is None: raise ValueError("Parameter 'credential' must not be None.") @@ -51,23 +52,21 @@ def __init__( self.credential = credential self.subscription_id = subscription_id self.api_version = api_version - self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'mgmt-digitaltwins/{}'.format(VERSION)) + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-digitaltwins/{}".format(VERSION)) self._configure(**kwargs) - def _configure( - self, - **kwargs # type: Any - ): - # type: (...) -> None - self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get('retry_policy') or policies.RetryPolicy(**kwargs) - self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get('redirect_policy') or policies.RedirectPolicy(**kwargs) - self.authentication_policy = kwargs.get('authentication_policy') + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: - self.authentication_policy = ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs) + self.authentication_policy = ARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/_metadata.json b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/_metadata.json index 81899687a9cc4..f50be20b59387 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/_metadata.json +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/_metadata.json @@ -10,20 +10,20 @@ "azure_arm": true, "has_lro_operations": true, "client_side_validation": false, - "sync_imports": "{\"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}, \"regular\": {\"azurecore\": {\"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"], \"azure.mgmt.core\": [\"ARMPipelineClient\"]}, \"local\": {\"._configuration\": [\"AzureDigitalTwinsManagementClientConfiguration\"]}, \"thirdparty\": {\"msrest\": [\"Deserializer\", \"Serializer\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}}", - "async_imports": "{\"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"], \"azure.core.credentials\": [\"TokenCredential\"]}}, \"regular\": {\"azurecore\": {\"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"], \"azure.mgmt.core\": [\"AsyncARMPipelineClient\"]}, \"local\": {\"._configuration\": [\"AzureDigitalTwinsManagementClientConfiguration\"]}, \"thirdparty\": {\"msrest\": [\"Deserializer\", \"Serializer\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}}" + "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"AzureDigitalTwinsManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"AzureDigitalTwinsManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "global_parameters": { "sync": { "credential": { - "signature": "credential, # type: \"TokenCredential\"", - "description": "Credential needed for the client to connect to Azure.", + "signature": "credential: \"TokenCredential\",", + "description": "Credential needed for the client to connect to Azure. Required.", "docstring_type": "~azure.core.credentials.TokenCredential", "required": true }, "subscription_id": { - "signature": "subscription_id, # type: str", - "description": "The subscription identifier.", + "signature": "subscription_id: str,", + "description": "The subscription identifier. Required.", "docstring_type": "str", "required": true } @@ -31,13 +31,13 @@ "async": { "credential": { "signature": "credential: \"AsyncTokenCredential\",", - "description": "Credential needed for the client to connect to Azure.", + "description": "Credential needed for the client to connect to Azure. Required.", "docstring_type": "~azure.core.credentials_async.AsyncTokenCredential", "required": true }, "subscription_id": { "signature": "subscription_id: str,", - "description": "The subscription identifier.", + "description": "The subscription identifier. Required.", "docstring_type": "str", "required": true } @@ -48,19 +48,19 @@ "service_client_specific": { "sync": { "api_version": { - "signature": "api_version=None, # type: Optional[str]", + "signature": "api_version: Optional[str]=None,", "description": "API version to use if no profile is provided, or if missing in profile.", "docstring_type": "str", "required": false }, "base_url": { - "signature": "base_url=\"https://management.azure.com\", # type: str", + "signature": "base_url: str = \"https://management.azure.com\",", "description": "Service URL", "docstring_type": "str", "required": false }, "profile": { - "signature": "profile=KnownProfiles.default, # type: KnownProfiles", + "signature": "profile: KnownProfiles=KnownProfiles.default,", "description": "A profile definition, from KnownProfiles to dict.", "docstring_type": "azure.profiles.KnownProfiles", "required": false @@ -101,4 +101,4 @@ "digital_twins_endpoint": "DigitalTwinsEndpointOperations", "operations": "Operations" } -} \ No newline at end of file +} diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/_patch.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/_patch.py index 74e48ecd07cf3..f99e77fef9861 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/_patch.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/_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/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/_vendor.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/_vendor.py index 138f663c53a4e..9aad73fc743e7 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/_vendor.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/_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/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/_version.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/_version.py index a55d01326aa81..e5754a47ce68f 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/_version.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "6.2.0" +VERSION = "1.0.0b1" diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/aio/__init__.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/aio/__init__.py index 20a6435cbbdb2..e4da5a5dc30c1 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/aio/__init__.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/aio/__init__.py @@ -7,9 +7,17 @@ # -------------------------------------------------------------------------- from ._azure_digital_twins_management_client import AzureDigitalTwinsManagementClient -__all__ = ['AzureDigitalTwinsManagementClient'] -# `._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 * # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "AzureDigitalTwinsManagementClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/aio/_azure_digital_twins_management_client.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/aio/_azure_digital_twins_management_client.py index db9584cdfd109..9b3de706f75c7 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/aio/_azure_digital_twins_management_client.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/aio/_azure_digital_twins_management_client.py @@ -9,12 +9,11 @@ from copy import deepcopy from typing import Any, Awaitable, TYPE_CHECKING -from msrest import Deserializer, Serializer - from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient -from .. import models +from .. import models as _models +from ..._serialization import Deserializer, Serializer from ._configuration import AzureDigitalTwinsManagementClientConfiguration from .operations import DigitalTwinsEndpointOperations, DigitalTwinsOperations, Operations @@ -22,7 +21,8 @@ # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class AzureDigitalTwinsManagementClient: + +class AzureDigitalTwinsManagementClient: # pylint: disable=client-accepts-api-version-keyword """Azure Digital Twins Client for managing DigitalTwinsInstance. :ivar digital_twins: DigitalTwinsOperations operations @@ -33,9 +33,9 @@ class AzureDigitalTwinsManagementClient: azure.mgmt.digitaltwins.v2020_10_31.aio.operations.DigitalTwinsEndpointOperations :ivar operations: Operations operations :vartype operations: azure.mgmt.digitaltwins.v2020_10_31.aio.operations.Operations - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: The subscription identifier. + :param subscription_id: The subscription identifier. Required. :type subscription_id: str :param base_url: Service URL. Default value is "https://management.azure.com". :type base_url: str @@ -53,23 +53,22 @@ def __init__( base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: - self._config = AzureDigitalTwinsManagementClientConfiguration(credential=credential, subscription_id=subscription_id, **kwargs) + self._config = AzureDigitalTwinsManagementClientConfiguration( + credential=credential, subscription_id=subscription_id, **kwargs + ) self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) - client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) self._deserialize = Deserializer(client_models) self._serialize.client_side_validation = False self.digital_twins = DigitalTwinsOperations(self._client, self._config, self._serialize, self._deserialize) - self.digital_twins_endpoint = DigitalTwinsEndpointOperations(self._client, self._config, self._serialize, self._deserialize) + self.digital_twins_endpoint = DigitalTwinsEndpointOperations( + self._client, self._config, self._serialize, self._deserialize + ) self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) - - def _send_request( - self, - request: HttpRequest, - **kwargs: Any - ) -> Awaitable[AsyncHttpResponse]: + 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 @@ -78,7 +77,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/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/aio/_configuration.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/aio/_configuration.py index 4ac68535db956..0e464db5ca0c1 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/aio/_configuration.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/aio/_configuration.py @@ -6,6 +6,7 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, TYPE_CHECKING from azure.core.configuration import Configuration @@ -14,6 +15,11 @@ from .._version import VERSION +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports + if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential @@ -25,23 +31,18 @@ class AzureDigitalTwinsManagementClientConfiguration(Configuration): # pylint: Note that all parameters used to create this instance are saved as instance attributes. - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: The subscription identifier. + :param subscription_id: The subscription identifier. Required. :type subscription_id: str :keyword api_version: Api Version. Default value is "2020-10-31". 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(AzureDigitalTwinsManagementClientConfiguration, self).__init__(**kwargs) - api_version = kwargs.pop('api_version', "2020-10-31") # type: str + api_version: Literal["2020-10-31"] = kwargs.pop("api_version", "2020-10-31") if credential is None: raise ValueError("Parameter 'credential' must not be None.") @@ -51,22 +52,21 @@ def __init__( self.credential = credential self.subscription_id = subscription_id self.api_version = api_version - self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'mgmt-digitaltwins/{}'.format(VERSION)) + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-digitaltwins/{}".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/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/aio/_patch.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/aio/_patch.py index 74e48ecd07cf3..f99e77fef9861 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/aio/_patch.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/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/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/aio/operations/__init__.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/aio/operations/__init__.py index a9cda9c99062e..a2f402ab0c76f 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/aio/operations/__init__.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/aio/operations/__init__.py @@ -10,8 +10,14 @@ from ._digital_twins_endpoint_operations import DigitalTwinsEndpointOperations from ._operations import Operations +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + __all__ = [ - 'DigitalTwinsOperations', - 'DigitalTwinsEndpointOperations', - 'Operations', + "DigitalTwinsOperations", + "DigitalTwinsEndpointOperations", + "Operations", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/aio/operations/_digital_twins_endpoint_operations.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/aio/operations/_digital_twins_endpoint_operations.py index 83ed3a8fdbc84..621fd541a4618 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/aio/operations/_digital_twins_endpoint_operations.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/aio/operations/_digital_twins_endpoint_operations.py @@ -6,96 +6,124 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar, Union +import sys +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models from ..._vendor import _convert_request -from ...operations._digital_twins_endpoint_operations import build_create_or_update_request_initial, build_delete_request_initial, build_get_request, build_list_request -T = TypeVar('T') +from ...operations._digital_twins_endpoint_operations import ( + build_create_or_update_request, + build_delete_request, + build_get_request, + build_list_request, +) + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class DigitalTwinsEndpointOperations: - """DigitalTwinsEndpointOperations 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 DigitalTwinsEndpointOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.digitaltwins.v2020_10_31.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.digitaltwins.v2020_10_31.aio.AzureDigitalTwinsManagementClient`'s + :attr:`digital_twins_endpoint` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list( - self, - resource_group_name: str, - resource_name: str, - **kwargs: Any - ) -> AsyncIterable["_models.DigitalTwinsEndpointResourceListResult"]: + self, resource_group_name: str, resource_name: str, **kwargs: Any + ) -> AsyncIterable["_models.DigitalTwinsEndpointResource"]: """Get DigitalTwinsInstance Endpoints. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either DigitalTwinsEndpointResourceListResult or the - result of cls(response) + :return: An iterator like instance of either DigitalTwinsEndpointResource or the result of + cls(response) :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.digitaltwins.v2020_10_31.models.DigitalTwinsEndpointResourceListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.digitaltwins.v2020_10_31.models.DigitalTwinsEndpointResource] + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2020-10-31") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-31")) + cls: ClsType[_models.DigitalTwinsEndpointResourceListResult] = kwargs.pop("cls", None) - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsEndpointResourceListResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list.metadata['url'], + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: - - request = build_list_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - resource_name=resource_name, - api_version=api_version, - template_url=next_link, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) @@ -106,16 +134,14 @@ async def extract_data(pipeline_response): deserialized = self._deserialize("DigitalTwinsEndpointResourceListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -126,59 +152,61 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints"} # type: ignore + list.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints" + } @distributed_trace_async async def get( - self, - resource_group_name: str, - resource_name: str, - endpoint_name: str, - **kwargs: Any - ) -> "_models.DigitalTwinsEndpointResource": + self, resource_group_name: str, resource_name: str, endpoint_name: str, **kwargs: Any + ) -> _models.DigitalTwinsEndpointResource: """Get DigitalTwinsInstances Endpoint. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param endpoint_name: Name of Endpoint Resource. + :param endpoint_name: Name of Endpoint Resource. Required. :type endpoint_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: DigitalTwinsEndpointResource, or the result of cls(response) + :return: DigitalTwinsEndpointResource or the result of cls(response) :rtype: ~azure.mgmt.digitaltwins.v2020_10_31.models.DigitalTwinsEndpointResource - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsEndpointResource"] 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', "2020-10-31") # type: str + api_version: Literal["2020-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-31")) + cls: ClsType[_models.DigitalTwinsEndpointResource] = kwargs.pop("cls", None) - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, endpoint_name=endpoint_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -186,72 +214,172 @@ async def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('DigitalTwinsEndpointResource', pipeline_response) + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}"} # type: ignore - + get.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}" + } async def _create_or_update_initial( self, resource_group_name: str, resource_name: str, endpoint_name: str, - endpoint_description: "_models.DigitalTwinsEndpointResource", + endpoint_description: Union[_models.DigitalTwinsEndpointResource, IO], **kwargs: Any - ) -> "_models.DigitalTwinsEndpointResource": - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsEndpointResource"] + ) -> _models.DigitalTwinsEndpointResource: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2020-10-31") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(endpoint_description, 'DigitalTwinsEndpointResource') + api_version: Literal["2020-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DigitalTwinsEndpointResource] = kwargs.pop("cls", None) - request = build_create_or_update_request_initial( - subscription_id=self._config.subscription_id, + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(endpoint_description, (IO, bytes)): + _content = endpoint_description + else: + _json = self._serialize.body(endpoint_description, "DigitalTwinsEndpointResource") + + request = build_create_or_update_request( resource_group_name=resource_group_name, resource_name=resource_name, 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_initial.metadata['url'], + content=_content, + template_url=self._create_or_update_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('DigitalTwinsEndpointResource', pipeline_response) + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('DigitalTwinsEndpointResource', pipeline_response) + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized + return deserialized # type: ignore + + _create_or_update_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}" + } + + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + endpoint_name: str, + endpoint_description: _models.DigitalTwinsEndpointResource, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.DigitalTwinsEndpointResource]: + """Create or update DigitalTwinsInstance endpoint. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param endpoint_name: Name of Endpoint Resource. Required. + :type endpoint_name: str + :param endpoint_description: The DigitalTwinsInstance endpoint metadata and security metadata. + Required. + :type endpoint_description: + ~azure.mgmt.digitaltwins.v2020_10_31.models.DigitalTwinsEndpointResource + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either DigitalTwinsEndpointResource or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2020_10_31.models.DigitalTwinsEndpointResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ - _create_or_update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}"} # type: ignore + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + endpoint_name: str, + endpoint_description: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.DigitalTwinsEndpointResource]: + """Create or update DigitalTwinsInstance endpoint. + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param endpoint_name: Name of Endpoint Resource. Required. + :type endpoint_name: str + :param endpoint_description: The DigitalTwinsInstance endpoint metadata and security metadata. + Required. + :type endpoint_description: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either DigitalTwinsEndpointResource or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2020_10_31.models.DigitalTwinsEndpointResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace_async async def begin_create_or_update( @@ -259,21 +387,25 @@ async def begin_create_or_update( resource_group_name: str, resource_name: str, endpoint_name: str, - endpoint_description: "_models.DigitalTwinsEndpointResource", + endpoint_description: Union[_models.DigitalTwinsEndpointResource, IO], **kwargs: Any - ) -> AsyncLROPoller["_models.DigitalTwinsEndpointResource"]: + ) -> AsyncLROPoller[_models.DigitalTwinsEndpointResource]: """Create or update DigitalTwinsInstance endpoint. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param endpoint_name: Name of Endpoint Resource. + :param endpoint_name: Name of Endpoint Resource. Required. :type endpoint_name: str :param endpoint_description: The DigitalTwinsInstance endpoint metadata and security metadata. + Is either a model type or a IO type. Required. :type endpoint_description: - ~azure.mgmt.digitaltwins.v2020_10_31.models.DigitalTwinsEndpointResource + ~azure.mgmt.digitaltwins.v2020_10_31.models.DigitalTwinsEndpointResource or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for @@ -286,17 +418,17 @@ async def begin_create_or_update( result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2020_10_31.models.DigitalTwinsEndpointResource] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2020-10-31") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsEndpointResource"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DigitalTwinsEndpointResource] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = await self._create_or_update_initial( resource_group_name=resource_group_name, @@ -305,102 +437,107 @@ async def begin_create_or_update( endpoint_description=endpoint_description, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('DigitalTwinsEndpointResource', pipeline_response) + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - begin_create_or_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}"} # type: ignore + begin_create_or_update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}" + } async def _delete_initial( - self, - resource_group_name: str, - resource_name: str, - endpoint_name: str, - **kwargs: Any - ) -> Optional["_models.DigitalTwinsEndpointResource"]: - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.DigitalTwinsEndpointResource"]] + self, resource_group_name: str, resource_name: str, endpoint_name: str, **kwargs: Any + ) -> Optional[_models.DigitalTwinsEndpointResource]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2020-10-31") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - request = build_delete_request_initial( - subscription_id=self._config.subscription_id, + api_version: Literal["2020-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-31")) + cls: ClsType[Optional[_models.DigitalTwinsEndpointResource]] = kwargs.pop("cls", None) + + request = build_delete_request( resource_group_name=resource_group_name, resource_name=resource_name, endpoint_name=endpoint_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._delete_initial.metadata['url'], + template_url=self._delete_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('DigitalTwinsEndpointResource', pipeline_response) + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) if response.status_code == 202: - deserialized = self._deserialize('DigitalTwinsEndpointResource', pipeline_response) + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _delete_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}"} # type: ignore - + _delete_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}" + } @distributed_trace_async async def begin_delete( - self, - resource_group_name: str, - resource_name: str, - endpoint_name: str, - **kwargs: Any - ) -> AsyncLROPoller["_models.DigitalTwinsEndpointResource"]: + self, resource_group_name: str, resource_name: str, endpoint_name: str, **kwargs: Any + ) -> AsyncLROPoller[_models.DigitalTwinsEndpointResource]: """Delete a DigitalTwinsInstance endpoint. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param endpoint_name: Name of Endpoint Resource. + :param endpoint_name: Name of Endpoint Resource. Required. :type endpoint_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. @@ -414,45 +551,50 @@ async def begin_delete( result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2020_10_31.models.DigitalTwinsEndpointResource] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2020-10-31") # type: str - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsEndpointResource"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-31")) + cls: ClsType[_models.DigitalTwinsEndpointResource] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = await self._delete_initial( resource_group_name=resource_group_name, resource_name=resource_name, endpoint_name=endpoint_name, api_version=api_version, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('DigitalTwinsEndpointResource', pipeline_response) + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - begin_delete.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}"} # type: ignore + begin_delete.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}" + } diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/aio/operations/_digital_twins_operations.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/aio/operations/_digital_twins_operations.py index a5fe5d59cd162..0e09d4527a849 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/aio/operations/_digital_twins_operations.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/aio/operations/_digital_twins_operations.py @@ -6,90 +6,112 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar, Union +import sys +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models from ..._vendor import _convert_request -from ...operations._digital_twins_operations import build_check_name_availability_request, build_create_or_update_request_initial, build_delete_request_initial, build_get_request, build_list_by_resource_group_request, build_list_request, build_update_request -T = TypeVar('T') +from ...operations._digital_twins_operations import ( + build_check_name_availability_request, + build_create_or_update_request, + build_delete_request, + build_get_request, + build_list_by_resource_group_request, + build_list_request, + build_update_request, +) + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class DigitalTwinsOperations: - """DigitalTwinsOperations 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 DigitalTwinsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.digitaltwins.v2020_10_31.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.digitaltwins.v2020_10_31.aio.AzureDigitalTwinsManagementClient`'s + :attr:`digital_twins` 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, - resource_group_name: str, - resource_name: str, - **kwargs: Any - ) -> "_models.DigitalTwinsDescription": + async def get(self, resource_group_name: str, resource_name: str, **kwargs: Any) -> _models.DigitalTwinsDescription: """Get DigitalTwinsInstances resource. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: DigitalTwinsDescription, or the result of cls(response) + :return: DigitalTwinsDescription or the result of cls(response) :rtype: ~azure.mgmt.digitaltwins.v2020_10_31.models.DigitalTwinsDescription - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescription"] 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', "2020-10-31") # type: str + api_version: Literal["2020-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-31")) + cls: ClsType[_models.DigitalTwinsDescription] = kwargs.pop("cls", None) - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -97,90 +119,190 @@ async def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}"} # type: ignore - + get.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } async def _create_or_update_initial( self, resource_group_name: str, resource_name: str, - digital_twins_create: "_models.DigitalTwinsDescription", + digital_twins_create: Union[_models.DigitalTwinsDescription, IO], **kwargs: Any - ) -> "_models.DigitalTwinsDescription": - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescription"] + ) -> _models.DigitalTwinsDescription: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2020-10-31") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(digital_twins_create, 'DigitalTwinsDescription') + api_version: Literal["2020-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DigitalTwinsDescription] = kwargs.pop("cls", None) - request = build_create_or_update_request_initial( - subscription_id=self._config.subscription_id, + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(digital_twins_create, (IO, bytes)): + _content = digital_twins_create + else: + _json = self._serialize.body(digital_twins_create, "DigitalTwinsDescription") + + request = build_create_or_update_request( resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._create_or_update_initial.metadata['url'], + content=_content, + template_url=self._create_or_update_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized + return deserialized # type: ignore - _create_or_update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}"} # type: ignore + _create_or_update_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + digital_twins_create: _models.DigitalTwinsDescription, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.DigitalTwinsDescription]: + """Create or update the metadata of a DigitalTwinsInstance. The usual pattern to modify a property + is to retrieve the DigitalTwinsInstance and security metadata, and then combine them with the + modified values in a new body to update the DigitalTwinsInstance. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param digital_twins_create: The DigitalTwinsInstance and security metadata. Required. + :type digital_twins_create: ~azure.mgmt.digitaltwins.v2020_10_31.models.DigitalTwinsDescription + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either DigitalTwinsDescription or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2020_10_31.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + digital_twins_create: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.DigitalTwinsDescription]: + """Create or update the metadata of a DigitalTwinsInstance. The usual pattern to modify a property + is to retrieve the DigitalTwinsInstance and security metadata, and then combine them with the + modified values in a new body to update the DigitalTwinsInstance. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param digital_twins_create: The DigitalTwinsInstance and security metadata. Required. + :type digital_twins_create: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either DigitalTwinsDescription or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2020_10_31.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace_async async def begin_create_or_update( self, resource_group_name: str, resource_name: str, - digital_twins_create: "_models.DigitalTwinsDescription", + digital_twins_create: Union[_models.DigitalTwinsDescription, IO], **kwargs: Any - ) -> AsyncLROPoller["_models.DigitalTwinsDescription"]: + ) -> AsyncLROPoller[_models.DigitalTwinsDescription]: """Create or update the metadata of a DigitalTwinsInstance. The usual pattern to modify a property is to retrieve the DigitalTwinsInstance and security metadata, and then combine them with the modified values in a new body to update the DigitalTwinsInstance. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param digital_twins_create: The DigitalTwinsInstance and security metadata. + :param digital_twins_create: The DigitalTwinsInstance and security metadata. Is either a model + type or a IO type. Required. :type digital_twins_create: ~azure.mgmt.digitaltwins.v2020_10_31.models.DigitalTwinsDescription + or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for @@ -193,17 +315,17 @@ async def begin_create_or_update( result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2020_10_31.models.DigitalTwinsDescription] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2020-10-31") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescription"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DigitalTwinsDescription] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = await self._create_or_update_initial( resource_group_name=resource_group_name, @@ -211,84 +333,166 @@ async def begin_create_or_update( digital_twins_create=digital_twins_create, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - begin_create_or_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}"} # type: ignore + begin_create_or_update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } - @distributed_trace_async + @overload async def update( self, resource_group_name: str, resource_name: str, - digital_twins_patch_description: "_models.DigitalTwinsPatchDescription", + digital_twins_patch_description: _models.DigitalTwinsPatchDescription, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.DigitalTwinsDescription": + ) -> _models.DigitalTwinsDescription: """Update metadata of DigitalTwinsInstance. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str :param digital_twins_patch_description: The DigitalTwinsInstance and security metadata. + Required. :type digital_twins_patch_description: ~azure.mgmt.digitaltwins.v2020_10_31.models.DigitalTwinsPatchDescription + :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: DigitalTwinsDescription or the result of cls(response) + :rtype: ~azure.mgmt.digitaltwins.v2020_10_31.models.DigitalTwinsDescription + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def update( + self, + resource_group_name: str, + resource_name: str, + digital_twins_patch_description: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.DigitalTwinsDescription: + """Update metadata of DigitalTwinsInstance. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param digital_twins_patch_description: The DigitalTwinsInstance and security metadata. + Required. + :type digital_twins_patch_description: 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: DigitalTwinsDescription or the result of cls(response) + :rtype: ~azure.mgmt.digitaltwins.v2020_10_31.models.DigitalTwinsDescription + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def update( + self, + resource_group_name: str, + resource_name: str, + digital_twins_patch_description: Union[_models.DigitalTwinsPatchDescription, IO], + **kwargs: Any + ) -> _models.DigitalTwinsDescription: + """Update metadata of DigitalTwinsInstance. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param digital_twins_patch_description: The DigitalTwinsInstance and security metadata. Is + either a model type or a IO type. Required. + :type digital_twins_patch_description: + ~azure.mgmt.digitaltwins.v2020_10_31.models.DigitalTwinsPatchDescription 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: DigitalTwinsDescription, or the result of cls(response) + :return: DigitalTwinsDescription or the result of cls(response) :rtype: ~azure.mgmt.digitaltwins.v2020_10_31.models.DigitalTwinsDescription - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescription"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', "2020-10-31") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + api_version: Literal["2020-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DigitalTwinsDescription] = kwargs.pop("cls", None) - _json = self._serialize.body(digital_twins_patch_description, 'DigitalTwinsPatchDescription') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(digital_twins_patch_description, (IO, bytes)): + _content = digital_twins_patch_description + else: + _json = self._serialize.body(digital_twins_patch_description, "DigitalTwinsPatchDescription") request = build_update_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_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) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -296,80 +500,83 @@ async def update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}"} # type: ignore - + update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } async def _delete_initial( - self, - resource_group_name: str, - resource_name: str, - **kwargs: Any - ) -> Optional["_models.DigitalTwinsDescription"]: - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.DigitalTwinsDescription"]] + self, resource_group_name: str, resource_name: str, **kwargs: Any + ) -> Optional[_models.DigitalTwinsDescription]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2020-10-31") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - request = build_delete_request_initial( - subscription_id=self._config.subscription_id, + api_version: Literal["2020-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-31")) + cls: ClsType[Optional[_models.DigitalTwinsDescription]] = kwargs.pop("cls", None) + + request = build_delete_request( resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._delete_initial.metadata['url'], + template_url=self._delete_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if response.status_code == 202: - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _delete_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}"} # type: ignore - + _delete_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } @distributed_trace_async async def begin_delete( - self, - resource_group_name: str, - resource_name: str, - **kwargs: Any - ) -> AsyncLROPoller["_models.DigitalTwinsDescription"]: + self, resource_group_name: str, resource_name: str, **kwargs: Any + ) -> AsyncLROPoller[_models.DigitalTwinsDescription]: """Delete a DigitalTwinsInstance. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. @@ -383,86 +590,103 @@ async def begin_delete( result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2020_10_31.models.DigitalTwinsDescription] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2020-10-31") # type: str - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescription"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-31")) + cls: ClsType[_models.DigitalTwinsDescription] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = await self._delete_initial( resource_group_name=resource_group_name, resource_name=resource_name, api_version=api_version, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - begin_delete.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}"} # type: ignore + begin_delete.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } @distributed_trace - def list( - self, - **kwargs: Any - ) -> AsyncIterable["_models.DigitalTwinsDescriptionListResult"]: + def list(self, **kwargs: Any) -> AsyncIterable["_models.DigitalTwinsDescription"]: """Get all the DigitalTwinsInstances in a subscription. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either DigitalTwinsDescriptionListResult or the result of + :return: An iterator like instance of either DigitalTwinsDescription or the result of cls(response) :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.digitaltwins.v2020_10_31.models.DigitalTwinsDescriptionListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.digitaltwins.v2020_10_31.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2020-10-31") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-31")) + cls: ClsType[_models.DigitalTwinsDescriptionListResult] = kwargs.pop("cls", None) - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescriptionListResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list.metadata['url'], + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: - - request = build_list_request( - subscription_id=self._config.subscription_id, - api_version=api_version, - template_url=next_link, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) @@ -473,16 +697,14 @@ async def extract_data(pipeline_response): deserialized = self._deserialize("DigitalTwinsDescriptionListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -493,56 +715,66 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.DigitalTwins/digitalTwinsInstances"} # type: ignore + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.DigitalTwins/digitalTwinsInstances"} @distributed_trace def list_by_resource_group( - self, - resource_group_name: str, - **kwargs: Any - ) -> AsyncIterable["_models.DigitalTwinsDescriptionListResult"]: + self, resource_group_name: str, **kwargs: Any + ) -> AsyncIterable["_models.DigitalTwinsDescription"]: """Get all the DigitalTwinsInstances in a resource group. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. 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 DigitalTwinsDescriptionListResult or the result of + :return: An iterator like instance of either DigitalTwinsDescription or the result of cls(response) :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.digitaltwins.v2020_10_31.models.DigitalTwinsDescriptionListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.digitaltwins.v2020_10_31.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2020-10-31") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-31")) + cls: ClsType[_models.DigitalTwinsDescriptionListResult] = kwargs.pop("cls", None) - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescriptionListResult"] 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( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata['url'], + template_url=self.list_by_resource_group.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: - - request = build_list_by_resource_group_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - api_version=api_version, - template_url=next_link, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) @@ -553,16 +785,14 @@ async def extract_data(pipeline_response): deserialized = self._deserialize("DigitalTwinsDescriptionListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -573,59 +803,127 @@ 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.DigitalTwins/digitalTwinsInstances"} # type: ignore + list_by_resource_group.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances" + } - @distributed_trace_async + @overload async def check_name_availability( self, location: str, - digital_twins_instance_check_name: "_models.CheckNameRequest", + digital_twins_instance_check_name: _models.CheckNameRequest, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.CheckNameResult": + ) -> _models.CheckNameResult: """Check if a DigitalTwinsInstance name is available. - :param location: Location of DigitalTwinsInstance. + :param location: Location of DigitalTwinsInstance. Required. :type location: str :param digital_twins_instance_check_name: Set the name parameter in the DigitalTwinsInstanceCheckName structure to the name of the DigitalTwinsInstance to check. + Required. :type digital_twins_instance_check_name: ~azure.mgmt.digitaltwins.v2020_10_31.models.CheckNameRequest + :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: CheckNameResult or the result of cls(response) + :rtype: ~azure.mgmt.digitaltwins.v2020_10_31.models.CheckNameResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def check_name_availability( + self, + location: str, + digital_twins_instance_check_name: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.CheckNameResult: + """Check if a DigitalTwinsInstance name is available. + + :param location: Location of DigitalTwinsInstance. Required. + :type location: str + :param digital_twins_instance_check_name: Set the name parameter in the + DigitalTwinsInstanceCheckName structure to the name of the DigitalTwinsInstance to check. + Required. + :type digital_twins_instance_check_name: 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: CheckNameResult, or the result of cls(response) + :return: CheckNameResult or the result of cls(response) :rtype: ~azure.mgmt.digitaltwins.v2020_10_31.models.CheckNameResult - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def check_name_availability( + self, location: str, digital_twins_instance_check_name: Union[_models.CheckNameRequest, IO], **kwargs: Any + ) -> _models.CheckNameResult: + """Check if a DigitalTwinsInstance name is available. + + :param location: Location of DigitalTwinsInstance. Required. + :type location: str + :param digital_twins_instance_check_name: Set the name parameter in the + DigitalTwinsInstanceCheckName structure to the name of the DigitalTwinsInstance to check. Is + either a model type or a IO type. Required. + :type digital_twins_instance_check_name: + ~azure.mgmt.digitaltwins.v2020_10_31.models.CheckNameRequest 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: CheckNameResult or the result of cls(response) + :rtype: ~azure.mgmt.digitaltwins.v2020_10_31.models.CheckNameResult + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.CheckNameResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2020-10-31") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(digital_twins_instance_check_name, 'CheckNameRequest') + api_version: Literal["2020-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.CheckNameResult] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(digital_twins_instance_check_name, (IO, bytes)): + _content = digital_twins_instance_check_name + else: + _json = self._serialize.body(digital_twins_instance_check_name, "CheckNameRequest") request = build_check_name_availability_request( - subscription_id=self._config.subscription_id, location=location, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self.check_name_availability.metadata['url'], + content=_content, + template_url=self.check_name_availability.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -633,12 +931,13 @@ async def check_name_availability( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('CheckNameResult', pipeline_response) + deserialized = self._deserialize("CheckNameResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - check_name_availability.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.DigitalTwins/locations/{location}/checkNameAvailability"} # type: ignore - + check_name_availability.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.DigitalTwins/locations/{location}/checkNameAvailability" + } diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/aio/operations/_operations.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/aio/operations/_operations.py index bedfc5fd80a41..8490f838da9fe 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/aio/operations/_operations.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/aio/operations/_operations.py @@ -6,79 +6,105 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models from ..._vendor import _convert_request from ...operations._operations import build_list_request -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class Operations: - """Operations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class Operations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.digitaltwins.v2020_10_31.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.digitaltwins.v2020_10_31.aio.AzureDigitalTwinsManagementClient`'s + :attr:`operations` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace - def list( - self, - **kwargs: Any - ) -> AsyncIterable["_models.OperationListResult"]: + def list(self, **kwargs: Any) -> AsyncIterable["_models.Operation"]: """Lists all of the available DigitalTwins service REST API operations. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either OperationListResult or the result of cls(response) + :return: An iterator like instance of either Operation or the result of cls(response) :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.digitaltwins.v2020_10_31.models.OperationListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.digitaltwins.v2020_10_31.models.Operation] + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2020-10-31") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-31")) + cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) - cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationListResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( api_version=api_version, - template_url=self.list.metadata['url'], + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: - - request = build_list_request( - api_version=api_version, - template_url=next_link, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) @@ -89,16 +115,14 @@ async def extract_data(pipeline_response): deserialized = self._deserialize("OperationListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -109,8 +133,6 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/providers/Microsoft.DigitalTwins/operations"} # type: ignore + list.metadata = {"url": "/providers/Microsoft.DigitalTwins/operations"} diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/aio/operations/_patch.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/aio/operations/_patch.py new file mode 100644 index 0000000000000..f7dd32510333d --- /dev/null +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/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/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/models/__init__.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/models/__init__.py index f8b09c7653728..d28ef89e96d37 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/models/__init__.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/models/__init__.py @@ -25,35 +25,37 @@ from ._models_py3 import OperationListResult from ._models_py3 import ServiceBus - -from ._azure_digital_twins_management_client_enums import ( - EndpointProvisioningState, - EndpointType, - ProvisioningState, - Reason, -) +from ._azure_digital_twins_management_client_enums import EndpointProvisioningState +from ._azure_digital_twins_management_client_enums import EndpointType +from ._azure_digital_twins_management_client_enums import ProvisioningState +from ._azure_digital_twins_management_client_enums import Reason +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk __all__ = [ - 'CheckNameRequest', - 'CheckNameResult', - 'DigitalTwinsDescription', - 'DigitalTwinsDescriptionListResult', - 'DigitalTwinsEndpointResource', - 'DigitalTwinsEndpointResourceListResult', - 'DigitalTwinsEndpointResourceProperties', - 'DigitalTwinsPatchDescription', - 'DigitalTwinsResource', - 'ErrorDefinition', - 'ErrorResponse', - 'EventGrid', - 'EventHub', - 'ExternalResource', - 'Operation', - 'OperationDisplay', - 'OperationListResult', - 'ServiceBus', - 'EndpointProvisioningState', - 'EndpointType', - 'ProvisioningState', - 'Reason', + "CheckNameRequest", + "CheckNameResult", + "DigitalTwinsDescription", + "DigitalTwinsDescriptionListResult", + "DigitalTwinsEndpointResource", + "DigitalTwinsEndpointResourceListResult", + "DigitalTwinsEndpointResourceProperties", + "DigitalTwinsPatchDescription", + "DigitalTwinsResource", + "ErrorDefinition", + "ErrorResponse", + "EventGrid", + "EventHub", + "ExternalResource", + "Operation", + "OperationDisplay", + "OperationListResult", + "ServiceBus", + "EndpointProvisioningState", + "EndpointType", + "ProvisioningState", + "Reason", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/models/_azure_digital_twins_management_client_enums.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/models/_azure_digital_twins_management_client_enums.py index cd0a70c13befa..8bbd0c120fe43 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/models/_azure_digital_twins_management_client_enums.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/models/_azure_digital_twins_management_client_enums.py @@ -7,13 +7,11 @@ # -------------------------------------------------------------------------- from enum import Enum -from six import with_metaclass from azure.core import CaseInsensitiveEnumMeta -class EndpointProvisioningState(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The provisioning state. - """ +class EndpointProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The provisioning state.""" PROVISIONING = "Provisioning" DELETING = "Deleting" @@ -27,17 +25,17 @@ class EndpointProvisioningState(with_metaclass(CaseInsensitiveEnumMeta, str, Enu MOVING = "Moving" DISABLED = "Disabled" -class EndpointType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The type of Digital Twins endpoint - """ + +class EndpointType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of Digital Twins endpoint.""" EVENT_HUB = "EventHub" EVENT_GRID = "EventGrid" SERVICE_BUS = "ServiceBus" -class ProvisioningState(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The provisioning state. - """ + +class ProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The provisioning state.""" PROVISIONING = "Provisioning" DELETING = "Deleting" @@ -50,9 +48,9 @@ class ProvisioningState(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): RESTORING = "Restoring" MOVING = "Moving" -class Reason(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """Message providing the reason why the given name is invalid. - """ + +class Reason(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Message providing the reason why the given name is invalid.""" INVALID = "Invalid" ALREADY_EXISTS = "AlreadyExists" diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/models/_models_py3.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/models/_models_py3.py index 89d32bed9c885..f60b9ab60385d 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/models/_models_py3.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/models/_models_py3.py @@ -1,4 +1,5 @@ # coding=utf-8 +# pylint: disable=too-many-lines # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. @@ -6,55 +7,51 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Dict, List, Optional, Union +from typing import Dict, List, Optional, TYPE_CHECKING, Union -from azure.core.exceptions import HttpResponseError -import msrest.serialization +from ... import _serialization -from ._azure_digital_twins_management_client_enums import * +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from .. import models as _models -class CheckNameRequest(msrest.serialization.Model): +class CheckNameRequest(_serialization.Model): """The result returned from a database check name availability request. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. - :ivar name: Required. Resource name. + :ivar name: Resource name. Required. :vartype name: str :ivar type: The type of resource, for instance Microsoft.DigitalTwins/digitalTwinsInstances. - Has constant value: "Microsoft.DigitalTwins/digitalTwinsInstances". + Required. Default value is "Microsoft.DigitalTwins/digitalTwinsInstances". :vartype type: str """ _validation = { - 'name': {'required': True}, - 'type': {'required': True, 'constant': True}, + "name": {"required": True}, + "type": {"required": True, "constant": True}, } _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, } type = "Microsoft.DigitalTwins/digitalTwinsInstances" - def __init__( - self, - *, - name: str, - **kwargs - ): + def __init__(self, *, name: str, **kwargs): """ - :keyword name: Required. Resource name. + :keyword name: Resource name. Required. :paramtype name: str """ - super(CheckNameRequest, self).__init__(**kwargs) + super().__init__(**kwargs) self.name = name -class CheckNameResult(msrest.serialization.Model): +class CheckNameResult(_serialization.Model): """The result returned from a check name availability request. :ivar name_available: Specifies a Boolean value that indicates if the name is available. @@ -62,15 +59,15 @@ class CheckNameResult(msrest.serialization.Model): :ivar message: Message indicating an unavailable name due to a conflict, or a description of the naming rules that are violated. :vartype message: str - :ivar reason: Message providing the reason why the given name is invalid. Possible values - include: "Invalid", "AlreadyExists". + :ivar reason: Message providing the reason why the given name is invalid. Known values are: + "Invalid" and "AlreadyExists". :vartype reason: str or ~azure.mgmt.digitaltwins.v2020_10_31.models.Reason """ _attribute_map = { - 'name_available': {'key': 'nameAvailable', 'type': 'bool'}, - 'message': {'key': 'message', 'type': 'str'}, - 'reason': {'key': 'reason', 'type': 'str'}, + "name_available": {"key": "nameAvailable", "type": "bool"}, + "message": {"key": "message", "type": "str"}, + "reason": {"key": "reason", "type": "str"}, } def __init__( @@ -78,7 +75,7 @@ def __init__( *, name_available: Optional[bool] = None, message: Optional[str] = None, - reason: Optional[Union[str, "Reason"]] = None, + reason: Optional[Union[str, "_models.Reason"]] = None, **kwargs ): """ @@ -87,17 +84,17 @@ def __init__( :keyword message: Message indicating an unavailable name due to a conflict, or a description of the naming rules that are violated. :paramtype message: str - :keyword reason: Message providing the reason why the given name is invalid. Possible values - include: "Invalid", "AlreadyExists". + :keyword reason: Message providing the reason why the given name is invalid. Known values are: + "Invalid" and "AlreadyExists". :paramtype reason: str or ~azure.mgmt.digitaltwins.v2020_10_31.models.Reason """ - super(CheckNameResult, self).__init__(**kwargs) + super().__init__(**kwargs) self.name_available = name_available self.message = message self.reason = reason -class DigitalTwinsResource(msrest.serialization.Model): +class DigitalTwinsResource(_serialization.Model): """The common properties of a DigitalTwinsInstance. Variables are only populated by the server, and will be ignored when sending a request. @@ -110,41 +107,35 @@ class DigitalTwinsResource(msrest.serialization.Model): :vartype name: str :ivar type: The resource type. :vartype type: str - :ivar location: Required. The resource location. + :ivar location: The resource location. Required. :vartype location: str - :ivar tags: A set of tags. The resource tags. + :ivar tags: The resource tags. :vartype tags: dict[str, str] """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True, 'pattern': r'^(?!-)[A-Za-z0-9-]{3,63}(?= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False + def build_list_request( - subscription_id: str, - resource_group_name: str, - resource_name: str, - **kwargs: Any + resource_group_name: str, resource_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = kwargs.pop('api_version', "2020-10-31") # type: str + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-31")) + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints", + ) # 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', max_length=64, min_length=1), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=63, min_length=3, pattern=r'^(?!-)[A-Za-z0-9-]{3,63}(? HttpRequest: - api_version = kwargs.pop('api_version', "2020-10-31") # type: str + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-31")) + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}", + ) # 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', max_length=64, min_length=1), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=63, min_length=3, pattern=r'^(?!-)[A-Za-z0-9-]{3,63}(? HttpRequest: - api_version = kwargs.pop('api_version', "2020-10-31") # type: str - content_type = kwargs.pop('content_type', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}", + ) # 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', max_length=64, min_length=1), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=63, min_length=3, pattern=r'^(?!-)[A-Za-z0-9-]{3,63}(? HttpRequest: - api_version = kwargs.pop('api_version', "2020-10-31") # type: str + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-31")) + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}", + ) # 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', max_length=64, min_length=1), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=63, min_length=3, pattern=r'^(?!-)[A-Za-z0-9-]{3,63}(? Iterable["_models.DigitalTwinsEndpointResourceListResult"]: + self, resource_group_name: str, resource_name: str, **kwargs: Any + ) -> Iterable["_models.DigitalTwinsEndpointResource"]: """Get DigitalTwinsInstance Endpoints. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either DigitalTwinsEndpointResourceListResult or the - result of cls(response) + :return: An iterator like instance of either DigitalTwinsEndpointResource or the result of + cls(response) :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.digitaltwins.v2020_10_31.models.DigitalTwinsEndpointResourceListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.paging.ItemPaged[~azure.mgmt.digitaltwins.v2020_10_31.models.DigitalTwinsEndpointResource] + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2020-10-31") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-31")) + cls: ClsType[_models.DigitalTwinsEndpointResourceListResult] = kwargs.pop("cls", None) - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsEndpointResourceListResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list.metadata['url'], + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: - - request = build_list_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - resource_name=resource_name, - api_version=api_version, - template_url=next_link, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) @@ -267,16 +318,14 @@ def extract_data(pipeline_response): deserialized = self._deserialize("DigitalTwinsEndpointResourceListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -287,59 +336,61 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints"} # type: ignore + list.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints" + } @distributed_trace def get( - self, - resource_group_name: str, - resource_name: str, - endpoint_name: str, - **kwargs: Any - ) -> "_models.DigitalTwinsEndpointResource": + self, resource_group_name: str, resource_name: str, endpoint_name: str, **kwargs: Any + ) -> _models.DigitalTwinsEndpointResource: """Get DigitalTwinsInstances Endpoint. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param endpoint_name: Name of Endpoint Resource. + :param endpoint_name: Name of Endpoint Resource. Required. :type endpoint_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: DigitalTwinsEndpointResource, or the result of cls(response) + :return: DigitalTwinsEndpointResource or the result of cls(response) :rtype: ~azure.mgmt.digitaltwins.v2020_10_31.models.DigitalTwinsEndpointResource - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsEndpointResource"] 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', "2020-10-31") # type: str + api_version: Literal["2020-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-31")) + cls: ClsType[_models.DigitalTwinsEndpointResource] = kwargs.pop("cls", None) - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, endpoint_name=endpoint_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -347,72 +398,172 @@ def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('DigitalTwinsEndpointResource', pipeline_response) + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}"} # type: ignore - + get.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}" + } def _create_or_update_initial( self, resource_group_name: str, resource_name: str, endpoint_name: str, - endpoint_description: "_models.DigitalTwinsEndpointResource", + endpoint_description: Union[_models.DigitalTwinsEndpointResource, IO], **kwargs: Any - ) -> "_models.DigitalTwinsEndpointResource": - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsEndpointResource"] + ) -> _models.DigitalTwinsEndpointResource: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2020-10-31") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(endpoint_description, 'DigitalTwinsEndpointResource') + api_version: Literal["2020-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DigitalTwinsEndpointResource] = kwargs.pop("cls", None) - request = build_create_or_update_request_initial( - subscription_id=self._config.subscription_id, + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(endpoint_description, (IO, bytes)): + _content = endpoint_description + else: + _json = self._serialize.body(endpoint_description, "DigitalTwinsEndpointResource") + + request = build_create_or_update_request( resource_group_name=resource_group_name, resource_name=resource_name, 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_initial.metadata['url'], + content=_content, + template_url=self._create_or_update_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('DigitalTwinsEndpointResource', pipeline_response) + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('DigitalTwinsEndpointResource', pipeline_response) + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized + return deserialized # type: ignore + + _create_or_update_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}" + } + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + endpoint_name: str, + endpoint_description: _models.DigitalTwinsEndpointResource, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.DigitalTwinsEndpointResource]: + """Create or update DigitalTwinsInstance endpoint. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param endpoint_name: Name of Endpoint Resource. Required. + :type endpoint_name: str + :param endpoint_description: The DigitalTwinsInstance endpoint metadata and security metadata. + Required. + :type endpoint_description: + ~azure.mgmt.digitaltwins.v2020_10_31.models.DigitalTwinsEndpointResource + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either DigitalTwinsEndpointResource or the + result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2020_10_31.models.DigitalTwinsEndpointResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ - _create_or_update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}"} # type: ignore + @overload + def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + endpoint_name: str, + endpoint_description: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.DigitalTwinsEndpointResource]: + """Create or update DigitalTwinsInstance endpoint. + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param endpoint_name: Name of Endpoint Resource. Required. + :type endpoint_name: str + :param endpoint_description: The DigitalTwinsInstance endpoint metadata and security metadata. + Required. + :type endpoint_description: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either DigitalTwinsEndpointResource or the + result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2020_10_31.models.DigitalTwinsEndpointResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace def begin_create_or_update( @@ -420,21 +571,25 @@ def begin_create_or_update( resource_group_name: str, resource_name: str, endpoint_name: str, - endpoint_description: "_models.DigitalTwinsEndpointResource", + endpoint_description: Union[_models.DigitalTwinsEndpointResource, IO], **kwargs: Any - ) -> LROPoller["_models.DigitalTwinsEndpointResource"]: + ) -> LROPoller[_models.DigitalTwinsEndpointResource]: """Create or update DigitalTwinsInstance endpoint. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param endpoint_name: Name of Endpoint Resource. + :param endpoint_name: Name of Endpoint Resource. Required. :type endpoint_name: str :param endpoint_description: The DigitalTwinsInstance endpoint metadata and security metadata. + Is either a model type or a IO type. Required. :type endpoint_description: - ~azure.mgmt.digitaltwins.v2020_10_31.models.DigitalTwinsEndpointResource + ~azure.mgmt.digitaltwins.v2020_10_31.models.DigitalTwinsEndpointResource or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this @@ -447,17 +602,17 @@ def begin_create_or_update( result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2020_10_31.models.DigitalTwinsEndpointResource] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2020-10-31") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsEndpointResource"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DigitalTwinsEndpointResource] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = self._create_or_update_initial( resource_group_name=resource_group_name, @@ -466,102 +621,107 @@ def begin_create_or_update( endpoint_description=endpoint_description, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('DigitalTwinsEndpointResource', pipeline_response) + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - begin_create_or_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}"} # type: ignore + begin_create_or_update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}" + } def _delete_initial( - self, - resource_group_name: str, - resource_name: str, - endpoint_name: str, - **kwargs: Any - ) -> Optional["_models.DigitalTwinsEndpointResource"]: - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.DigitalTwinsEndpointResource"]] + self, resource_group_name: str, resource_name: str, endpoint_name: str, **kwargs: Any + ) -> Optional[_models.DigitalTwinsEndpointResource]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2020-10-31") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - request = build_delete_request_initial( - subscription_id=self._config.subscription_id, + api_version: Literal["2020-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-31")) + cls: ClsType[Optional[_models.DigitalTwinsEndpointResource]] = kwargs.pop("cls", None) + + request = build_delete_request( resource_group_name=resource_group_name, resource_name=resource_name, endpoint_name=endpoint_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._delete_initial.metadata['url'], + template_url=self._delete_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('DigitalTwinsEndpointResource', pipeline_response) + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) if response.status_code == 202: - deserialized = self._deserialize('DigitalTwinsEndpointResource', pipeline_response) + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _delete_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}"} # type: ignore - + _delete_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}" + } @distributed_trace def begin_delete( - self, - resource_group_name: str, - resource_name: str, - endpoint_name: str, - **kwargs: Any - ) -> LROPoller["_models.DigitalTwinsEndpointResource"]: + self, resource_group_name: str, resource_name: str, endpoint_name: str, **kwargs: Any + ) -> LROPoller[_models.DigitalTwinsEndpointResource]: """Delete a DigitalTwinsInstance endpoint. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param endpoint_name: Name of Endpoint Resource. + :param endpoint_name: Name of Endpoint Resource. Required. :type endpoint_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. @@ -575,45 +735,50 @@ def begin_delete( result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2020_10_31.models.DigitalTwinsEndpointResource] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2020-10-31") # type: str - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsEndpointResource"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-31")) + cls: ClsType[_models.DigitalTwinsEndpointResource] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = self._delete_initial( resource_group_name=resource_group_name, resource_name=resource_name, endpoint_name=endpoint_name, api_version=api_version, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('DigitalTwinsEndpointResource', pipeline_response) + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - begin_delete.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}"} # type: ignore + begin_delete.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}" + } diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/operations/_digital_twins_operations.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/operations/_digital_twins_operations.py index 7c098af0983ca..9487dcafebebe 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/operations/_digital_twins_operations.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/operations/_digital_twins_operations.py @@ -6,361 +6,357 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Iterable, Optional, TypeVar, Union - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import sys +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models +from ..._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') -JSONType = Any + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_get_request( - subscription_id: str, - resource_group_name: str, - resource_name: str, - **kwargs: Any -) -> HttpRequest: - api_version = kwargs.pop('api_version', "2020-10-31") # type: str - accept = "application/json" +def build_get_request(resource_group_name: str, resource_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-31")) + accept = _headers.pop("Accept", "application/json") + # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}", + ) # 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', max_length=64, min_length=1), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=63, min_length=3, pattern=r'^(?!-)[A-Za-z0-9-]{3,63}(? HttpRequest: - api_version = kwargs.pop('api_version', "2020-10-31") # type: str - content_type = kwargs.pop('content_type', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}", + ) # 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', max_length=64, min_length=1), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=63, min_length=3, pattern=r'^(?!-)[A-Za-z0-9-]{3,63}(? HttpRequest: - api_version = kwargs.pop('api_version', "2020-10-31") # type: str - content_type = kwargs.pop('content_type', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}", + ) # 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', max_length=64, min_length=1), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=63, min_length=3, pattern=r'^(?!-)[A-Za-z0-9-]{3,63}(? HttpRequest: - api_version = kwargs.pop('api_version', "2020-10-31") # type: str + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-31")) + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}", + ) # 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', max_length=64, min_length=1), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=63, min_length=3, pattern=r'^(?!-)[A-Za-z0-9-]{3,63}(? HttpRequest: - api_version = kwargs.pop('api_version', "2020-10-31") # type: str +def build_list_request(subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-31")) + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.DigitalTwins/digitalTwinsInstances") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.DigitalTwins/digitalTwinsInstances" + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters - _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - _query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - _header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="GET", - url=_url, - params=_query_parameters, - headers=_header_parameters, - **kwargs - ) - - -def build_list_by_resource_group_request( - subscription_id: str, - resource_group_name: str, - **kwargs: Any -) -> HttpRequest: - api_version = kwargs.pop('api_version', "2020-10-31") # type: str + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_by_resource_group_request(resource_group_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-31")) + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances", + ) # 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', max_length=64, min_length=1), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=64, min_length=1 + ), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # 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_check_name_availability_request( - subscription_id: str, - location: str, - *, - json: JSONType = None, - content: Any = None, - **kwargs: Any -) -> HttpRequest: - api_version = kwargs.pop('api_version', "2020-10-31") # type: str - content_type = kwargs.pop('content_type', None) # type: Optional[str] + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_check_name_availability_request(location: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.DigitalTwins/locations/{location}/checkNameAvailability") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.DigitalTwins/locations/{location}/checkNameAvailability", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), - "location": _SERIALIZER.url("location", location, 'str', min_length=3), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "location": _SERIALIZER.url("location", location, "str", min_length=3), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters - _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - _query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] if content_type is not None: - _header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') - _header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="POST", - url=_url, - params=_query_parameters, - headers=_header_parameters, - json=json, - content=content, - **kwargs - ) - -class DigitalTwinsOperations(object): - """DigitalTwinsOperations 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.digitaltwins.v2020_10_31.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class DigitalTwinsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.digitaltwins.v2020_10_31.AzureDigitalTwinsManagementClient`'s + :attr:`digital_twins` 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, - resource_group_name: str, - resource_name: str, - **kwargs: Any - ) -> "_models.DigitalTwinsDescription": + def get(self, resource_group_name: str, resource_name: str, **kwargs: Any) -> _models.DigitalTwinsDescription: """Get DigitalTwinsInstances resource. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: DigitalTwinsDescription, or the result of cls(response) + :return: DigitalTwinsDescription or the result of cls(response) :rtype: ~azure.mgmt.digitaltwins.v2020_10_31.models.DigitalTwinsDescription - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescription"] 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', "2020-10-31") # type: str + api_version: Literal["2020-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-31")) + cls: ClsType[_models.DigitalTwinsDescription] = kwargs.pop("cls", None) - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -368,90 +364,190 @@ def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}"} # type: ignore - + get.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } def _create_or_update_initial( self, resource_group_name: str, resource_name: str, - digital_twins_create: "_models.DigitalTwinsDescription", + digital_twins_create: Union[_models.DigitalTwinsDescription, IO], **kwargs: Any - ) -> "_models.DigitalTwinsDescription": - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescription"] + ) -> _models.DigitalTwinsDescription: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2020-10-31") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(digital_twins_create, 'DigitalTwinsDescription') + api_version: Literal["2020-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DigitalTwinsDescription] = kwargs.pop("cls", None) - request = build_create_or_update_request_initial( - subscription_id=self._config.subscription_id, + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(digital_twins_create, (IO, bytes)): + _content = digital_twins_create + else: + _json = self._serialize.body(digital_twins_create, "DigitalTwinsDescription") + + request = build_create_or_update_request( resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._create_or_update_initial.metadata['url'], + content=_content, + template_url=self._create_or_update_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized + return deserialized # type: ignore + + _create_or_update_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + digital_twins_create: _models.DigitalTwinsDescription, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.DigitalTwinsDescription]: + """Create or update the metadata of a DigitalTwinsInstance. The usual pattern to modify a property + is to retrieve the DigitalTwinsInstance and security metadata, and then combine them with the + modified values in a new body to update the DigitalTwinsInstance. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param digital_twins_create: The DigitalTwinsInstance and security metadata. Required. + :type digital_twins_create: ~azure.mgmt.digitaltwins.v2020_10_31.models.DigitalTwinsDescription + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either DigitalTwinsDescription or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2020_10_31.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: + """ - _create_or_update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}"} # type: ignore + @overload + def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + digital_twins_create: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.DigitalTwinsDescription]: + """Create or update the metadata of a DigitalTwinsInstance. The usual pattern to modify a property + is to retrieve the DigitalTwinsInstance and security metadata, and then combine them with the + modified values in a new body to update the DigitalTwinsInstance. + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param digital_twins_create: The DigitalTwinsInstance and security metadata. Required. + :type digital_twins_create: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either DigitalTwinsDescription or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2020_10_31.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace def begin_create_or_update( self, resource_group_name: str, resource_name: str, - digital_twins_create: "_models.DigitalTwinsDescription", + digital_twins_create: Union[_models.DigitalTwinsDescription, IO], **kwargs: Any - ) -> LROPoller["_models.DigitalTwinsDescription"]: + ) -> LROPoller[_models.DigitalTwinsDescription]: """Create or update the metadata of a DigitalTwinsInstance. The usual pattern to modify a property is to retrieve the DigitalTwinsInstance and security metadata, and then combine them with the modified values in a new body to update the DigitalTwinsInstance. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param digital_twins_create: The DigitalTwinsInstance and security metadata. + :param digital_twins_create: The DigitalTwinsInstance and security metadata. Is either a model + type or a IO type. Required. :type digital_twins_create: ~azure.mgmt.digitaltwins.v2020_10_31.models.DigitalTwinsDescription + or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this @@ -464,17 +560,17 @@ def begin_create_or_update( cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2020_10_31.models.DigitalTwinsDescription] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2020-10-31") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescription"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DigitalTwinsDescription] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = self._create_or_update_initial( resource_group_name=resource_group_name, @@ -482,84 +578,166 @@ def begin_create_or_update( digital_twins_create=digital_twins_create, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - begin_create_or_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}"} # type: ignore + begin_create_or_update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } - @distributed_trace + @overload def update( self, resource_group_name: str, resource_name: str, - digital_twins_patch_description: "_models.DigitalTwinsPatchDescription", + digital_twins_patch_description: _models.DigitalTwinsPatchDescription, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.DigitalTwinsDescription": + ) -> _models.DigitalTwinsDescription: """Update metadata of DigitalTwinsInstance. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str :param digital_twins_patch_description: The DigitalTwinsInstance and security metadata. + Required. :type digital_twins_patch_description: ~azure.mgmt.digitaltwins.v2020_10_31.models.DigitalTwinsPatchDescription + :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: DigitalTwinsDescription, or the result of cls(response) + :return: DigitalTwinsDescription or the result of cls(response) :rtype: ~azure.mgmt.digitaltwins.v2020_10_31.models.DigitalTwinsDescription - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def update( + self, + resource_group_name: str, + resource_name: str, + digital_twins_patch_description: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.DigitalTwinsDescription: + """Update metadata of DigitalTwinsInstance. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param digital_twins_patch_description: The DigitalTwinsInstance and security metadata. + Required. + :type digital_twins_patch_description: 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: DigitalTwinsDescription or the result of cls(response) + :rtype: ~azure.mgmt.digitaltwins.v2020_10_31.models.DigitalTwinsDescription + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def update( + self, + resource_group_name: str, + resource_name: str, + digital_twins_patch_description: Union[_models.DigitalTwinsPatchDescription, IO], + **kwargs: Any + ) -> _models.DigitalTwinsDescription: + """Update metadata of DigitalTwinsInstance. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param digital_twins_patch_description: The DigitalTwinsInstance and security metadata. Is + either a model type or a IO type. Required. + :type digital_twins_patch_description: + ~azure.mgmt.digitaltwins.v2020_10_31.models.DigitalTwinsPatchDescription 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: DigitalTwinsDescription or the result of cls(response) + :rtype: ~azure.mgmt.digitaltwins.v2020_10_31.models.DigitalTwinsDescription + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescription"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', "2020-10-31") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + api_version: Literal["2020-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DigitalTwinsDescription] = kwargs.pop("cls", None) - _json = self._serialize.body(digital_twins_patch_description, 'DigitalTwinsPatchDescription') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(digital_twins_patch_description, (IO, bytes)): + _content = digital_twins_patch_description + else: + _json = self._serialize.body(digital_twins_patch_description, "DigitalTwinsPatchDescription") request = build_update_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_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) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -567,80 +745,83 @@ def update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}"} # type: ignore - + update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } def _delete_initial( - self, - resource_group_name: str, - resource_name: str, - **kwargs: Any - ) -> Optional["_models.DigitalTwinsDescription"]: - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.DigitalTwinsDescription"]] + self, resource_group_name: str, resource_name: str, **kwargs: Any + ) -> Optional[_models.DigitalTwinsDescription]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2020-10-31") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - request = build_delete_request_initial( - subscription_id=self._config.subscription_id, + api_version: Literal["2020-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-31")) + cls: ClsType[Optional[_models.DigitalTwinsDescription]] = kwargs.pop("cls", None) + + request = build_delete_request( resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._delete_initial.metadata['url'], + template_url=self._delete_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if response.status_code == 202: - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _delete_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}"} # type: ignore - + _delete_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } @distributed_trace def begin_delete( - self, - resource_group_name: str, - resource_name: str, - **kwargs: Any - ) -> LROPoller["_models.DigitalTwinsDescription"]: + self, resource_group_name: str, resource_name: str, **kwargs: Any + ) -> LROPoller[_models.DigitalTwinsDescription]: """Delete a DigitalTwinsInstance. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. @@ -654,86 +835,103 @@ def begin_delete( cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2020_10_31.models.DigitalTwinsDescription] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2020-10-31") # type: str - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescription"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-31")) + cls: ClsType[_models.DigitalTwinsDescription] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = self._delete_initial( resource_group_name=resource_group_name, resource_name=resource_name, api_version=api_version, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - begin_delete.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}"} # type: ignore + begin_delete.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } @distributed_trace - def list( - self, - **kwargs: Any - ) -> Iterable["_models.DigitalTwinsDescriptionListResult"]: + def list(self, **kwargs: Any) -> Iterable["_models.DigitalTwinsDescription"]: """Get all the DigitalTwinsInstances in a subscription. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either DigitalTwinsDescriptionListResult or the result of + :return: An iterator like instance of either DigitalTwinsDescription or the result of cls(response) :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.digitaltwins.v2020_10_31.models.DigitalTwinsDescriptionListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.paging.ItemPaged[~azure.mgmt.digitaltwins.v2020_10_31.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2020-10-31") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-31")) + cls: ClsType[_models.DigitalTwinsDescriptionListResult] = kwargs.pop("cls", None) - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescriptionListResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list.metadata['url'], + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: - - request = build_list_request( - subscription_id=self._config.subscription_id, - api_version=api_version, - template_url=next_link, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) @@ -744,16 +942,14 @@ def extract_data(pipeline_response): deserialized = self._deserialize("DigitalTwinsDescriptionListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -764,56 +960,66 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.DigitalTwins/digitalTwinsInstances"} # type: ignore + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.DigitalTwins/digitalTwinsInstances"} @distributed_trace def list_by_resource_group( - self, - resource_group_name: str, - **kwargs: Any - ) -> Iterable["_models.DigitalTwinsDescriptionListResult"]: + self, resource_group_name: str, **kwargs: Any + ) -> Iterable["_models.DigitalTwinsDescription"]: """Get all the DigitalTwinsInstances in a resource group. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. 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 DigitalTwinsDescriptionListResult or the result of + :return: An iterator like instance of either DigitalTwinsDescription or the result of cls(response) :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.digitaltwins.v2020_10_31.models.DigitalTwinsDescriptionListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.paging.ItemPaged[~azure.mgmt.digitaltwins.v2020_10_31.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2020-10-31") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-31")) + cls: ClsType[_models.DigitalTwinsDescriptionListResult] = kwargs.pop("cls", None) - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescriptionListResult"] 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( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata['url'], + template_url=self.list_by_resource_group.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: - - request = build_list_by_resource_group_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - api_version=api_version, - template_url=next_link, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) @@ -824,16 +1030,14 @@ def extract_data(pipeline_response): deserialized = self._deserialize("DigitalTwinsDescriptionListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -844,59 +1048,127 @@ 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.DigitalTwins/digitalTwinsInstances"} # type: ignore + list_by_resource_group.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances" + } - @distributed_trace + @overload def check_name_availability( self, location: str, - digital_twins_instance_check_name: "_models.CheckNameRequest", + digital_twins_instance_check_name: _models.CheckNameRequest, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.CheckNameResult": + ) -> _models.CheckNameResult: """Check if a DigitalTwinsInstance name is available. - :param location: Location of DigitalTwinsInstance. + :param location: Location of DigitalTwinsInstance. Required. :type location: str :param digital_twins_instance_check_name: Set the name parameter in the DigitalTwinsInstanceCheckName structure to the name of the DigitalTwinsInstance to check. + Required. :type digital_twins_instance_check_name: ~azure.mgmt.digitaltwins.v2020_10_31.models.CheckNameRequest + :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: CheckNameResult, or the result of cls(response) + :return: CheckNameResult or the result of cls(response) :rtype: ~azure.mgmt.digitaltwins.v2020_10_31.models.CheckNameResult - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def check_name_availability( + self, + location: str, + digital_twins_instance_check_name: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.CheckNameResult: + """Check if a DigitalTwinsInstance name is available. + + :param location: Location of DigitalTwinsInstance. Required. + :type location: str + :param digital_twins_instance_check_name: Set the name parameter in the + DigitalTwinsInstanceCheckName structure to the name of the DigitalTwinsInstance to check. + Required. + :type digital_twins_instance_check_name: 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: CheckNameResult or the result of cls(response) + :rtype: ~azure.mgmt.digitaltwins.v2020_10_31.models.CheckNameResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def check_name_availability( + self, location: str, digital_twins_instance_check_name: Union[_models.CheckNameRequest, IO], **kwargs: Any + ) -> _models.CheckNameResult: + """Check if a DigitalTwinsInstance name is available. + + :param location: Location of DigitalTwinsInstance. Required. + :type location: str + :param digital_twins_instance_check_name: Set the name parameter in the + DigitalTwinsInstanceCheckName structure to the name of the DigitalTwinsInstance to check. Is + either a model type or a IO type. Required. + :type digital_twins_instance_check_name: + ~azure.mgmt.digitaltwins.v2020_10_31.models.CheckNameRequest 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: CheckNameResult or the result of cls(response) + :rtype: ~azure.mgmt.digitaltwins.v2020_10_31.models.CheckNameResult + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.CheckNameResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2020-10-31") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(digital_twins_instance_check_name, 'CheckNameRequest') + api_version: Literal["2020-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.CheckNameResult] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(digital_twins_instance_check_name, (IO, bytes)): + _content = digital_twins_instance_check_name + else: + _json = self._serialize.body(digital_twins_instance_check_name, "CheckNameRequest") request = build_check_name_availability_request( - subscription_id=self._config.subscription_id, location=location, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self.check_name_availability.metadata['url'], + content=_content, + template_url=self.check_name_availability.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -904,12 +1176,13 @@ def check_name_availability( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('CheckNameResult', pipeline_response) + deserialized = self._deserialize("CheckNameResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - check_name_availability.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.DigitalTwins/locations/{location}/checkNameAvailability"} # type: ignore - + check_name_availability.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.DigitalTwins/locations/{location}/checkNameAvailability" + } diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/operations/_operations.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/operations/_operations.py index 832b6f5995e2c..c641c539e986e 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/operations/_operations.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/operations/_operations.py @@ -6,108 +6,126 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, Callable, Dict, Iterable, Optional, TypeVar - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from ..._serialization import Serializer from .._vendor import _convert_request -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_list_request( - **kwargs: Any -) -> HttpRequest: - api_version = kwargs.pop('api_version', "2020-10-31") # type: str - accept = "application/json" +def build_list_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-31")) + accept = _headers.pop("Accept", "application/json") + # Construct URL _url = kwargs.pop("template_url", "/providers/Microsoft.DigitalTwins/operations") # Construct parameters - _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - _query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - _header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="GET", - url=_url, - params=_query_parameters, - headers=_header_parameters, - **kwargs - ) - -class Operations(object): - """Operations operations. - - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. - - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.digitaltwins.v2020_10_31.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class Operations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.digitaltwins.v2020_10_31.AzureDigitalTwinsManagementClient`'s + :attr:`operations` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace - def list( - self, - **kwargs: Any - ) -> Iterable["_models.OperationListResult"]: + def list(self, **kwargs: Any) -> Iterable["_models.Operation"]: """Lists all of the available DigitalTwins service REST API operations. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either OperationListResult or the result of cls(response) - :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.digitaltwins.v2020_10_31.models.OperationListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Operation or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.digitaltwins.v2020_10_31.models.Operation] + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2020-10-31") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2020-10-31")) + cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) - cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationListResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( api_version=api_version, - template_url=self.list.metadata['url'], + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: - - request = build_list_request( - api_version=api_version, - template_url=next_link, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) @@ -118,16 +136,14 @@ def extract_data(pipeline_response): deserialized = self._deserialize("OperationListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -138,8 +154,6 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/providers/Microsoft.DigitalTwins/operations"} # type: ignore + list.metadata = {"url": "/providers/Microsoft.DigitalTwins/operations"} diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/operations/_patch.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/operations/_patch.py new file mode 100644 index 0000000000000..f7dd32510333d --- /dev/null +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_10_31/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/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/__init__.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/__init__.py index 36b558a96cdfd..3d416a868dd25 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/__init__.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/__init__.py @@ -10,9 +10,17 @@ from ._version import VERSION __version__ = VERSION -__all__ = ['AzureDigitalTwinsManagementClient'] -# `._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 * # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "AzureDigitalTwinsManagementClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/_azure_digital_twins_management_client.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/_azure_digital_twins_management_client.py index 4907a867db484..35c3888efbcb8 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/_azure_digital_twins_management_client.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/_azure_digital_twins_management_client.py @@ -9,20 +9,26 @@ from copy import deepcopy from typing import Any, TYPE_CHECKING -from msrest import Deserializer, Serializer - from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient -from . import models +from . import models as _models +from .._serialization import Deserializer, Serializer from ._configuration import AzureDigitalTwinsManagementClientConfiguration -from .operations import DigitalTwinsEndpointOperations, DigitalTwinsOperations, Operations, PrivateEndpointConnectionsOperations, PrivateLinkResourcesOperations +from .operations import ( + DigitalTwinsEndpointOperations, + DigitalTwinsOperations, + Operations, + PrivateEndpointConnectionsOperations, + PrivateLinkResourcesOperations, +) if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class AzureDigitalTwinsManagementClient: + +class AzureDigitalTwinsManagementClient: # pylint: disable=client-accepts-api-version-keyword """Azure Digital Twins Client for managing DigitalTwinsInstance. :ivar digital_twins: DigitalTwinsOperations operations @@ -38,9 +44,9 @@ class AzureDigitalTwinsManagementClient: :ivar private_endpoint_connections: PrivateEndpointConnectionsOperations operations :vartype private_endpoint_connections: azure.mgmt.digitaltwins.v2020_12_01.operations.PrivateEndpointConnectionsOperations - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: The subscription identifier. + :param subscription_id: The subscription identifier. Required. :type subscription_id: str :param base_url: Service URL. Default value is "https://management.azure.com". :type base_url: str @@ -58,25 +64,28 @@ def __init__( base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: - self._config = AzureDigitalTwinsManagementClientConfiguration(credential=credential, subscription_id=subscription_id, **kwargs) + self._config = AzureDigitalTwinsManagementClientConfiguration( + credential=credential, subscription_id=subscription_id, **kwargs + ) self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) - client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) self._deserialize = Deserializer(client_models) self._serialize.client_side_validation = False self.digital_twins = DigitalTwinsOperations(self._client, self._config, self._serialize, self._deserialize) - self.digital_twins_endpoint = DigitalTwinsEndpointOperations(self._client, self._config, self._serialize, self._deserialize) + self.digital_twins_endpoint = DigitalTwinsEndpointOperations( + self._client, self._config, self._serialize, self._deserialize + ) self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) - self.private_link_resources = PrivateLinkResourcesOperations(self._client, self._config, self._serialize, self._deserialize) - self.private_endpoint_connections = PrivateEndpointConnectionsOperations(self._client, self._config, self._serialize, self._deserialize) - - - def _send_request( - self, - request: HttpRequest, - **kwargs: Any - ) -> HttpResponse: + self.private_link_resources = PrivateLinkResourcesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.private_endpoint_connections = PrivateEndpointConnectionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + + def _send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: """Runs the network request through the client's chained policies. >>> from azure.core.rest import HttpRequest @@ -85,7 +94,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 @@ -98,15 +107,12 @@ def _send_request( request_copy.url = self._client.format_url(request_copy.url) return self._client.send_request(request_copy, **kwargs) - def close(self): - # type: () -> None + def close(self) -> None: self._client.close() - def __enter__(self): - # type: () -> AzureDigitalTwinsManagementClient + def __enter__(self) -> "AzureDigitalTwinsManagementClient": self._client.__enter__() return self - def __exit__(self, *exc_details): - # type: (Any) -> None + def __exit__(self, *exc_details) -> None: self._client.__exit__(*exc_details) diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/_configuration.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/_configuration.py index 023b224c5ec0e..ddd3c75aad420 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/_configuration.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/_configuration.py @@ -6,6 +6,7 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, TYPE_CHECKING from azure.core.configuration import Configuration @@ -14,6 +15,11 @@ from ._version import VERSION +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports + if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential @@ -25,23 +31,18 @@ class AzureDigitalTwinsManagementClientConfiguration(Configuration): # pylint: Note that all parameters used to create this instance are saved as instance attributes. - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: The subscription identifier. + :param subscription_id: The subscription identifier. Required. :type subscription_id: str :keyword api_version: Api Version. Default value is "2020-12-01". Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str """ - def __init__( - self, - credential: "TokenCredential", - subscription_id: str, - **kwargs: Any - ) -> None: + def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: super(AzureDigitalTwinsManagementClientConfiguration, self).__init__(**kwargs) - api_version = kwargs.pop('api_version', "2020-12-01") # type: str + api_version: Literal["2020-12-01"] = kwargs.pop("api_version", "2020-12-01") if credential is None: raise ValueError("Parameter 'credential' must not be None.") @@ -51,23 +52,21 @@ def __init__( self.credential = credential self.subscription_id = subscription_id self.api_version = api_version - self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'mgmt-digitaltwins/{}'.format(VERSION)) + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-digitaltwins/{}".format(VERSION)) self._configure(**kwargs) - def _configure( - self, - **kwargs # type: Any - ): - # type: (...) -> None - self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get('retry_policy') or policies.RetryPolicy(**kwargs) - self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get('redirect_policy') or policies.RedirectPolicy(**kwargs) - self.authentication_policy = kwargs.get('authentication_policy') + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: - self.authentication_policy = ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs) + self.authentication_policy = ARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/_metadata.json b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/_metadata.json index 62203ac8c1290..f132fd93270d9 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/_metadata.json +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/_metadata.json @@ -10,20 +10,20 @@ "azure_arm": true, "has_lro_operations": true, "client_side_validation": false, - "sync_imports": "{\"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}, \"regular\": {\"azurecore\": {\"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"], \"azure.mgmt.core\": [\"ARMPipelineClient\"]}, \"local\": {\"._configuration\": [\"AzureDigitalTwinsManagementClientConfiguration\"]}, \"thirdparty\": {\"msrest\": [\"Deserializer\", \"Serializer\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}}", - "async_imports": "{\"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"], \"azure.core.credentials\": [\"TokenCredential\"]}}, \"regular\": {\"azurecore\": {\"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"], \"azure.mgmt.core\": [\"AsyncARMPipelineClient\"]}, \"local\": {\"._configuration\": [\"AzureDigitalTwinsManagementClientConfiguration\"]}, \"thirdparty\": {\"msrest\": [\"Deserializer\", \"Serializer\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}}" + "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"AzureDigitalTwinsManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"AzureDigitalTwinsManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "global_parameters": { "sync": { "credential": { - "signature": "credential, # type: \"TokenCredential\"", - "description": "Credential needed for the client to connect to Azure.", + "signature": "credential: \"TokenCredential\",", + "description": "Credential needed for the client to connect to Azure. Required.", "docstring_type": "~azure.core.credentials.TokenCredential", "required": true }, "subscription_id": { - "signature": "subscription_id, # type: str", - "description": "The subscription identifier.", + "signature": "subscription_id: str,", + "description": "The subscription identifier. Required.", "docstring_type": "str", "required": true } @@ -31,13 +31,13 @@ "async": { "credential": { "signature": "credential: \"AsyncTokenCredential\",", - "description": "Credential needed for the client to connect to Azure.", + "description": "Credential needed for the client to connect to Azure. Required.", "docstring_type": "~azure.core.credentials_async.AsyncTokenCredential", "required": true }, "subscription_id": { "signature": "subscription_id: str,", - "description": "The subscription identifier.", + "description": "The subscription identifier. Required.", "docstring_type": "str", "required": true } @@ -48,19 +48,19 @@ "service_client_specific": { "sync": { "api_version": { - "signature": "api_version=None, # type: Optional[str]", + "signature": "api_version: Optional[str]=None,", "description": "API version to use if no profile is provided, or if missing in profile.", "docstring_type": "str", "required": false }, "base_url": { - "signature": "base_url=\"https://management.azure.com\", # type: str", + "signature": "base_url: str = \"https://management.azure.com\",", "description": "Service URL", "docstring_type": "str", "required": false }, "profile": { - "signature": "profile=KnownProfiles.default, # type: KnownProfiles", + "signature": "profile: KnownProfiles=KnownProfiles.default,", "description": "A profile definition, from KnownProfiles to dict.", "docstring_type": "azure.profiles.KnownProfiles", "required": false @@ -103,4 +103,4 @@ "private_link_resources": "PrivateLinkResourcesOperations", "private_endpoint_connections": "PrivateEndpointConnectionsOperations" } -} \ No newline at end of file +} diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/_patch.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/_patch.py index 74e48ecd07cf3..f99e77fef9861 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/_patch.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/_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/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/_vendor.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/_vendor.py index 138f663c53a4e..9aad73fc743e7 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/_vendor.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/_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/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/_version.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/_version.py index a55d01326aa81..e5754a47ce68f 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/_version.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "6.2.0" +VERSION = "1.0.0b1" diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/aio/__init__.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/aio/__init__.py index 20a6435cbbdb2..e4da5a5dc30c1 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/aio/__init__.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/aio/__init__.py @@ -7,9 +7,17 @@ # -------------------------------------------------------------------------- from ._azure_digital_twins_management_client import AzureDigitalTwinsManagementClient -__all__ = ['AzureDigitalTwinsManagementClient'] -# `._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 * # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "AzureDigitalTwinsManagementClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/aio/_azure_digital_twins_management_client.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/aio/_azure_digital_twins_management_client.py index 245345a7a3811..66eb765512f39 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/aio/_azure_digital_twins_management_client.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/aio/_azure_digital_twins_management_client.py @@ -9,20 +9,26 @@ from copy import deepcopy from typing import Any, Awaitable, TYPE_CHECKING -from msrest import Deserializer, Serializer - from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient -from .. import models +from .. import models as _models +from ..._serialization import Deserializer, Serializer from ._configuration import AzureDigitalTwinsManagementClientConfiguration -from .operations import DigitalTwinsEndpointOperations, DigitalTwinsOperations, Operations, PrivateEndpointConnectionsOperations, PrivateLinkResourcesOperations +from .operations import ( + DigitalTwinsEndpointOperations, + DigitalTwinsOperations, + Operations, + PrivateEndpointConnectionsOperations, + PrivateLinkResourcesOperations, +) if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class AzureDigitalTwinsManagementClient: + +class AzureDigitalTwinsManagementClient: # pylint: disable=client-accepts-api-version-keyword """Azure Digital Twins Client for managing DigitalTwinsInstance. :ivar digital_twins: DigitalTwinsOperations operations @@ -39,9 +45,9 @@ class AzureDigitalTwinsManagementClient: :ivar private_endpoint_connections: PrivateEndpointConnectionsOperations operations :vartype private_endpoint_connections: azure.mgmt.digitaltwins.v2020_12_01.aio.operations.PrivateEndpointConnectionsOperations - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: The subscription identifier. + :param subscription_id: The subscription identifier. Required. :type subscription_id: str :param base_url: Service URL. Default value is "https://management.azure.com". :type base_url: str @@ -59,25 +65,28 @@ def __init__( base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: - self._config = AzureDigitalTwinsManagementClientConfiguration(credential=credential, subscription_id=subscription_id, **kwargs) + self._config = AzureDigitalTwinsManagementClientConfiguration( + credential=credential, subscription_id=subscription_id, **kwargs + ) self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) - client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) self._deserialize = Deserializer(client_models) self._serialize.client_side_validation = False self.digital_twins = DigitalTwinsOperations(self._client, self._config, self._serialize, self._deserialize) - self.digital_twins_endpoint = DigitalTwinsEndpointOperations(self._client, self._config, self._serialize, self._deserialize) + self.digital_twins_endpoint = DigitalTwinsEndpointOperations( + self._client, self._config, self._serialize, self._deserialize + ) self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) - self.private_link_resources = PrivateLinkResourcesOperations(self._client, self._config, self._serialize, self._deserialize) - self.private_endpoint_connections = PrivateEndpointConnectionsOperations(self._client, self._config, self._serialize, self._deserialize) - - - def _send_request( - self, - request: HttpRequest, - **kwargs: Any - ) -> Awaitable[AsyncHttpResponse]: + self.private_link_resources = PrivateLinkResourcesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.private_endpoint_connections = PrivateEndpointConnectionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + + def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: """Runs the network request through the client's chained policies. >>> from azure.core.rest import HttpRequest @@ -86,7 +95,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/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/aio/_configuration.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/aio/_configuration.py index 9edebfb37f03b..0c1ea0f0a30fc 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/aio/_configuration.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/aio/_configuration.py @@ -6,6 +6,7 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, TYPE_CHECKING from azure.core.configuration import Configuration @@ -14,6 +15,11 @@ from .._version import VERSION +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports + if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential @@ -25,23 +31,18 @@ class AzureDigitalTwinsManagementClientConfiguration(Configuration): # pylint: Note that all parameters used to create this instance are saved as instance attributes. - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: The subscription identifier. + :param subscription_id: The subscription identifier. Required. :type subscription_id: str :keyword api_version: Api Version. Default value is "2020-12-01". Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str """ - def __init__( - self, - credential: "AsyncTokenCredential", - subscription_id: str, - **kwargs: Any - ) -> None: + def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: super(AzureDigitalTwinsManagementClientConfiguration, self).__init__(**kwargs) - api_version = kwargs.pop('api_version', "2020-12-01") # type: str + api_version: Literal["2020-12-01"] = kwargs.pop("api_version", "2020-12-01") if credential is None: raise ValueError("Parameter 'credential' must not be None.") @@ -51,22 +52,21 @@ def __init__( self.credential = credential self.subscription_id = subscription_id self.api_version = api_version - self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'mgmt-digitaltwins/{}'.format(VERSION)) + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-digitaltwins/{}".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/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/aio/_patch.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/aio/_patch.py index 74e48ecd07cf3..f99e77fef9861 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/aio/_patch.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/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/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/aio/operations/__init__.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/aio/operations/__init__.py index 4d014a642a968..9382705d7dcfb 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/aio/operations/__init__.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/aio/operations/__init__.py @@ -12,10 +12,16 @@ from ._private_link_resources_operations import PrivateLinkResourcesOperations from ._private_endpoint_connections_operations import PrivateEndpointConnectionsOperations +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + __all__ = [ - 'DigitalTwinsOperations', - 'DigitalTwinsEndpointOperations', - 'Operations', - 'PrivateLinkResourcesOperations', - 'PrivateEndpointConnectionsOperations', + "DigitalTwinsOperations", + "DigitalTwinsEndpointOperations", + "Operations", + "PrivateLinkResourcesOperations", + "PrivateEndpointConnectionsOperations", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/aio/operations/_digital_twins_endpoint_operations.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/aio/operations/_digital_twins_endpoint_operations.py index 11b798fb1dca4..9a0d95bf9fe27 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/aio/operations/_digital_twins_endpoint_operations.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/aio/operations/_digital_twins_endpoint_operations.py @@ -6,96 +6,124 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar, Union +import sys +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models from ..._vendor import _convert_request -from ...operations._digital_twins_endpoint_operations import build_create_or_update_request_initial, build_delete_request_initial, build_get_request, build_list_request -T = TypeVar('T') +from ...operations._digital_twins_endpoint_operations import ( + build_create_or_update_request, + build_delete_request, + build_get_request, + build_list_request, +) + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class DigitalTwinsEndpointOperations: - """DigitalTwinsEndpointOperations 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 DigitalTwinsEndpointOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.digitaltwins.v2020_12_01.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.digitaltwins.v2020_12_01.aio.AzureDigitalTwinsManagementClient`'s + :attr:`digital_twins_endpoint` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list( - self, - resource_group_name: str, - resource_name: str, - **kwargs: Any - ) -> AsyncIterable["_models.DigitalTwinsEndpointResourceListResult"]: + self, resource_group_name: str, resource_name: str, **kwargs: Any + ) -> AsyncIterable["_models.DigitalTwinsEndpointResource"]: """Get DigitalTwinsInstance Endpoints. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either DigitalTwinsEndpointResourceListResult or the - result of cls(response) + :return: An iterator like instance of either DigitalTwinsEndpointResource or the result of + cls(response) :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.digitaltwins.v2020_12_01.models.DigitalTwinsEndpointResourceListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.digitaltwins.v2020_12_01.models.DigitalTwinsEndpointResource] + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2020-12-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) + cls: ClsType[_models.DigitalTwinsEndpointResourceListResult] = kwargs.pop("cls", None) - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsEndpointResourceListResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list.metadata['url'], + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: - - request = build_list_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - resource_name=resource_name, - api_version=api_version, - template_url=next_link, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) @@ -106,16 +134,14 @@ async def extract_data(pipeline_response): deserialized = self._deserialize("DigitalTwinsEndpointResourceListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -126,59 +152,61 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints"} # type: ignore + list.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints" + } @distributed_trace_async async def get( - self, - resource_group_name: str, - resource_name: str, - endpoint_name: str, - **kwargs: Any - ) -> "_models.DigitalTwinsEndpointResource": + self, resource_group_name: str, resource_name: str, endpoint_name: str, **kwargs: Any + ) -> _models.DigitalTwinsEndpointResource: """Get DigitalTwinsInstances Endpoint. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param endpoint_name: Name of Endpoint Resource. + :param endpoint_name: Name of Endpoint Resource. Required. :type endpoint_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: DigitalTwinsEndpointResource, or the result of cls(response) + :return: DigitalTwinsEndpointResource or the result of cls(response) :rtype: ~azure.mgmt.digitaltwins.v2020_12_01.models.DigitalTwinsEndpointResource - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsEndpointResource"] 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', "2020-12-01") # type: str + api_version: Literal["2020-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) + cls: ClsType[_models.DigitalTwinsEndpointResource] = kwargs.pop("cls", None) - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, endpoint_name=endpoint_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -186,72 +214,172 @@ async def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('DigitalTwinsEndpointResource', pipeline_response) + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}"} # type: ignore - + get.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}" + } async def _create_or_update_initial( self, resource_group_name: str, resource_name: str, endpoint_name: str, - endpoint_description: "_models.DigitalTwinsEndpointResource", + endpoint_description: Union[_models.DigitalTwinsEndpointResource, IO], **kwargs: Any - ) -> "_models.DigitalTwinsEndpointResource": - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsEndpointResource"] + ) -> _models.DigitalTwinsEndpointResource: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2020-12-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(endpoint_description, 'DigitalTwinsEndpointResource') + api_version: Literal["2020-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DigitalTwinsEndpointResource] = kwargs.pop("cls", None) - request = build_create_or_update_request_initial( - subscription_id=self._config.subscription_id, + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(endpoint_description, (IO, bytes)): + _content = endpoint_description + else: + _json = self._serialize.body(endpoint_description, "DigitalTwinsEndpointResource") + + request = build_create_or_update_request( resource_group_name=resource_group_name, resource_name=resource_name, 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_initial.metadata['url'], + content=_content, + template_url=self._create_or_update_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('DigitalTwinsEndpointResource', pipeline_response) + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('DigitalTwinsEndpointResource', pipeline_response) + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized + return deserialized # type: ignore + + _create_or_update_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}" + } + + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + endpoint_name: str, + endpoint_description: _models.DigitalTwinsEndpointResource, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.DigitalTwinsEndpointResource]: + """Create or update DigitalTwinsInstance endpoint. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param endpoint_name: Name of Endpoint Resource. Required. + :type endpoint_name: str + :param endpoint_description: The DigitalTwinsInstance endpoint metadata and security metadata. + Required. + :type endpoint_description: + ~azure.mgmt.digitaltwins.v2020_12_01.models.DigitalTwinsEndpointResource + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either DigitalTwinsEndpointResource or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2020_12_01.models.DigitalTwinsEndpointResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ - _create_or_update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}"} # type: ignore + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + endpoint_name: str, + endpoint_description: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.DigitalTwinsEndpointResource]: + """Create or update DigitalTwinsInstance endpoint. + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param endpoint_name: Name of Endpoint Resource. Required. + :type endpoint_name: str + :param endpoint_description: The DigitalTwinsInstance endpoint metadata and security metadata. + Required. + :type endpoint_description: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either DigitalTwinsEndpointResource or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2020_12_01.models.DigitalTwinsEndpointResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace_async async def begin_create_or_update( @@ -259,21 +387,25 @@ async def begin_create_or_update( resource_group_name: str, resource_name: str, endpoint_name: str, - endpoint_description: "_models.DigitalTwinsEndpointResource", + endpoint_description: Union[_models.DigitalTwinsEndpointResource, IO], **kwargs: Any - ) -> AsyncLROPoller["_models.DigitalTwinsEndpointResource"]: + ) -> AsyncLROPoller[_models.DigitalTwinsEndpointResource]: """Create or update DigitalTwinsInstance endpoint. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param endpoint_name: Name of Endpoint Resource. + :param endpoint_name: Name of Endpoint Resource. Required. :type endpoint_name: str :param endpoint_description: The DigitalTwinsInstance endpoint metadata and security metadata. + Is either a model type or a IO type. Required. :type endpoint_description: - ~azure.mgmt.digitaltwins.v2020_12_01.models.DigitalTwinsEndpointResource + ~azure.mgmt.digitaltwins.v2020_12_01.models.DigitalTwinsEndpointResource or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for @@ -286,17 +418,17 @@ async def begin_create_or_update( result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2020_12_01.models.DigitalTwinsEndpointResource] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2020-12-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsEndpointResource"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DigitalTwinsEndpointResource] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = await self._create_or_update_initial( resource_group_name=resource_group_name, @@ -305,102 +437,107 @@ async def begin_create_or_update( endpoint_description=endpoint_description, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('DigitalTwinsEndpointResource', pipeline_response) + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - begin_create_or_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}"} # type: ignore + begin_create_or_update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}" + } async def _delete_initial( - self, - resource_group_name: str, - resource_name: str, - endpoint_name: str, - **kwargs: Any - ) -> Optional["_models.DigitalTwinsEndpointResource"]: - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.DigitalTwinsEndpointResource"]] + self, resource_group_name: str, resource_name: str, endpoint_name: str, **kwargs: Any + ) -> Optional[_models.DigitalTwinsEndpointResource]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2020-12-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - request = build_delete_request_initial( - subscription_id=self._config.subscription_id, + api_version: Literal["2020-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) + cls: ClsType[Optional[_models.DigitalTwinsEndpointResource]] = kwargs.pop("cls", None) + + request = build_delete_request( resource_group_name=resource_group_name, resource_name=resource_name, endpoint_name=endpoint_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._delete_initial.metadata['url'], + template_url=self._delete_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('DigitalTwinsEndpointResource', pipeline_response) + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) if response.status_code == 202: - deserialized = self._deserialize('DigitalTwinsEndpointResource', pipeline_response) + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _delete_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}"} # type: ignore - + _delete_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}" + } @distributed_trace_async async def begin_delete( - self, - resource_group_name: str, - resource_name: str, - endpoint_name: str, - **kwargs: Any - ) -> AsyncLROPoller["_models.DigitalTwinsEndpointResource"]: + self, resource_group_name: str, resource_name: str, endpoint_name: str, **kwargs: Any + ) -> AsyncLROPoller[_models.DigitalTwinsEndpointResource]: """Delete a DigitalTwinsInstance endpoint. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param endpoint_name: Name of Endpoint Resource. + :param endpoint_name: Name of Endpoint Resource. Required. :type endpoint_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. @@ -414,45 +551,50 @@ async def begin_delete( result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2020_12_01.models.DigitalTwinsEndpointResource] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2020-12-01") # type: str - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsEndpointResource"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) + cls: ClsType[_models.DigitalTwinsEndpointResource] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = await self._delete_initial( resource_group_name=resource_group_name, resource_name=resource_name, endpoint_name=endpoint_name, api_version=api_version, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('DigitalTwinsEndpointResource', pipeline_response) + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - begin_delete.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}"} # type: ignore + begin_delete.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}" + } diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/aio/operations/_digital_twins_operations.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/aio/operations/_digital_twins_operations.py index 8fd2fa68c90de..f2c4983f87eeb 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/aio/operations/_digital_twins_operations.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/aio/operations/_digital_twins_operations.py @@ -6,90 +6,112 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar, Union +import sys +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models from ..._vendor import _convert_request -from ...operations._digital_twins_operations import build_check_name_availability_request, build_create_or_update_request_initial, build_delete_request_initial, build_get_request, build_list_by_resource_group_request, build_list_request, build_update_request_initial -T = TypeVar('T') +from ...operations._digital_twins_operations import ( + build_check_name_availability_request, + build_create_or_update_request, + build_delete_request, + build_get_request, + build_list_by_resource_group_request, + build_list_request, + build_update_request, +) + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class DigitalTwinsOperations: - """DigitalTwinsOperations 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 DigitalTwinsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.digitaltwins.v2020_12_01.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.digitaltwins.v2020_12_01.aio.AzureDigitalTwinsManagementClient`'s + :attr:`digital_twins` 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, - resource_group_name: str, - resource_name: str, - **kwargs: Any - ) -> "_models.DigitalTwinsDescription": + async def get(self, resource_group_name: str, resource_name: str, **kwargs: Any) -> _models.DigitalTwinsDescription: """Get DigitalTwinsInstances resource. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: DigitalTwinsDescription, or the result of cls(response) + :return: DigitalTwinsDescription or the result of cls(response) :rtype: ~azure.mgmt.digitaltwins.v2020_12_01.models.DigitalTwinsDescription - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescription"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2020-12-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) + cls: ClsType[_models.DigitalTwinsDescription] = kwargs.pop("cls", None) - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -97,90 +119,190 @@ async def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}"} # type: ignore - + get.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } async def _create_or_update_initial( self, resource_group_name: str, resource_name: str, - digital_twins_create: "_models.DigitalTwinsDescription", + digital_twins_create: Union[_models.DigitalTwinsDescription, IO], **kwargs: Any - ) -> "_models.DigitalTwinsDescription": - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescription"] + ) -> _models.DigitalTwinsDescription: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2020-12-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(digital_twins_create, 'DigitalTwinsDescription') + api_version: Literal["2020-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DigitalTwinsDescription] = kwargs.pop("cls", None) - request = build_create_or_update_request_initial( - subscription_id=self._config.subscription_id, + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(digital_twins_create, (IO, bytes)): + _content = digital_twins_create + else: + _json = self._serialize.body(digital_twins_create, "DigitalTwinsDescription") + + request = build_create_or_update_request( resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._create_or_update_initial.metadata['url'], + content=_content, + template_url=self._create_or_update_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized + return deserialized # type: ignore + + _create_or_update_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } - _create_or_update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}"} # type: ignore + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + digital_twins_create: _models.DigitalTwinsDescription, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.DigitalTwinsDescription]: + """Create or update the metadata of a DigitalTwinsInstance. The usual pattern to modify a property + is to retrieve the DigitalTwinsInstance and security metadata, and then combine them with the + modified values in a new body to update the DigitalTwinsInstance. + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param digital_twins_create: The DigitalTwinsInstance and security metadata. Required. + :type digital_twins_create: ~azure.mgmt.digitaltwins.v2020_12_01.models.DigitalTwinsDescription + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either DigitalTwinsDescription or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2020_12_01.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + digital_twins_create: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.DigitalTwinsDescription]: + """Create or update the metadata of a DigitalTwinsInstance. The usual pattern to modify a property + is to retrieve the DigitalTwinsInstance and security metadata, and then combine them with the + modified values in a new body to update the DigitalTwinsInstance. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param digital_twins_create: The DigitalTwinsInstance and security metadata. Required. + :type digital_twins_create: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either DigitalTwinsDescription or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2020_12_01.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace_async async def begin_create_or_update( self, resource_group_name: str, resource_name: str, - digital_twins_create: "_models.DigitalTwinsDescription", + digital_twins_create: Union[_models.DigitalTwinsDescription, IO], **kwargs: Any - ) -> AsyncLROPoller["_models.DigitalTwinsDescription"]: + ) -> AsyncLROPoller[_models.DigitalTwinsDescription]: """Create or update the metadata of a DigitalTwinsInstance. The usual pattern to modify a property is to retrieve the DigitalTwinsInstance and security metadata, and then combine them with the modified values in a new body to update the DigitalTwinsInstance. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param digital_twins_create: The DigitalTwinsInstance and security metadata. + :param digital_twins_create: The DigitalTwinsInstance and security metadata. Is either a model + type or a IO type. Required. :type digital_twins_create: ~azure.mgmt.digitaltwins.v2020_12_01.models.DigitalTwinsDescription + or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for @@ -193,17 +315,17 @@ async def begin_create_or_update( result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2020_12_01.models.DigitalTwinsDescription] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2020-12-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescription"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DigitalTwinsDescription] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = await self._create_or_update_initial( resource_group_name=resource_group_name, @@ -211,106 +333,133 @@ async def begin_create_or_update( digital_twins_create=digital_twins_create, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - begin_create_or_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}"} # type: ignore + begin_create_or_update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } async def _update_initial( self, resource_group_name: str, resource_name: str, - digital_twins_patch_description: "_models.DigitalTwinsPatchDescription", + digital_twins_patch_description: Union[_models.DigitalTwinsPatchDescription, IO], **kwargs: Any - ) -> "_models.DigitalTwinsDescription": - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescription"] + ) -> _models.DigitalTwinsDescription: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2020-12-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(digital_twins_patch_description, 'DigitalTwinsPatchDescription') + api_version: Literal["2020-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DigitalTwinsDescription] = kwargs.pop("cls", None) - request = build_update_request_initial( - subscription_id=self._config.subscription_id, + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(digital_twins_patch_description, (IO, bytes)): + _content = digital_twins_patch_description + else: + _json = self._serialize.body(digital_twins_patch_description, "DigitalTwinsPatchDescription") + + request = build_update_request( resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._update_initial.metadata['url'], + content=_content, + template_url=self._update_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if response.status_code == 202: - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - _update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}"} # type: ignore + return deserialized # type: ignore + _update_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } - @distributed_trace_async + @overload async def begin_update( self, resource_group_name: str, resource_name: str, - digital_twins_patch_description: "_models.DigitalTwinsPatchDescription", + digital_twins_patch_description: _models.DigitalTwinsPatchDescription, + *, + content_type: str = "application/json", **kwargs: Any - ) -> AsyncLROPoller["_models.DigitalTwinsDescription"]: + ) -> AsyncLROPoller[_models.DigitalTwinsDescription]: """Update metadata of DigitalTwinsInstance. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str :param digital_twins_patch_description: The DigitalTwinsInstance and security metadata. + Required. :type digital_twins_patch_description: ~azure.mgmt.digitaltwins.v2020_12_01.models.DigitalTwinsPatchDescription + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for @@ -323,17 +472,92 @@ async def begin_update( result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2020_12_01.models.DigitalTwinsDescription] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2020-12-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescription"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + + @overload + async def begin_update( + self, + resource_group_name: str, + resource_name: str, + digital_twins_patch_description: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.DigitalTwinsDescription]: + """Update metadata of DigitalTwinsInstance. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param digital_twins_patch_description: The DigitalTwinsInstance and security metadata. + Required. + :type digital_twins_patch_description: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either DigitalTwinsDescription or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2020_12_01.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_update( + self, + resource_group_name: str, + resource_name: str, + digital_twins_patch_description: Union[_models.DigitalTwinsPatchDescription, IO], + **kwargs: Any + ) -> AsyncLROPoller[_models.DigitalTwinsDescription]: + """Update metadata of DigitalTwinsInstance. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param digital_twins_patch_description: The DigitalTwinsInstance and security metadata. Is + either a model type or a IO type. Required. + :type digital_twins_patch_description: + ~azure.mgmt.digitaltwins.v2020_12_01.models.DigitalTwinsPatchDescription or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either DigitalTwinsDescription or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2020_12_01.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DigitalTwinsDescription] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = await self._update_initial( resource_group_name=resource_group_name, @@ -341,97 +565,104 @@ async def begin_update( digital_twins_patch_description=digital_twins_patch_description, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - begin_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}"} # type: ignore + begin_update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } async def _delete_initial( - self, - resource_group_name: str, - resource_name: str, - **kwargs: Any - ) -> Optional["_models.DigitalTwinsDescription"]: - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.DigitalTwinsDescription"]] + self, resource_group_name: str, resource_name: str, **kwargs: Any + ) -> Optional[_models.DigitalTwinsDescription]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2020-12-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - request = build_delete_request_initial( - subscription_id=self._config.subscription_id, + api_version: Literal["2020-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) + cls: ClsType[Optional[_models.DigitalTwinsDescription]] = kwargs.pop("cls", None) + + request = build_delete_request( resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._delete_initial.metadata['url'], + template_url=self._delete_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if response.status_code == 202: - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _delete_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}"} # type: ignore - + _delete_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } @distributed_trace_async async def begin_delete( - self, - resource_group_name: str, - resource_name: str, - **kwargs: Any - ) -> AsyncLROPoller["_models.DigitalTwinsDescription"]: + self, resource_group_name: str, resource_name: str, **kwargs: Any + ) -> AsyncLROPoller[_models.DigitalTwinsDescription]: """Delete a DigitalTwinsInstance. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. @@ -445,86 +676,103 @@ async def begin_delete( result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2020_12_01.models.DigitalTwinsDescription] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2020-12-01") # type: str - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescription"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) + cls: ClsType[_models.DigitalTwinsDescription] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = await self._delete_initial( resource_group_name=resource_group_name, resource_name=resource_name, api_version=api_version, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - begin_delete.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}"} # type: ignore + begin_delete.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } @distributed_trace - def list( - self, - **kwargs: Any - ) -> AsyncIterable["_models.DigitalTwinsDescriptionListResult"]: + def list(self, **kwargs: Any) -> AsyncIterable["_models.DigitalTwinsDescription"]: """Get all the DigitalTwinsInstances in a subscription. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either DigitalTwinsDescriptionListResult or the result of + :return: An iterator like instance of either DigitalTwinsDescription or the result of cls(response) :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.digitaltwins.v2020_12_01.models.DigitalTwinsDescriptionListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.digitaltwins.v2020_12_01.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2020-12-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) + cls: ClsType[_models.DigitalTwinsDescriptionListResult] = kwargs.pop("cls", None) - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescriptionListResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list.metadata['url'], + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: - - request = build_list_request( - subscription_id=self._config.subscription_id, - api_version=api_version, - template_url=next_link, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) @@ -535,16 +783,14 @@ async def extract_data(pipeline_response): deserialized = self._deserialize("DigitalTwinsDescriptionListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -555,56 +801,66 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.DigitalTwins/digitalTwinsInstances"} # type: ignore + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.DigitalTwins/digitalTwinsInstances"} @distributed_trace def list_by_resource_group( - self, - resource_group_name: str, - **kwargs: Any - ) -> AsyncIterable["_models.DigitalTwinsDescriptionListResult"]: + self, resource_group_name: str, **kwargs: Any + ) -> AsyncIterable["_models.DigitalTwinsDescription"]: """Get all the DigitalTwinsInstances in a resource group. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. 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 DigitalTwinsDescriptionListResult or the result of + :return: An iterator like instance of either DigitalTwinsDescription or the result of cls(response) :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.digitaltwins.v2020_12_01.models.DigitalTwinsDescriptionListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.digitaltwins.v2020_12_01.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2020-12-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) + cls: ClsType[_models.DigitalTwinsDescriptionListResult] = kwargs.pop("cls", None) - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescriptionListResult"] 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( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata['url'], + template_url=self.list_by_resource_group.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: - - request = build_list_by_resource_group_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - api_version=api_version, - template_url=next_link, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) @@ -615,16 +871,14 @@ async def extract_data(pipeline_response): deserialized = self._deserialize("DigitalTwinsDescriptionListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -635,59 +889,127 @@ 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.DigitalTwins/digitalTwinsInstances"} # type: ignore + list_by_resource_group.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances" + } - @distributed_trace_async + @overload async def check_name_availability( self, location: str, - digital_twins_instance_check_name: "_models.CheckNameRequest", + digital_twins_instance_check_name: _models.CheckNameRequest, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.CheckNameResult": + ) -> _models.CheckNameResult: """Check if a DigitalTwinsInstance name is available. - :param location: Location of DigitalTwinsInstance. + :param location: Location of DigitalTwinsInstance. Required. :type location: str :param digital_twins_instance_check_name: Set the name parameter in the DigitalTwinsInstanceCheckName structure to the name of the DigitalTwinsInstance to check. + Required. :type digital_twins_instance_check_name: ~azure.mgmt.digitaltwins.v2020_12_01.models.CheckNameRequest + :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: CheckNameResult, or the result of cls(response) + :return: CheckNameResult or the result of cls(response) :rtype: ~azure.mgmt.digitaltwins.v2020_12_01.models.CheckNameResult - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def check_name_availability( + self, + location: str, + digital_twins_instance_check_name: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.CheckNameResult: + """Check if a DigitalTwinsInstance name is available. + + :param location: Location of DigitalTwinsInstance. Required. + :type location: str + :param digital_twins_instance_check_name: Set the name parameter in the + DigitalTwinsInstanceCheckName structure to the name of the DigitalTwinsInstance to check. + Required. + :type digital_twins_instance_check_name: 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: CheckNameResult or the result of cls(response) + :rtype: ~azure.mgmt.digitaltwins.v2020_12_01.models.CheckNameResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def check_name_availability( + self, location: str, digital_twins_instance_check_name: Union[_models.CheckNameRequest, IO], **kwargs: Any + ) -> _models.CheckNameResult: + """Check if a DigitalTwinsInstance name is available. + + :param location: Location of DigitalTwinsInstance. Required. + :type location: str + :param digital_twins_instance_check_name: Set the name parameter in the + DigitalTwinsInstanceCheckName structure to the name of the DigitalTwinsInstance to check. Is + either a model type or a IO type. Required. + :type digital_twins_instance_check_name: + ~azure.mgmt.digitaltwins.v2020_12_01.models.CheckNameRequest 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: CheckNameResult or the result of cls(response) + :rtype: ~azure.mgmt.digitaltwins.v2020_12_01.models.CheckNameResult + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.CheckNameResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', "2020-12-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + api_version: Literal["2020-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.CheckNameResult] = kwargs.pop("cls", None) - _json = self._serialize.body(digital_twins_instance_check_name, 'CheckNameRequest') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(digital_twins_instance_check_name, (IO, bytes)): + _content = digital_twins_instance_check_name + else: + _json = self._serialize.body(digital_twins_instance_check_name, "CheckNameRequest") request = build_check_name_availability_request( - subscription_id=self._config.subscription_id, location=location, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self.check_name_availability.metadata['url'], + content=_content, + template_url=self.check_name_availability.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -695,12 +1017,13 @@ async def check_name_availability( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('CheckNameResult', pipeline_response) + deserialized = self._deserialize("CheckNameResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - check_name_availability.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.DigitalTwins/locations/{location}/checkNameAvailability"} # type: ignore - + check_name_availability.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.DigitalTwins/locations/{location}/checkNameAvailability" + } diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/aio/operations/_operations.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/aio/operations/_operations.py index 381f404a9bbd9..b110f72befc3e 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/aio/operations/_operations.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/aio/operations/_operations.py @@ -6,79 +6,105 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models from ..._vendor import _convert_request from ...operations._operations import build_list_request -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class Operations: - """Operations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class Operations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.digitaltwins.v2020_12_01.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.digitaltwins.v2020_12_01.aio.AzureDigitalTwinsManagementClient`'s + :attr:`operations` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace - def list( - self, - **kwargs: Any - ) -> AsyncIterable["_models.OperationListResult"]: + def list(self, **kwargs: Any) -> AsyncIterable["_models.Operation"]: """Lists all of the available DigitalTwins service REST API operations. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either OperationListResult or the result of cls(response) + :return: An iterator like instance of either Operation or the result of cls(response) :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.digitaltwins.v2020_12_01.models.OperationListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.digitaltwins.v2020_12_01.models.Operation] + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2020-12-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) + cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) - cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationListResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( api_version=api_version, - template_url=self.list.metadata['url'], + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: - - request = build_list_request( - api_version=api_version, - template_url=next_link, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) @@ -89,16 +115,14 @@ async def extract_data(pipeline_response): deserialized = self._deserialize("OperationListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -109,8 +133,6 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/providers/Microsoft.DigitalTwins/operations"} # type: ignore + list.metadata = {"url": "/providers/Microsoft.DigitalTwins/operations"} diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/aio/operations/_patch.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/aio/operations/_patch.py new file mode 100644 index 0000000000000..f7dd32510333d --- /dev/null +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/aio/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/aio/operations/_private_endpoint_connections_operations.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/aio/operations/_private_endpoint_connections_operations.py index 8f98919ef2036..e5a1ccb1f3863 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/aio/operations/_private_endpoint_connections_operations.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/aio/operations/_private_endpoint_connections_operations.py @@ -6,88 +6,108 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Optional, TypeVar, Union - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import sys +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, cast, 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.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod 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 azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models from ..._vendor import _convert_request -from ...operations._private_endpoint_connections_operations import build_create_or_update_request_initial, build_delete_request_initial, build_get_request, build_list_request -T = TypeVar('T') +from ...operations._private_endpoint_connections_operations import ( + build_create_or_update_request, + build_delete_request, + build_get_request, + build_list_request, +) + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class PrivateEndpointConnectionsOperations: - """PrivateEndpointConnectionsOperations 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 PrivateEndpointConnectionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.digitaltwins.v2020_12_01.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.digitaltwins.v2020_12_01.aio.AzureDigitalTwinsManagementClient`'s + :attr:`private_endpoint_connections` 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 list( - self, - resource_group_name: str, - resource_name: str, - **kwargs: Any - ) -> "_models.PrivateEndpointConnectionsResponse": + self, resource_group_name: str, resource_name: str, **kwargs: Any + ) -> _models.PrivateEndpointConnectionsResponse: """List private endpoint connection properties. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: PrivateEndpointConnectionsResponse, or the result of cls(response) + :return: PrivateEndpointConnectionsResponse or the result of cls(response) :rtype: ~azure.mgmt.digitaltwins.v2020_12_01.models.PrivateEndpointConnectionsResponse - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnectionsResponse"] 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', "2020-12-01") # type: str + api_version: Literal["2020-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) + cls: ClsType[_models.PrivateEndpointConnectionsResponse] = kwargs.pop("cls", None) - request = build_list_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list.metadata['url'], + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -95,63 +115,66 @@ async def list( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('PrivateEndpointConnectionsResponse', pipeline_response) + deserialized = self._deserialize("PrivateEndpointConnectionsResponse", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - list.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections"} # type: ignore - + list.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections" + } @distributed_trace_async async def get( - self, - resource_group_name: str, - resource_name: str, - private_endpoint_connection_name: str, - **kwargs: Any - ) -> "_models.PrivateEndpointConnection": + self, resource_group_name: str, resource_name: str, private_endpoint_connection_name: str, **kwargs: Any + ) -> _models.PrivateEndpointConnection: """Get private endpoint connection properties for the given private endpoint. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param private_endpoint_connection_name: The name of the private endpoint connection. + :param private_endpoint_connection_name: The name of the private endpoint connection. Required. :type private_endpoint_connection_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: PrivateEndpointConnection, or the result of cls(response) + :return: PrivateEndpointConnection or the result of cls(response) :rtype: ~azure.mgmt.digitaltwins.v2020_12_01.models.PrivateEndpointConnection - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnection"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2020-12-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) + cls: ClsType[_models.PrivateEndpointConnection] = kwargs.pop("cls", None) - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, private_endpoint_connection_name=private_endpoint_connection_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -159,76 +182,77 @@ async def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore - + get.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}" + } async def _delete_initial( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - resource_name: str, - private_endpoint_connection_name: str, - **kwargs: Any + self, resource_group_name: str, resource_name: str, private_endpoint_connection_name: str, **kwargs: Any ) -> None: - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2020-12-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - request = build_delete_request_initial( - subscription_id=self._config.subscription_id, + api_version: Literal["2020-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + request = build_delete_request( resource_group_name=resource_group_name, resource_name=resource_name, private_endpoint_connection_name=private_endpoint_connection_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._delete_initial.metadata['url'], + template_url=self._delete_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - _delete_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore - + _delete_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}" + } @distributed_trace_async - async def begin_delete( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - resource_name: str, - private_endpoint_connection_name: str, - **kwargs: Any + async def begin_delete( + self, resource_group_name: str, resource_name: str, private_endpoint_connection_name: str, **kwargs: Any ) -> AsyncLROPoller[None]: """Delete private endpoint connection with the specified name. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param private_endpoint_connection_name: The name of the private endpoint connection. + :param private_endpoint_connection_name: The name of the private endpoint connection. Required. :type private_endpoint_connection_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. @@ -240,124 +264,152 @@ async def begin_delete( # pylint: disable=inconsistent-return-statements Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2020-12-01") # type: str - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType[None] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: - raw_result = await self._delete_initial( + raw_result = await self._delete_initial( # type: ignore resource_group_name=resource_group_name, resource_name=resource_name, private_endpoint_connection_name=private_endpoint_connection_name, api_version=api_version, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - - if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - begin_delete.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore + begin_delete.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}" + } async def _create_or_update_initial( self, resource_group_name: str, resource_name: str, private_endpoint_connection_name: str, - private_endpoint_connection: "_models.PrivateEndpointConnection", + private_endpoint_connection: Union[_models.PrivateEndpointConnection, IO], **kwargs: Any - ) -> "_models.PrivateEndpointConnection": - cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnection"] + ) -> _models.PrivateEndpointConnection: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2020-12-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(private_endpoint_connection, 'PrivateEndpointConnection') + api_version: Literal["2020-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PrivateEndpointConnection] = kwargs.pop("cls", None) - request = build_create_or_update_request_initial( - subscription_id=self._config.subscription_id, + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(private_endpoint_connection, (IO, bytes)): + _content = private_endpoint_connection + else: + _json = self._serialize.body(private_endpoint_connection, "PrivateEndpointConnection") + + request = build_create_or_update_request( resource_group_name=resource_group_name, resource_name=resource_name, private_endpoint_connection_name=private_endpoint_connection_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._create_or_update_initial.metadata['url'], + content=_content, + template_url=self._create_or_update_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) if response.status_code == 202: - deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - _create_or_update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore + return deserialized # type: ignore + _create_or_update_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}" + } - @distributed_trace_async + @overload async def begin_create_or_update( self, resource_group_name: str, resource_name: str, private_endpoint_connection_name: str, - private_endpoint_connection: "_models.PrivateEndpointConnection", + private_endpoint_connection: _models.PrivateEndpointConnection, + *, + content_type: str = "application/json", **kwargs: Any - ) -> AsyncLROPoller["_models.PrivateEndpointConnection"]: + ) -> AsyncLROPoller[_models.PrivateEndpointConnection]: """Update the status of a private endpoint connection with the given name. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param private_endpoint_connection_name: The name of the private endpoint connection. + :param private_endpoint_connection_name: The name of the private endpoint connection. Required. :type private_endpoint_connection_name: str :param private_endpoint_connection: The private endpoint connection with updated properties. + Required. :type private_endpoint_connection: ~azure.mgmt.digitaltwins.v2020_12_01.models.PrivateEndpointConnection + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for @@ -370,17 +422,98 @@ async def begin_create_or_update( result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2020_12_01.models.PrivateEndpointConnection] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2020-12-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnection"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + private_endpoint_connection_name: str, + private_endpoint_connection: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.PrivateEndpointConnection]: + """Update the status of a private endpoint connection with the given name. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param private_endpoint_connection_name: The name of the private endpoint connection. Required. + :type private_endpoint_connection_name: str + :param private_endpoint_connection: The private endpoint connection with updated properties. + Required. + :type private_endpoint_connection: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either PrivateEndpointConnection or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2020_12_01.models.PrivateEndpointConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + private_endpoint_connection_name: str, + private_endpoint_connection: Union[_models.PrivateEndpointConnection, IO], + **kwargs: Any + ) -> AsyncLROPoller[_models.PrivateEndpointConnection]: + """Update the status of a private endpoint connection with the given name. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param private_endpoint_connection_name: The name of the private endpoint connection. Required. + :type private_endpoint_connection_name: str + :param private_endpoint_connection: The private endpoint connection with updated properties. Is + either a model type or a IO type. Required. + :type private_endpoint_connection: + ~azure.mgmt.digitaltwins.v2020_12_01.models.PrivateEndpointConnection or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either PrivateEndpointConnection or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2020_12_01.models.PrivateEndpointConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PrivateEndpointConnection] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = await self._create_or_update_initial( resource_group_name=resource_group_name, @@ -389,29 +522,34 @@ async def begin_create_or_update( private_endpoint_connection=private_endpoint_connection, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - begin_create_or_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore + begin_create_or_update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}" + } diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/aio/operations/_private_link_resources_operations.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/aio/operations/_private_link_resources_operations.py index bf54b9ab43537..4b6fe072d8e12 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/aio/operations/_private_link_resources_operations.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/aio/operations/_private_link_resources_operations.py @@ -6,86 +6,101 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, Callable, Dict, Optional, TypeVar -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_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models from ..._vendor import _convert_request from ...operations._private_link_resources_operations import build_get_request, build_list_request -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class PrivateLinkResourcesOperations: - """PrivateLinkResourcesOperations 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 PrivateLinkResourcesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.digitaltwins.v2020_12_01.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.digitaltwins.v2020_12_01.aio.AzureDigitalTwinsManagementClient`'s + :attr:`private_link_resources` 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 list( - self, - resource_group_name: str, - resource_name: str, - **kwargs: Any - ) -> "_models.GroupIdInformationResponse": + self, resource_group_name: str, resource_name: str, **kwargs: Any + ) -> _models.GroupIdInformationResponse: """List private link resources for given Digital Twin. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: GroupIdInformationResponse, or the result of cls(response) + :return: GroupIdInformationResponse or the result of cls(response) :rtype: ~azure.mgmt.digitaltwins.v2020_12_01.models.GroupIdInformationResponse - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.GroupIdInformationResponse"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2020-12-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) + cls: ClsType[_models.GroupIdInformationResponse] = kwargs.pop("cls", None) - request = build_list_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list.metadata['url'], + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -93,63 +108,66 @@ async def list( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('GroupIdInformationResponse', pipeline_response) + deserialized = self._deserialize("GroupIdInformationResponse", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - list.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateLinkResources"} # type: ignore - + list.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateLinkResources" + } @distributed_trace_async async def get( - self, - resource_group_name: str, - resource_name: str, - resource_id: str, - **kwargs: Any - ) -> "_models.GroupIdInformation": + self, resource_group_name: str, resource_name: str, resource_id: str, **kwargs: Any + ) -> _models.GroupIdInformation: """Get the specified private link resource for the given Digital Twin. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param resource_id: The name of the private link resource. + :param resource_id: The name of the private link resource. Required. :type resource_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: GroupIdInformation, or the result of cls(response) + :return: GroupIdInformation or the result of cls(response) :rtype: ~azure.mgmt.digitaltwins.v2020_12_01.models.GroupIdInformation - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.GroupIdInformation"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2020-12-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) + cls: ClsType[_models.GroupIdInformation] = kwargs.pop("cls", None) - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, resource_id=resource_id, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -157,12 +175,13 @@ async def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('GroupIdInformation', pipeline_response) + deserialized = self._deserialize("GroupIdInformation", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateLinkResources/{resourceId}"} # type: ignore - + get.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateLinkResources/{resourceId}" + } diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/models/__init__.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/models/__init__.py index c7cefb74b47d1..b4f552a0f1cc4 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/models/__init__.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/models/__init__.py @@ -39,59 +39,61 @@ from ._models_py3 import PrivateEndpointConnectionsResponse from ._models_py3 import ServiceBus - -from ._azure_digital_twins_management_client_enums import ( - AuthenticationType, - ConnectionPropertiesProvisioningState, - DigitalTwinsIdentityType, - EndpointProvisioningState, - EndpointType, - PrivateLinkServiceConnectionStatus, - ProvisioningState, - PublicNetworkAccess, - Reason, -) +from ._azure_digital_twins_management_client_enums import AuthenticationType +from ._azure_digital_twins_management_client_enums import ConnectionPropertiesProvisioningState +from ._azure_digital_twins_management_client_enums import DigitalTwinsIdentityType +from ._azure_digital_twins_management_client_enums import EndpointProvisioningState +from ._azure_digital_twins_management_client_enums import EndpointType +from ._azure_digital_twins_management_client_enums import PrivateLinkServiceConnectionStatus +from ._azure_digital_twins_management_client_enums import ProvisioningState +from ._azure_digital_twins_management_client_enums import PublicNetworkAccess +from ._azure_digital_twins_management_client_enums import Reason +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk __all__ = [ - 'CheckNameRequest', - 'CheckNameResult', - 'ConnectionProperties', - 'ConnectionPropertiesPrivateEndpoint', - 'ConnectionPropertiesPrivateLinkServiceConnectionState', - 'ConnectionState', - 'DigitalTwinsDescription', - 'DigitalTwinsDescriptionListResult', - 'DigitalTwinsEndpointResource', - 'DigitalTwinsEndpointResourceListResult', - 'DigitalTwinsEndpointResourceProperties', - 'DigitalTwinsIdentity', - 'DigitalTwinsPatchDescription', - 'DigitalTwinsPatchProperties', - 'DigitalTwinsResource', - 'ErrorDefinition', - 'ErrorResponse', - 'EventGrid', - 'EventHub', - 'ExternalResource', - 'GroupIdInformation', - 'GroupIdInformationProperties', - 'GroupIdInformationPropertiesAutoGenerated', - 'GroupIdInformationResponse', - 'Operation', - 'OperationDisplay', - 'OperationListResult', - 'PrivateEndpoint', - 'PrivateEndpointConnection', - 'PrivateEndpointConnectionProperties', - 'PrivateEndpointConnectionsResponse', - 'ServiceBus', - 'AuthenticationType', - 'ConnectionPropertiesProvisioningState', - 'DigitalTwinsIdentityType', - 'EndpointProvisioningState', - 'EndpointType', - 'PrivateLinkServiceConnectionStatus', - 'ProvisioningState', - 'PublicNetworkAccess', - 'Reason', + "CheckNameRequest", + "CheckNameResult", + "ConnectionProperties", + "ConnectionPropertiesPrivateEndpoint", + "ConnectionPropertiesPrivateLinkServiceConnectionState", + "ConnectionState", + "DigitalTwinsDescription", + "DigitalTwinsDescriptionListResult", + "DigitalTwinsEndpointResource", + "DigitalTwinsEndpointResourceListResult", + "DigitalTwinsEndpointResourceProperties", + "DigitalTwinsIdentity", + "DigitalTwinsPatchDescription", + "DigitalTwinsPatchProperties", + "DigitalTwinsResource", + "ErrorDefinition", + "ErrorResponse", + "EventGrid", + "EventHub", + "ExternalResource", + "GroupIdInformation", + "GroupIdInformationProperties", + "GroupIdInformationPropertiesAutoGenerated", + "GroupIdInformationResponse", + "Operation", + "OperationDisplay", + "OperationListResult", + "PrivateEndpoint", + "PrivateEndpointConnection", + "PrivateEndpointConnectionProperties", + "PrivateEndpointConnectionsResponse", + "ServiceBus", + "AuthenticationType", + "ConnectionPropertiesProvisioningState", + "DigitalTwinsIdentityType", + "EndpointProvisioningState", + "EndpointType", + "PrivateLinkServiceConnectionStatus", + "ProvisioningState", + "PublicNetworkAccess", + "Reason", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/models/_azure_digital_twins_management_client_enums.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/models/_azure_digital_twins_management_client_enums.py index 83f29f9f75501..a73b22f851361 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/models/_azure_digital_twins_management_client_enums.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/models/_azure_digital_twins_management_client_enums.py @@ -7,27 +7,26 @@ # -------------------------------------------------------------------------- from enum import Enum -from six import with_metaclass from azure.core import CaseInsensitiveEnumMeta -class AuthenticationType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """Specifies the authentication type being used for connecting to the endpoint. - """ +class AuthenticationType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Specifies the authentication type being used for connecting to the endpoint.""" KEY_BASED = "KeyBased" IDENTITY_BASED = "IdentityBased" -class ConnectionPropertiesProvisioningState(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The provisioning state. - """ + +class ConnectionPropertiesProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The provisioning state.""" PENDING = "Pending" APPROVED = "Approved" REJECTED = "Rejected" DISCONNECTED = "Disconnected" -class DigitalTwinsIdentityType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): + +class DigitalTwinsIdentityType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The type of Managed Identity used by the DigitalTwinsInstance. Only SystemAssigned is supported. """ @@ -35,9 +34,9 @@ class DigitalTwinsIdentityType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum NONE = "None" SYSTEM_ASSIGNED = "SystemAssigned" -class EndpointProvisioningState(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The provisioning state. - """ + +class EndpointProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The provisioning state.""" PROVISIONING = "Provisioning" DELETING = "Deleting" @@ -51,26 +50,26 @@ class EndpointProvisioningState(with_metaclass(CaseInsensitiveEnumMeta, str, Enu MOVING = "Moving" DISABLED = "Disabled" -class EndpointType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The type of Digital Twins endpoint - """ + +class EndpointType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of Digital Twins endpoint.""" EVENT_HUB = "EventHub" EVENT_GRID = "EventGrid" SERVICE_BUS = "ServiceBus" -class PrivateLinkServiceConnectionStatus(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The status of a private endpoint connection. - """ + +class PrivateLinkServiceConnectionStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The status of a private endpoint connection.""" PENDING = "Pending" APPROVED = "Approved" REJECTED = "Rejected" DISCONNECTED = "Disconnected" -class ProvisioningState(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The provisioning state. - """ + +class ProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The provisioning state.""" PROVISIONING = "Provisioning" DELETING = "Deleting" @@ -84,16 +83,16 @@ class ProvisioningState(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): RESTORING = "Restoring" MOVING = "Moving" -class PublicNetworkAccess(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """Public network access for the DigitalTwinsInstance. - """ + +class PublicNetworkAccess(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Public network access for the DigitalTwinsInstance.""" ENABLED = "Enabled" DISABLED = "Disabled" -class Reason(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """Message providing the reason why the given name is invalid. - """ + +class Reason(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Message providing the reason why the given name is invalid.""" INVALID = "Invalid" ALREADY_EXISTS = "AlreadyExists" diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/models/_models_py3.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/models/_models_py3.py index 204072a793129..e9a778c9e0635 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/models/_models_py3.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/models/_models_py3.py @@ -1,4 +1,5 @@ # coding=utf-8 +# pylint: disable=too-many-lines # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. @@ -6,55 +7,51 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Dict, List, Optional, Union +from typing import Dict, List, Optional, TYPE_CHECKING, Union -from azure.core.exceptions import HttpResponseError -import msrest.serialization +from ... import _serialization -from ._azure_digital_twins_management_client_enums import * +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from .. import models as _models -class CheckNameRequest(msrest.serialization.Model): +class CheckNameRequest(_serialization.Model): """The result returned from a database check name availability request. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. - :ivar name: Required. Resource name. + :ivar name: Resource name. Required. :vartype name: str :ivar type: The type of resource, for instance Microsoft.DigitalTwins/digitalTwinsInstances. - Has constant value: "Microsoft.DigitalTwins/digitalTwinsInstances". + Required. Default value is "Microsoft.DigitalTwins/digitalTwinsInstances". :vartype type: str """ _validation = { - 'name': {'required': True}, - 'type': {'required': True, 'constant': True}, + "name": {"required": True}, + "type": {"required": True, "constant": True}, } _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, } type = "Microsoft.DigitalTwins/digitalTwinsInstances" - def __init__( - self, - *, - name: str, - **kwargs - ): + def __init__(self, *, name: str, **kwargs): """ - :keyword name: Required. Resource name. + :keyword name: Resource name. Required. :paramtype name: str """ - super(CheckNameRequest, self).__init__(**kwargs) + super().__init__(**kwargs) self.name = name -class CheckNameResult(msrest.serialization.Model): +class CheckNameResult(_serialization.Model): """The result returned from a check name availability request. :ivar name_available: Specifies a Boolean value that indicates if the name is available. @@ -62,15 +59,15 @@ class CheckNameResult(msrest.serialization.Model): :ivar message: Message indicating an unavailable name due to a conflict, or a description of the naming rules that are violated. :vartype message: str - :ivar reason: Message providing the reason why the given name is invalid. Possible values - include: "Invalid", "AlreadyExists". + :ivar reason: Message providing the reason why the given name is invalid. Known values are: + "Invalid" and "AlreadyExists". :vartype reason: str or ~azure.mgmt.digitaltwins.v2020_12_01.models.Reason """ _attribute_map = { - 'name_available': {'key': 'nameAvailable', 'type': 'bool'}, - 'message': {'key': 'message', 'type': 'str'}, - 'reason': {'key': 'reason', 'type': 'str'}, + "name_available": {"key": "nameAvailable", "type": "bool"}, + "message": {"key": "message", "type": "str"}, + "reason": {"key": "reason", "type": "str"}, } def __init__( @@ -78,7 +75,7 @@ def __init__( *, name_available: Optional[bool] = None, message: Optional[str] = None, - reason: Optional[Union[str, "Reason"]] = None, + reason: Optional[Union[str, "_models.Reason"]] = None, **kwargs ): """ @@ -87,23 +84,23 @@ def __init__( :keyword message: Message indicating an unavailable name due to a conflict, or a description of the naming rules that are violated. :paramtype message: str - :keyword reason: Message providing the reason why the given name is invalid. Possible values - include: "Invalid", "AlreadyExists". + :keyword reason: Message providing the reason why the given name is invalid. Known values are: + "Invalid" and "AlreadyExists". :paramtype reason: str or ~azure.mgmt.digitaltwins.v2020_12_01.models.Reason """ - super(CheckNameResult, self).__init__(**kwargs) + super().__init__(**kwargs) self.name_available = name_available self.message = message self.reason = reason -class ConnectionProperties(msrest.serialization.Model): +class ConnectionProperties(_serialization.Model): """The properties of a private endpoint connection. Variables are only populated by the server, and will be ignored when sending a request. - :ivar provisioning_state: The provisioning state. Possible values include: "Pending", - "Approved", "Rejected", "Disconnected". + :ivar provisioning_state: The provisioning state. Known values are: "Pending", "Approved", + "Rejected", and "Disconnected". :vartype provisioning_state: str or ~azure.mgmt.digitaltwins.v2020_12_01.models.ConnectionPropertiesProvisioningState :ivar private_endpoint: @@ -117,22 +114,27 @@ class ConnectionProperties(msrest.serialization.Model): """ _validation = { - 'provisioning_state': {'readonly': True}, + "provisioning_state": {"readonly": True}, } _attribute_map = { - 'provisioning_state': {'key': 'provisioningState', 'type': 'str'}, - 'private_endpoint': {'key': 'privateEndpoint', 'type': 'ConnectionPropertiesPrivateEndpoint'}, - 'group_ids': {'key': 'groupIds', 'type': '[str]'}, - 'private_link_service_connection_state': {'key': 'privateLinkServiceConnectionState', 'type': 'ConnectionPropertiesPrivateLinkServiceConnectionState'}, + "provisioning_state": {"key": "provisioningState", "type": "str"}, + "private_endpoint": {"key": "privateEndpoint", "type": "ConnectionPropertiesPrivateEndpoint"}, + "group_ids": {"key": "groupIds", "type": "[str]"}, + "private_link_service_connection_state": { + "key": "privateLinkServiceConnectionState", + "type": "ConnectionPropertiesPrivateLinkServiceConnectionState", + }, } def __init__( self, *, - private_endpoint: Optional["ConnectionPropertiesPrivateEndpoint"] = None, + private_endpoint: Optional["_models.ConnectionPropertiesPrivateEndpoint"] = None, group_ids: Optional[List[str]] = None, - private_link_service_connection_state: Optional["ConnectionPropertiesPrivateLinkServiceConnectionState"] = None, + private_link_service_connection_state: Optional[ + "_models.ConnectionPropertiesPrivateLinkServiceConnectionState" + ] = None, **kwargs ): """ @@ -145,14 +147,14 @@ def __init__( :paramtype private_link_service_connection_state: ~azure.mgmt.digitaltwins.v2020_12_01.models.ConnectionPropertiesPrivateLinkServiceConnectionState """ - super(ConnectionProperties, self).__init__(**kwargs) + super().__init__(**kwargs) self.provisioning_state = None self.private_endpoint = private_endpoint self.group_ids = group_ids self.private_link_service_connection_state = private_link_service_connection_state -class PrivateEndpoint(msrest.serialization.Model): +class PrivateEndpoint(_serialization.Model): """The private endpoint property of a private endpoint connection. Variables are only populated by the server, and will be ignored when sending a request. @@ -162,20 +164,16 @@ class PrivateEndpoint(msrest.serialization.Model): """ _validation = { - 'id': {'readonly': True}, + "id": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(PrivateEndpoint, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.id = None @@ -189,69 +187,65 @@ class ConnectionPropertiesPrivateEndpoint(PrivateEndpoint): """ _validation = { - 'id': {'readonly': True}, + "id": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(ConnectionPropertiesPrivateEndpoint, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) -class ConnectionState(msrest.serialization.Model): +class ConnectionState(_serialization.Model): """The current state of a private endpoint connection. All required parameters must be populated in order to send to Azure. - :ivar status: Required. The status of a private endpoint connection. Possible values include: - "Pending", "Approved", "Rejected", "Disconnected". + :ivar status: The status of a private endpoint connection. Required. Known values are: + "Pending", "Approved", "Rejected", and "Disconnected". :vartype status: str or ~azure.mgmt.digitaltwins.v2020_12_01.models.PrivateLinkServiceConnectionStatus - :ivar description: Required. The description for the current state of a private endpoint - connection. + :ivar description: The description for the current state of a private endpoint connection. + Required. :vartype description: str :ivar actions_required: Actions required for a private endpoint connection. :vartype actions_required: str """ _validation = { - 'status': {'required': True}, - 'description': {'required': True}, + "status": {"required": True}, + "description": {"required": True}, } _attribute_map = { - 'status': {'key': 'status', 'type': 'str'}, - 'description': {'key': 'description', 'type': 'str'}, - 'actions_required': {'key': 'actionsRequired', 'type': 'str'}, + "status": {"key": "status", "type": "str"}, + "description": {"key": "description", "type": "str"}, + "actions_required": {"key": "actionsRequired", "type": "str"}, } def __init__( self, *, - status: Union[str, "PrivateLinkServiceConnectionStatus"], + status: Union[str, "_models.PrivateLinkServiceConnectionStatus"], description: str, actions_required: Optional[str] = None, **kwargs ): """ - :keyword status: Required. The status of a private endpoint connection. Possible values - include: "Pending", "Approved", "Rejected", "Disconnected". + :keyword status: The status of a private endpoint connection. Required. Known values are: + "Pending", "Approved", "Rejected", and "Disconnected". :paramtype status: str or ~azure.mgmt.digitaltwins.v2020_12_01.models.PrivateLinkServiceConnectionStatus - :keyword description: Required. The description for the current state of a private endpoint - connection. + :keyword description: The description for the current state of a private endpoint connection. + Required. :paramtype description: str :keyword actions_required: Actions required for a private endpoint connection. :paramtype actions_required: str """ - super(ConnectionState, self).__init__(**kwargs) + super().__init__(**kwargs) self.status = status self.description = description self.actions_required = actions_required @@ -262,51 +256,51 @@ class ConnectionPropertiesPrivateLinkServiceConnectionState(ConnectionState): All required parameters must be populated in order to send to Azure. - :ivar status: Required. The status of a private endpoint connection. Possible values include: - "Pending", "Approved", "Rejected", "Disconnected". + :ivar status: The status of a private endpoint connection. Required. Known values are: + "Pending", "Approved", "Rejected", and "Disconnected". :vartype status: str or ~azure.mgmt.digitaltwins.v2020_12_01.models.PrivateLinkServiceConnectionStatus - :ivar description: Required. The description for the current state of a private endpoint - connection. + :ivar description: The description for the current state of a private endpoint connection. + Required. :vartype description: str :ivar actions_required: Actions required for a private endpoint connection. :vartype actions_required: str """ _validation = { - 'status': {'required': True}, - 'description': {'required': True}, + "status": {"required": True}, + "description": {"required": True}, } _attribute_map = { - 'status': {'key': 'status', 'type': 'str'}, - 'description': {'key': 'description', 'type': 'str'}, - 'actions_required': {'key': 'actionsRequired', 'type': 'str'}, + "status": {"key": "status", "type": "str"}, + "description": {"key": "description", "type": "str"}, + "actions_required": {"key": "actionsRequired", "type": "str"}, } def __init__( self, *, - status: Union[str, "PrivateLinkServiceConnectionStatus"], + status: Union[str, "_models.PrivateLinkServiceConnectionStatus"], description: str, actions_required: Optional[str] = None, **kwargs ): """ - :keyword status: Required. The status of a private endpoint connection. Possible values - include: "Pending", "Approved", "Rejected", "Disconnected". + :keyword status: The status of a private endpoint connection. Required. Known values are: + "Pending", "Approved", "Rejected", and "Disconnected". :paramtype status: str or ~azure.mgmt.digitaltwins.v2020_12_01.models.PrivateLinkServiceConnectionStatus - :keyword description: Required. The description for the current state of a private endpoint - connection. + :keyword description: The description for the current state of a private endpoint connection. + Required. :paramtype description: str :keyword actions_required: Actions required for a private endpoint connection. :paramtype actions_required: str """ - super(ConnectionPropertiesPrivateLinkServiceConnectionState, self).__init__(status=status, description=description, actions_required=actions_required, **kwargs) + super().__init__(status=status, description=description, actions_required=actions_required, **kwargs) -class DigitalTwinsResource(msrest.serialization.Model): +class DigitalTwinsResource(_serialization.Model): """The common properties of a DigitalTwinsInstance. Variables are only populated by the server, and will be ignored when sending a request. @@ -319,28 +313,28 @@ class DigitalTwinsResource(msrest.serialization.Model): :vartype name: str :ivar type: The resource type. :vartype type: str - :ivar location: Required. The resource location. + :ivar location: The resource location. Required. :vartype location: str - :ivar tags: A set of tags. The resource tags. + :ivar tags: The resource tags. :vartype tags: dict[str, str] :ivar identity: The managed identity for the DigitalTwinsInstance. :vartype identity: ~azure.mgmt.digitaltwins.v2020_12_01.models.DigitalTwinsIdentity """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True, 'pattern': r'^(?!-)[A-Za-z0-9-]{3,63}(?= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False + def build_list_request( - subscription_id: str, - resource_group_name: str, - resource_name: str, - **kwargs: Any + resource_group_name: str, resource_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = kwargs.pop('api_version', "2020-12-01") # type: str + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints", + ) # 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', max_length=90, min_length=1), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=63, min_length=3, pattern=r'^(?!-)[A-Za-z0-9-]{3,63}(? HttpRequest: - api_version = kwargs.pop('api_version', "2020-12-01") # type: str + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}", + ) # 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', max_length=90, min_length=1), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=63, min_length=3, pattern=r'^(?!-)[A-Za-z0-9-]{3,63}(? HttpRequest: - api_version = kwargs.pop('api_version', "2020-12-01") # type: str - content_type = kwargs.pop('content_type', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}", + ) # 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', max_length=90, min_length=1), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=63, min_length=3, pattern=r'^(?!-)[A-Za-z0-9-]{3,63}(? HttpRequest: - api_version = kwargs.pop('api_version', "2020-12-01") # type: str + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}", + ) # 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', max_length=90, min_length=1), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=63, min_length=3, pattern=r'^(?!-)[A-Za-z0-9-]{3,63}(? Iterable["_models.DigitalTwinsEndpointResourceListResult"]: + self, resource_group_name: str, resource_name: str, **kwargs: Any + ) -> Iterable["_models.DigitalTwinsEndpointResource"]: """Get DigitalTwinsInstance Endpoints. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either DigitalTwinsEndpointResourceListResult or the - result of cls(response) + :return: An iterator like instance of either DigitalTwinsEndpointResource or the result of + cls(response) :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.digitaltwins.v2020_12_01.models.DigitalTwinsEndpointResourceListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.paging.ItemPaged[~azure.mgmt.digitaltwins.v2020_12_01.models.DigitalTwinsEndpointResource] + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2020-12-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) + cls: ClsType[_models.DigitalTwinsEndpointResourceListResult] = kwargs.pop("cls", None) - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsEndpointResourceListResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list.metadata['url'], + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: - - request = build_list_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - resource_name=resource_name, - api_version=api_version, - template_url=next_link, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) @@ -267,16 +318,14 @@ def extract_data(pipeline_response): deserialized = self._deserialize("DigitalTwinsEndpointResourceListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -287,59 +336,61 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints"} # type: ignore + list.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints" + } @distributed_trace def get( - self, - resource_group_name: str, - resource_name: str, - endpoint_name: str, - **kwargs: Any - ) -> "_models.DigitalTwinsEndpointResource": + self, resource_group_name: str, resource_name: str, endpoint_name: str, **kwargs: Any + ) -> _models.DigitalTwinsEndpointResource: """Get DigitalTwinsInstances Endpoint. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param endpoint_name: Name of Endpoint Resource. + :param endpoint_name: Name of Endpoint Resource. Required. :type endpoint_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: DigitalTwinsEndpointResource, or the result of cls(response) + :return: DigitalTwinsEndpointResource or the result of cls(response) :rtype: ~azure.mgmt.digitaltwins.v2020_12_01.models.DigitalTwinsEndpointResource - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsEndpointResource"] 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', "2020-12-01") # type: str + api_version: Literal["2020-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) + cls: ClsType[_models.DigitalTwinsEndpointResource] = kwargs.pop("cls", None) - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, endpoint_name=endpoint_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -347,72 +398,172 @@ def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('DigitalTwinsEndpointResource', pipeline_response) + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}"} # type: ignore - + get.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}" + } def _create_or_update_initial( self, resource_group_name: str, resource_name: str, endpoint_name: str, - endpoint_description: "_models.DigitalTwinsEndpointResource", + endpoint_description: Union[_models.DigitalTwinsEndpointResource, IO], **kwargs: Any - ) -> "_models.DigitalTwinsEndpointResource": - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsEndpointResource"] + ) -> _models.DigitalTwinsEndpointResource: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2020-12-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(endpoint_description, 'DigitalTwinsEndpointResource') + api_version: Literal["2020-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DigitalTwinsEndpointResource] = kwargs.pop("cls", None) - request = build_create_or_update_request_initial( - subscription_id=self._config.subscription_id, + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(endpoint_description, (IO, bytes)): + _content = endpoint_description + else: + _json = self._serialize.body(endpoint_description, "DigitalTwinsEndpointResource") + + request = build_create_or_update_request( resource_group_name=resource_group_name, resource_name=resource_name, 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_initial.metadata['url'], + content=_content, + template_url=self._create_or_update_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('DigitalTwinsEndpointResource', pipeline_response) + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('DigitalTwinsEndpointResource', pipeline_response) + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized + return deserialized # type: ignore + + _create_or_update_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}" + } + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + endpoint_name: str, + endpoint_description: _models.DigitalTwinsEndpointResource, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.DigitalTwinsEndpointResource]: + """Create or update DigitalTwinsInstance endpoint. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param endpoint_name: Name of Endpoint Resource. Required. + :type endpoint_name: str + :param endpoint_description: The DigitalTwinsInstance endpoint metadata and security metadata. + Required. + :type endpoint_description: + ~azure.mgmt.digitaltwins.v2020_12_01.models.DigitalTwinsEndpointResource + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either DigitalTwinsEndpointResource or the + result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2020_12_01.models.DigitalTwinsEndpointResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ - _create_or_update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}"} # type: ignore + @overload + def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + endpoint_name: str, + endpoint_description: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.DigitalTwinsEndpointResource]: + """Create or update DigitalTwinsInstance endpoint. + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param endpoint_name: Name of Endpoint Resource. Required. + :type endpoint_name: str + :param endpoint_description: The DigitalTwinsInstance endpoint metadata and security metadata. + Required. + :type endpoint_description: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either DigitalTwinsEndpointResource or the + result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2020_12_01.models.DigitalTwinsEndpointResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace def begin_create_or_update( @@ -420,21 +571,25 @@ def begin_create_or_update( resource_group_name: str, resource_name: str, endpoint_name: str, - endpoint_description: "_models.DigitalTwinsEndpointResource", + endpoint_description: Union[_models.DigitalTwinsEndpointResource, IO], **kwargs: Any - ) -> LROPoller["_models.DigitalTwinsEndpointResource"]: + ) -> LROPoller[_models.DigitalTwinsEndpointResource]: """Create or update DigitalTwinsInstance endpoint. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param endpoint_name: Name of Endpoint Resource. + :param endpoint_name: Name of Endpoint Resource. Required. :type endpoint_name: str :param endpoint_description: The DigitalTwinsInstance endpoint metadata and security metadata. + Is either a model type or a IO type. Required. :type endpoint_description: - ~azure.mgmt.digitaltwins.v2020_12_01.models.DigitalTwinsEndpointResource + ~azure.mgmt.digitaltwins.v2020_12_01.models.DigitalTwinsEndpointResource or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this @@ -447,17 +602,17 @@ def begin_create_or_update( result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2020_12_01.models.DigitalTwinsEndpointResource] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2020-12-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsEndpointResource"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DigitalTwinsEndpointResource] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = self._create_or_update_initial( resource_group_name=resource_group_name, @@ -466,102 +621,107 @@ def begin_create_or_update( endpoint_description=endpoint_description, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('DigitalTwinsEndpointResource', pipeline_response) + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - begin_create_or_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}"} # type: ignore + begin_create_or_update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}" + } def _delete_initial( - self, - resource_group_name: str, - resource_name: str, - endpoint_name: str, - **kwargs: Any - ) -> Optional["_models.DigitalTwinsEndpointResource"]: - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.DigitalTwinsEndpointResource"]] + self, resource_group_name: str, resource_name: str, endpoint_name: str, **kwargs: Any + ) -> Optional[_models.DigitalTwinsEndpointResource]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2020-12-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - request = build_delete_request_initial( - subscription_id=self._config.subscription_id, + api_version: Literal["2020-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) + cls: ClsType[Optional[_models.DigitalTwinsEndpointResource]] = kwargs.pop("cls", None) + + request = build_delete_request( resource_group_name=resource_group_name, resource_name=resource_name, endpoint_name=endpoint_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._delete_initial.metadata['url'], + template_url=self._delete_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('DigitalTwinsEndpointResource', pipeline_response) + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) if response.status_code == 202: - deserialized = self._deserialize('DigitalTwinsEndpointResource', pipeline_response) + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _delete_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}"} # type: ignore - + _delete_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}" + } @distributed_trace def begin_delete( - self, - resource_group_name: str, - resource_name: str, - endpoint_name: str, - **kwargs: Any - ) -> LROPoller["_models.DigitalTwinsEndpointResource"]: + self, resource_group_name: str, resource_name: str, endpoint_name: str, **kwargs: Any + ) -> LROPoller[_models.DigitalTwinsEndpointResource]: """Delete a DigitalTwinsInstance endpoint. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param endpoint_name: Name of Endpoint Resource. + :param endpoint_name: Name of Endpoint Resource. Required. :type endpoint_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. @@ -575,45 +735,50 @@ def begin_delete( result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2020_12_01.models.DigitalTwinsEndpointResource] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2020-12-01") # type: str - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsEndpointResource"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) + cls: ClsType[_models.DigitalTwinsEndpointResource] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = self._delete_initial( resource_group_name=resource_group_name, resource_name=resource_name, endpoint_name=endpoint_name, api_version=api_version, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('DigitalTwinsEndpointResource', pipeline_response) + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - begin_delete.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}"} # type: ignore + begin_delete.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}" + } diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/operations/_digital_twins_operations.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/operations/_digital_twins_operations.py index f303a04195798..f1e48585b9b95 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/operations/_digital_twins_operations.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/operations/_digital_twins_operations.py @@ -6,361 +6,357 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Iterable, Optional, TypeVar, Union - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import sys +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models +from ..._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') -JSONType = Any + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_get_request( - subscription_id: str, - resource_group_name: str, - resource_name: str, - **kwargs: Any -) -> HttpRequest: - api_version = kwargs.pop('api_version', "2020-12-01") # type: str - accept = "application/json" +def build_get_request(resource_group_name: str, resource_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) + accept = _headers.pop("Accept", "application/json") + # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}", + ) # 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', max_length=90, min_length=1), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=63, min_length=3, pattern=r'^(?!-)[A-Za-z0-9-]{3,63}(? HttpRequest: - api_version = kwargs.pop('api_version', "2020-12-01") # type: str - content_type = kwargs.pop('content_type', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}", + ) # 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', max_length=90, min_length=1), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=63, min_length=3, pattern=r'^(?!-)[A-Za-z0-9-]{3,63}(? HttpRequest: - api_version = kwargs.pop('api_version', "2020-12-01") # type: str - content_type = kwargs.pop('content_type', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}", + ) # 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', max_length=90, min_length=1), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=63, min_length=3, pattern=r'^(?!-)[A-Za-z0-9-]{3,63}(? HttpRequest: - api_version = kwargs.pop('api_version', "2020-12-01") # type: str + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}", + ) # 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', max_length=90, min_length=1), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=63, min_length=3, pattern=r'^(?!-)[A-Za-z0-9-]{3,63}(? HttpRequest: - api_version = kwargs.pop('api_version', "2020-12-01") # type: str +def build_list_request(subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.DigitalTwins/digitalTwinsInstances") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.DigitalTwins/digitalTwinsInstances" + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters - _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - _query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - _header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="GET", - url=_url, - params=_query_parameters, - headers=_header_parameters, - **kwargs - ) - - -def build_list_by_resource_group_request( - subscription_id: str, - resource_group_name: str, - **kwargs: Any -) -> HttpRequest: - api_version = kwargs.pop('api_version', "2020-12-01") # type: str + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_by_resource_group_request(resource_group_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances", + ) # 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', max_length=90, min_length=1), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # 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_check_name_availability_request( - subscription_id: str, - location: str, - *, - json: JSONType = None, - content: Any = None, - **kwargs: Any -) -> HttpRequest: - api_version = kwargs.pop('api_version', "2020-12-01") # type: str - content_type = kwargs.pop('content_type', None) # type: Optional[str] + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_check_name_availability_request(location: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.DigitalTwins/locations/{location}/checkNameAvailability") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.DigitalTwins/locations/{location}/checkNameAvailability", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), - "location": _SERIALIZER.url("location", location, 'str', min_length=3), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "location": _SERIALIZER.url("location", location, "str", min_length=3), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters - _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - _query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] if content_type is not None: - _header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') - _header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="POST", - url=_url, - params=_query_parameters, - headers=_header_parameters, - json=json, - content=content, - **kwargs - ) - -class DigitalTwinsOperations(object): - """DigitalTwinsOperations 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.digitaltwins.v2020_12_01.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class DigitalTwinsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.digitaltwins.v2020_12_01.AzureDigitalTwinsManagementClient`'s + :attr:`digital_twins` 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, - resource_group_name: str, - resource_name: str, - **kwargs: Any - ) -> "_models.DigitalTwinsDescription": + def get(self, resource_group_name: str, resource_name: str, **kwargs: Any) -> _models.DigitalTwinsDescription: """Get DigitalTwinsInstances resource. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: DigitalTwinsDescription, or the result of cls(response) + :return: DigitalTwinsDescription or the result of cls(response) :rtype: ~azure.mgmt.digitaltwins.v2020_12_01.models.DigitalTwinsDescription - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescription"] 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', "2020-12-01") # type: str + api_version: Literal["2020-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) + cls: ClsType[_models.DigitalTwinsDescription] = kwargs.pop("cls", None) - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -368,90 +364,190 @@ def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}"} # type: ignore - + get.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } def _create_or_update_initial( self, resource_group_name: str, resource_name: str, - digital_twins_create: "_models.DigitalTwinsDescription", + digital_twins_create: Union[_models.DigitalTwinsDescription, IO], **kwargs: Any - ) -> "_models.DigitalTwinsDescription": - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescription"] + ) -> _models.DigitalTwinsDescription: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2020-12-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(digital_twins_create, 'DigitalTwinsDescription') + api_version: Literal["2020-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DigitalTwinsDescription] = kwargs.pop("cls", None) - request = build_create_or_update_request_initial( - subscription_id=self._config.subscription_id, + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(digital_twins_create, (IO, bytes)): + _content = digital_twins_create + else: + _json = self._serialize.body(digital_twins_create, "DigitalTwinsDescription") + + request = build_create_or_update_request( resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._create_or_update_initial.metadata['url'], + content=_content, + template_url=self._create_or_update_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized + return deserialized # type: ignore - _create_or_update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}"} # type: ignore + _create_or_update_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } + @overload + def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + digital_twins_create: _models.DigitalTwinsDescription, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.DigitalTwinsDescription]: + """Create or update the metadata of a DigitalTwinsInstance. The usual pattern to modify a property + is to retrieve the DigitalTwinsInstance and security metadata, and then combine them with the + modified values in a new body to update the DigitalTwinsInstance. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param digital_twins_create: The DigitalTwinsInstance and security metadata. Required. + :type digital_twins_create: ~azure.mgmt.digitaltwins.v2020_12_01.models.DigitalTwinsDescription + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either DigitalTwinsDescription or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2020_12_01.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + digital_twins_create: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.DigitalTwinsDescription]: + """Create or update the metadata of a DigitalTwinsInstance. The usual pattern to modify a property + is to retrieve the DigitalTwinsInstance and security metadata, and then combine them with the + modified values in a new body to update the DigitalTwinsInstance. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param digital_twins_create: The DigitalTwinsInstance and security metadata. Required. + :type digital_twins_create: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either DigitalTwinsDescription or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2020_12_01.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace def begin_create_or_update( self, resource_group_name: str, resource_name: str, - digital_twins_create: "_models.DigitalTwinsDescription", + digital_twins_create: Union[_models.DigitalTwinsDescription, IO], **kwargs: Any - ) -> LROPoller["_models.DigitalTwinsDescription"]: + ) -> LROPoller[_models.DigitalTwinsDescription]: """Create or update the metadata of a DigitalTwinsInstance. The usual pattern to modify a property is to retrieve the DigitalTwinsInstance and security metadata, and then combine them with the modified values in a new body to update the DigitalTwinsInstance. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param digital_twins_create: The DigitalTwinsInstance and security metadata. + :param digital_twins_create: The DigitalTwinsInstance and security metadata. Is either a model + type or a IO type. Required. :type digital_twins_create: ~azure.mgmt.digitaltwins.v2020_12_01.models.DigitalTwinsDescription + or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this @@ -464,17 +560,17 @@ def begin_create_or_update( cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2020_12_01.models.DigitalTwinsDescription] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2020-12-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescription"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DigitalTwinsDescription] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = self._create_or_update_initial( resource_group_name=resource_group_name, @@ -482,106 +578,133 @@ def begin_create_or_update( digital_twins_create=digital_twins_create, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - begin_create_or_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}"} # type: ignore + begin_create_or_update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } def _update_initial( self, resource_group_name: str, resource_name: str, - digital_twins_patch_description: "_models.DigitalTwinsPatchDescription", + digital_twins_patch_description: Union[_models.DigitalTwinsPatchDescription, IO], **kwargs: Any - ) -> "_models.DigitalTwinsDescription": - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescription"] + ) -> _models.DigitalTwinsDescription: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2020-12-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(digital_twins_patch_description, 'DigitalTwinsPatchDescription') + api_version: Literal["2020-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DigitalTwinsDescription] = kwargs.pop("cls", None) - request = build_update_request_initial( - subscription_id=self._config.subscription_id, + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(digital_twins_patch_description, (IO, bytes)): + _content = digital_twins_patch_description + else: + _json = self._serialize.body(digital_twins_patch_description, "DigitalTwinsPatchDescription") + + request = build_update_request( resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._update_initial.metadata['url'], + content=_content, + template_url=self._update_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if response.status_code == 202: - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - _update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}"} # type: ignore + return deserialized # type: ignore + _update_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } - @distributed_trace + @overload def begin_update( self, resource_group_name: str, resource_name: str, - digital_twins_patch_description: "_models.DigitalTwinsPatchDescription", + digital_twins_patch_description: _models.DigitalTwinsPatchDescription, + *, + content_type: str = "application/json", **kwargs: Any - ) -> LROPoller["_models.DigitalTwinsDescription"]: + ) -> LROPoller[_models.DigitalTwinsDescription]: """Update metadata of DigitalTwinsInstance. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str :param digital_twins_patch_description: The DigitalTwinsInstance and security metadata. + Required. :type digital_twins_patch_description: ~azure.mgmt.digitaltwins.v2020_12_01.models.DigitalTwinsPatchDescription + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this @@ -594,17 +717,92 @@ def begin_update( cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2020_12_01.models.DigitalTwinsDescription] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2020-12-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescription"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + + @overload + def begin_update( + self, + resource_group_name: str, + resource_name: str, + digital_twins_patch_description: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.DigitalTwinsDescription]: + """Update metadata of DigitalTwinsInstance. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param digital_twins_patch_description: The DigitalTwinsInstance and security metadata. + Required. + :type digital_twins_patch_description: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either DigitalTwinsDescription or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2020_12_01.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_update( + self, + resource_group_name: str, + resource_name: str, + digital_twins_patch_description: Union[_models.DigitalTwinsPatchDescription, IO], + **kwargs: Any + ) -> LROPoller[_models.DigitalTwinsDescription]: + """Update metadata of DigitalTwinsInstance. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param digital_twins_patch_description: The DigitalTwinsInstance and security metadata. Is + either a model type or a IO type. Required. + :type digital_twins_patch_description: + ~azure.mgmt.digitaltwins.v2020_12_01.models.DigitalTwinsPatchDescription or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either DigitalTwinsDescription or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2020_12_01.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DigitalTwinsDescription] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = self._update_initial( resource_group_name=resource_group_name, @@ -612,97 +810,104 @@ def begin_update( digital_twins_patch_description=digital_twins_patch_description, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - begin_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}"} # type: ignore + begin_update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } def _delete_initial( - self, - resource_group_name: str, - resource_name: str, - **kwargs: Any - ) -> Optional["_models.DigitalTwinsDescription"]: - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.DigitalTwinsDescription"]] + self, resource_group_name: str, resource_name: str, **kwargs: Any + ) -> Optional[_models.DigitalTwinsDescription]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2020-12-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - request = build_delete_request_initial( - subscription_id=self._config.subscription_id, + api_version: Literal["2020-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) + cls: ClsType[Optional[_models.DigitalTwinsDescription]] = kwargs.pop("cls", None) + + request = build_delete_request( resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._delete_initial.metadata['url'], + template_url=self._delete_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if response.status_code == 202: - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _delete_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}"} # type: ignore - + _delete_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } @distributed_trace def begin_delete( - self, - resource_group_name: str, - resource_name: str, - **kwargs: Any - ) -> LROPoller["_models.DigitalTwinsDescription"]: + self, resource_group_name: str, resource_name: str, **kwargs: Any + ) -> LROPoller[_models.DigitalTwinsDescription]: """Delete a DigitalTwinsInstance. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. @@ -716,86 +921,103 @@ def begin_delete( cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2020_12_01.models.DigitalTwinsDescription] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2020-12-01") # type: str - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescription"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) + cls: ClsType[_models.DigitalTwinsDescription] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = self._delete_initial( resource_group_name=resource_group_name, resource_name=resource_name, api_version=api_version, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - begin_delete.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}"} # type: ignore + begin_delete.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } @distributed_trace - def list( - self, - **kwargs: Any - ) -> Iterable["_models.DigitalTwinsDescriptionListResult"]: + def list(self, **kwargs: Any) -> Iterable["_models.DigitalTwinsDescription"]: """Get all the DigitalTwinsInstances in a subscription. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either DigitalTwinsDescriptionListResult or the result of + :return: An iterator like instance of either DigitalTwinsDescription or the result of cls(response) :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.digitaltwins.v2020_12_01.models.DigitalTwinsDescriptionListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.paging.ItemPaged[~azure.mgmt.digitaltwins.v2020_12_01.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2020-12-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) + cls: ClsType[_models.DigitalTwinsDescriptionListResult] = kwargs.pop("cls", None) - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescriptionListResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list.metadata['url'], + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: - - request = build_list_request( - subscription_id=self._config.subscription_id, - api_version=api_version, - template_url=next_link, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) @@ -806,16 +1028,14 @@ def extract_data(pipeline_response): deserialized = self._deserialize("DigitalTwinsDescriptionListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -826,56 +1046,66 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.DigitalTwins/digitalTwinsInstances"} # type: ignore + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.DigitalTwins/digitalTwinsInstances"} @distributed_trace def list_by_resource_group( - self, - resource_group_name: str, - **kwargs: Any - ) -> Iterable["_models.DigitalTwinsDescriptionListResult"]: + self, resource_group_name: str, **kwargs: Any + ) -> Iterable["_models.DigitalTwinsDescription"]: """Get all the DigitalTwinsInstances in a resource group. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. 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 DigitalTwinsDescriptionListResult or the result of + :return: An iterator like instance of either DigitalTwinsDescription or the result of cls(response) :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.digitaltwins.v2020_12_01.models.DigitalTwinsDescriptionListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.paging.ItemPaged[~azure.mgmt.digitaltwins.v2020_12_01.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2020-12-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) + cls: ClsType[_models.DigitalTwinsDescriptionListResult] = kwargs.pop("cls", None) - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescriptionListResult"] 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( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata['url'], + template_url=self.list_by_resource_group.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: - - request = build_list_by_resource_group_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - api_version=api_version, - template_url=next_link, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) @@ -886,16 +1116,14 @@ def extract_data(pipeline_response): deserialized = self._deserialize("DigitalTwinsDescriptionListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -906,59 +1134,127 @@ 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.DigitalTwins/digitalTwinsInstances"} # type: ignore + list_by_resource_group.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances" + } - @distributed_trace + @overload def check_name_availability( self, location: str, - digital_twins_instance_check_name: "_models.CheckNameRequest", + digital_twins_instance_check_name: _models.CheckNameRequest, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.CheckNameResult": + ) -> _models.CheckNameResult: """Check if a DigitalTwinsInstance name is available. - :param location: Location of DigitalTwinsInstance. + :param location: Location of DigitalTwinsInstance. Required. :type location: str :param digital_twins_instance_check_name: Set the name parameter in the DigitalTwinsInstanceCheckName structure to the name of the DigitalTwinsInstance to check. + Required. :type digital_twins_instance_check_name: ~azure.mgmt.digitaltwins.v2020_12_01.models.CheckNameRequest + :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: CheckNameResult or the result of cls(response) + :rtype: ~azure.mgmt.digitaltwins.v2020_12_01.models.CheckNameResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def check_name_availability( + self, + location: str, + digital_twins_instance_check_name: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.CheckNameResult: + """Check if a DigitalTwinsInstance name is available. + + :param location: Location of DigitalTwinsInstance. Required. + :type location: str + :param digital_twins_instance_check_name: Set the name parameter in the + DigitalTwinsInstanceCheckName structure to the name of the DigitalTwinsInstance to check. + Required. + :type digital_twins_instance_check_name: 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: CheckNameResult, or the result of cls(response) + :return: CheckNameResult or the result of cls(response) :rtype: ~azure.mgmt.digitaltwins.v2020_12_01.models.CheckNameResult - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def check_name_availability( + self, location: str, digital_twins_instance_check_name: Union[_models.CheckNameRequest, IO], **kwargs: Any + ) -> _models.CheckNameResult: + """Check if a DigitalTwinsInstance name is available. + + :param location: Location of DigitalTwinsInstance. Required. + :type location: str + :param digital_twins_instance_check_name: Set the name parameter in the + DigitalTwinsInstanceCheckName structure to the name of the DigitalTwinsInstance to check. Is + either a model type or a IO type. Required. + :type digital_twins_instance_check_name: + ~azure.mgmt.digitaltwins.v2020_12_01.models.CheckNameRequest 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: CheckNameResult or the result of cls(response) + :rtype: ~azure.mgmt.digitaltwins.v2020_12_01.models.CheckNameResult + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.CheckNameResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', "2020-12-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + api_version: Literal["2020-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.CheckNameResult] = kwargs.pop("cls", None) - _json = self._serialize.body(digital_twins_instance_check_name, 'CheckNameRequest') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(digital_twins_instance_check_name, (IO, bytes)): + _content = digital_twins_instance_check_name + else: + _json = self._serialize.body(digital_twins_instance_check_name, "CheckNameRequest") request = build_check_name_availability_request( - subscription_id=self._config.subscription_id, location=location, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self.check_name_availability.metadata['url'], + content=_content, + template_url=self.check_name_availability.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -966,12 +1262,13 @@ def check_name_availability( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('CheckNameResult', pipeline_response) + deserialized = self._deserialize("CheckNameResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - check_name_availability.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.DigitalTwins/locations/{location}/checkNameAvailability"} # type: ignore - + check_name_availability.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.DigitalTwins/locations/{location}/checkNameAvailability" + } diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/operations/_operations.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/operations/_operations.py index d7601b8ef81b5..8f5ef452c37b1 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/operations/_operations.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/operations/_operations.py @@ -6,108 +6,126 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, Callable, Dict, Iterable, Optional, TypeVar - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from ..._serialization import Serializer from .._vendor import _convert_request -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_list_request( - **kwargs: Any -) -> HttpRequest: - api_version = kwargs.pop('api_version', "2020-12-01") # type: str - accept = "application/json" +def build_list_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) + accept = _headers.pop("Accept", "application/json") + # Construct URL _url = kwargs.pop("template_url", "/providers/Microsoft.DigitalTwins/operations") # Construct parameters - _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - _query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - _header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="GET", - url=_url, - params=_query_parameters, - headers=_header_parameters, - **kwargs - ) - -class Operations(object): - """Operations operations. - - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. - - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.digitaltwins.v2020_12_01.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class Operations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.digitaltwins.v2020_12_01.AzureDigitalTwinsManagementClient`'s + :attr:`operations` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace - def list( - self, - **kwargs: Any - ) -> Iterable["_models.OperationListResult"]: + def list(self, **kwargs: Any) -> Iterable["_models.Operation"]: """Lists all of the available DigitalTwins service REST API operations. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either OperationListResult or the result of cls(response) - :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.digitaltwins.v2020_12_01.models.OperationListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Operation or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.digitaltwins.v2020_12_01.models.Operation] + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2020-12-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) + cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) - cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationListResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( api_version=api_version, - template_url=self.list.metadata['url'], + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: - - request = build_list_request( - api_version=api_version, - template_url=next_link, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) @@ -118,16 +136,14 @@ def extract_data(pipeline_response): deserialized = self._deserialize("OperationListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -138,8 +154,6 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/providers/Microsoft.DigitalTwins/operations"} # type: ignore + list.metadata = {"url": "/providers/Microsoft.DigitalTwins/operations"} diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/operations/_patch.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/operations/_patch.py new file mode 100644 index 0000000000000..f7dd32510333d --- /dev/null +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/operations/_private_endpoint_connections_operations.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/operations/_private_endpoint_connections_operations.py index b6647555bd013..8e7f1371de337 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/operations/_private_endpoint_connections_operations.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/operations/_private_endpoint_connections_operations.py @@ -6,250 +6,290 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Optional, TypeVar, Union - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import sys +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, cast, 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.polling import LROPoller, NoPolling, PollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models +from ..._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') -JSONType = Any + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False + def build_list_request( - subscription_id: str, - resource_group_name: str, - resource_name: str, - **kwargs: Any + resource_group_name: str, resource_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = kwargs.pop('api_version', "2020-12-01") # type: str + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=63, min_length=3, pattern=r'^(?!-)[A-Za-z0-9-]{3,63}(? HttpRequest: - api_version = kwargs.pop('api_version', "2020-12-01") # type: str + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=63, min_length=3, pattern=r'^(?!-)[A-Za-z0-9-]{3,63}(? HttpRequest: - api_version = kwargs.pop('api_version', "2020-12-01") # type: str + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=63, min_length=3, pattern=r'^(?!-)[A-Za-z0-9-]{3,63}(? HttpRequest: - api_version = kwargs.pop('api_version', "2020-12-01") # type: str - content_type = kwargs.pop('content_type', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=63, min_length=3, pattern=r'^(?!-)[A-Za-z0-9-]{3,63}(? "_models.PrivateEndpointConnectionsResponse": + self, resource_group_name: str, resource_name: str, **kwargs: Any + ) -> _models.PrivateEndpointConnectionsResponse: """List private endpoint connection properties. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: PrivateEndpointConnectionsResponse, or the result of cls(response) + :return: PrivateEndpointConnectionsResponse or the result of cls(response) :rtype: ~azure.mgmt.digitaltwins.v2020_12_01.models.PrivateEndpointConnectionsResponse - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnectionsResponse"] 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', "2020-12-01") # type: str + api_version: Literal["2020-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) + cls: ClsType[_models.PrivateEndpointConnectionsResponse] = kwargs.pop("cls", None) - request = build_list_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list.metadata['url'], + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -257,63 +297,66 @@ def list( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('PrivateEndpointConnectionsResponse', pipeline_response) + deserialized = self._deserialize("PrivateEndpointConnectionsResponse", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - list.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections"} # type: ignore - + list.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections" + } @distributed_trace def get( - self, - resource_group_name: str, - resource_name: str, - private_endpoint_connection_name: str, - **kwargs: Any - ) -> "_models.PrivateEndpointConnection": + self, resource_group_name: str, resource_name: str, private_endpoint_connection_name: str, **kwargs: Any + ) -> _models.PrivateEndpointConnection: """Get private endpoint connection properties for the given private endpoint. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param private_endpoint_connection_name: The name of the private endpoint connection. + :param private_endpoint_connection_name: The name of the private endpoint connection. Required. :type private_endpoint_connection_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: PrivateEndpointConnection, or the result of cls(response) + :return: PrivateEndpointConnection or the result of cls(response) :rtype: ~azure.mgmt.digitaltwins.v2020_12_01.models.PrivateEndpointConnection - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnection"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', "2020-12-01") # type: str + api_version: Literal["2020-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) + cls: ClsType[_models.PrivateEndpointConnection] = kwargs.pop("cls", None) - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, private_endpoint_connection_name=private_endpoint_connection_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -321,76 +364,77 @@ def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore - + get.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}" + } def _delete_initial( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - resource_name: str, - private_endpoint_connection_name: str, - **kwargs: Any + self, resource_group_name: str, resource_name: str, private_endpoint_connection_name: str, **kwargs: Any ) -> None: - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2020-12-01") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - request = build_delete_request_initial( - subscription_id=self._config.subscription_id, + api_version: Literal["2020-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + + request = build_delete_request( resource_group_name=resource_group_name, resource_name=resource_name, private_endpoint_connection_name=private_endpoint_connection_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._delete_initial.metadata['url'], + template_url=self._delete_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - _delete_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore - + _delete_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}" + } @distributed_trace - def begin_delete( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - resource_name: str, - private_endpoint_connection_name: str, - **kwargs: Any + def begin_delete( + self, resource_group_name: str, resource_name: str, private_endpoint_connection_name: str, **kwargs: Any ) -> LROPoller[None]: """Delete private endpoint connection with the specified name. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param private_endpoint_connection_name: The name of the private endpoint connection. + :param private_endpoint_connection_name: The name of the private endpoint connection. Required. :type private_endpoint_connection_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. @@ -402,124 +446,152 @@ def begin_delete( # pylint: disable=inconsistent-return-statements Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2020-12-01") # type: str - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType[None] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: - raw_result = self._delete_initial( + raw_result = self._delete_initial( # type: ignore resource_group_name=resource_group_name, resource_name=resource_name, private_endpoint_connection_name=private_endpoint_connection_name, api_version=api_version, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - - if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - begin_delete.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore + begin_delete.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}" + } def _create_or_update_initial( self, resource_group_name: str, resource_name: str, private_endpoint_connection_name: str, - private_endpoint_connection: "_models.PrivateEndpointConnection", + private_endpoint_connection: Union[_models.PrivateEndpointConnection, IO], **kwargs: Any - ) -> "_models.PrivateEndpointConnection": - cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnection"] + ) -> _models.PrivateEndpointConnection: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2020-12-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(private_endpoint_connection, 'PrivateEndpointConnection') + api_version: Literal["2020-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PrivateEndpointConnection] = kwargs.pop("cls", None) - request = build_create_or_update_request_initial( - subscription_id=self._config.subscription_id, + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(private_endpoint_connection, (IO, bytes)): + _content = private_endpoint_connection + else: + _json = self._serialize.body(private_endpoint_connection, "PrivateEndpointConnection") + + request = build_create_or_update_request( resource_group_name=resource_group_name, resource_name=resource_name, private_endpoint_connection_name=private_endpoint_connection_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._create_or_update_initial.metadata['url'], + content=_content, + template_url=self._create_or_update_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) if response.status_code == 202: - deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - _create_or_update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore + return deserialized # type: ignore + _create_or_update_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}" + } - @distributed_trace + @overload def begin_create_or_update( self, resource_group_name: str, resource_name: str, private_endpoint_connection_name: str, - private_endpoint_connection: "_models.PrivateEndpointConnection", + private_endpoint_connection: _models.PrivateEndpointConnection, + *, + content_type: str = "application/json", **kwargs: Any - ) -> LROPoller["_models.PrivateEndpointConnection"]: + ) -> LROPoller[_models.PrivateEndpointConnection]: """Update the status of a private endpoint connection with the given name. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param private_endpoint_connection_name: The name of the private endpoint connection. + :param private_endpoint_connection_name: The name of the private endpoint connection. Required. :type private_endpoint_connection_name: str :param private_endpoint_connection: The private endpoint connection with updated properties. + Required. :type private_endpoint_connection: ~azure.mgmt.digitaltwins.v2020_12_01.models.PrivateEndpointConnection + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this @@ -532,17 +604,98 @@ def begin_create_or_update( of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2020_12_01.models.PrivateEndpointConnection] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2020-12-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnection"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + private_endpoint_connection_name: str, + private_endpoint_connection: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.PrivateEndpointConnection]: + """Update the status of a private endpoint connection with the given name. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param private_endpoint_connection_name: The name of the private endpoint connection. Required. + :type private_endpoint_connection_name: str + :param private_endpoint_connection: The private endpoint connection with updated properties. + Required. + :type private_endpoint_connection: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either PrivateEndpointConnection or the result + of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2020_12_01.models.PrivateEndpointConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + private_endpoint_connection_name: str, + private_endpoint_connection: Union[_models.PrivateEndpointConnection, IO], + **kwargs: Any + ) -> LROPoller[_models.PrivateEndpointConnection]: + """Update the status of a private endpoint connection with the given name. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param private_endpoint_connection_name: The name of the private endpoint connection. Required. + :type private_endpoint_connection_name: str + :param private_endpoint_connection: The private endpoint connection with updated properties. Is + either a model type or a IO type. Required. + :type private_endpoint_connection: + ~azure.mgmt.digitaltwins.v2020_12_01.models.PrivateEndpointConnection or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either PrivateEndpointConnection or the result + of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2020_12_01.models.PrivateEndpointConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PrivateEndpointConnection] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = self._create_or_update_initial( resource_group_name=resource_group_name, @@ -551,29 +704,34 @@ def begin_create_or_update( private_endpoint_connection=private_endpoint_connection, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - begin_create_or_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore + begin_create_or_update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}" + } diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/operations/_private_link_resources_operations.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/operations/_private_link_resources_operations.py index b31f872b34eb1..a499c0939a6ff 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/operations/_private_link_resources_operations.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2020_12_01/operations/_private_link_resources_operations.py @@ -6,163 +6,183 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, Callable, Dict, Optional, TypeVar -from msrest import Serializer - -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 HttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from ..._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False + def build_list_request( - subscription_id: str, - resource_group_name: str, - resource_name: str, - **kwargs: Any + resource_group_name: str, resource_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = kwargs.pop('api_version', "2020-12-01") # type: str + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateLinkResources") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateLinkResources", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=63, min_length=3, pattern=r'^(?!-)[A-Za-z0-9-]{3,63}(? HttpRequest: - api_version = kwargs.pop('api_version', "2020-12-01") # type: str + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2020-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateLinkResources/{resourceId}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateLinkResources/{resourceId}", + ) # 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', max_length=90, min_length=1), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=63, min_length=3, pattern=r'^(?!-)[A-Za-z0-9-]{3,63}(? "_models.GroupIdInformationResponse": + def list(self, resource_group_name: str, resource_name: str, **kwargs: Any) -> _models.GroupIdInformationResponse: """List private link resources for given Digital Twin. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: GroupIdInformationResponse, or the result of cls(response) + :return: GroupIdInformationResponse or the result of cls(response) :rtype: ~azure.mgmt.digitaltwins.v2020_12_01.models.GroupIdInformationResponse - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.GroupIdInformationResponse"] 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', "2020-12-01") # type: str + api_version: Literal["2020-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) + cls: ClsType[_models.GroupIdInformationResponse] = kwargs.pop("cls", None) - request = build_list_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list.metadata['url'], + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -170,63 +190,66 @@ def list( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('GroupIdInformationResponse', pipeline_response) + deserialized = self._deserialize("GroupIdInformationResponse", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - list.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateLinkResources"} # type: ignore - + list.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateLinkResources" + } @distributed_trace def get( - self, - resource_group_name: str, - resource_name: str, - resource_id: str, - **kwargs: Any - ) -> "_models.GroupIdInformation": + self, resource_group_name: str, resource_name: str, resource_id: str, **kwargs: Any + ) -> _models.GroupIdInformation: """Get the specified private link resource for the given Digital Twin. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param resource_id: The name of the private link resource. + :param resource_id: The name of the private link resource. Required. :type resource_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: GroupIdInformation, or the result of cls(response) + :return: GroupIdInformation or the result of cls(response) :rtype: ~azure.mgmt.digitaltwins.v2020_12_01.models.GroupIdInformation - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.GroupIdInformation"] 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', "2020-12-01") # type: str + api_version: Literal["2020-12-01"] = kwargs.pop("api_version", _params.pop("api-version", "2020-12-01")) + cls: ClsType[_models.GroupIdInformation] = kwargs.pop("cls", None) - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, resource_id=resource_id, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -234,12 +257,13 @@ def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('GroupIdInformation', pipeline_response) + deserialized = self._deserialize("GroupIdInformation", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateLinkResources/{resourceId}"} # type: ignore - + get.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateLinkResources/{resourceId}" + } diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/__init__.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/__init__.py index 36b558a96cdfd..3d416a868dd25 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/__init__.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/__init__.py @@ -10,9 +10,17 @@ from ._version import VERSION __version__ = VERSION -__all__ = ['AzureDigitalTwinsManagementClient'] -# `._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 * # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "AzureDigitalTwinsManagementClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/_azure_digital_twins_management_client.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/_azure_digital_twins_management_client.py index 8b64ea7aa5aaa..e750c96db3dd8 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/_azure_digital_twins_management_client.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/_azure_digital_twins_management_client.py @@ -9,20 +9,27 @@ from copy import deepcopy from typing import Any, TYPE_CHECKING -from msrest import Deserializer, Serializer - from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient -from . import models +from . import models as _models +from .._serialization import Deserializer, Serializer from ._configuration import AzureDigitalTwinsManagementClientConfiguration -from .operations import DigitalTwinsEndpointOperations, DigitalTwinsOperations, Operations, PrivateEndpointConnectionsOperations, PrivateLinkResourcesOperations, TimeSeriesDatabaseConnectionsOperations +from .operations import ( + DigitalTwinsEndpointOperations, + DigitalTwinsOperations, + Operations, + PrivateEndpointConnectionsOperations, + PrivateLinkResourcesOperations, + TimeSeriesDatabaseConnectionsOperations, +) if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class AzureDigitalTwinsManagementClient: + +class AzureDigitalTwinsManagementClient: # pylint: disable=client-accepts-api-version-keyword """Azure Digital Twins Client for managing DigitalTwinsInstance. :ivar digital_twins: DigitalTwinsOperations operations @@ -42,9 +49,9 @@ class AzureDigitalTwinsManagementClient: :ivar time_series_database_connections: TimeSeriesDatabaseConnectionsOperations operations :vartype time_series_database_connections: azure.mgmt.digitaltwins.v2021_06_30_preview.operations.TimeSeriesDatabaseConnectionsOperations - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: The subscription identifier. + :param subscription_id: The subscription identifier. Required. :type subscription_id: str :param base_url: Service URL. Default value is "https://management.azure.com". :type base_url: str @@ -62,26 +69,31 @@ def __init__( base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: - self._config = AzureDigitalTwinsManagementClientConfiguration(credential=credential, subscription_id=subscription_id, **kwargs) + self._config = AzureDigitalTwinsManagementClientConfiguration( + credential=credential, subscription_id=subscription_id, **kwargs + ) self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) - client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) self._deserialize = Deserializer(client_models) self._serialize.client_side_validation = False self.digital_twins = DigitalTwinsOperations(self._client, self._config, self._serialize, self._deserialize) - self.digital_twins_endpoint = DigitalTwinsEndpointOperations(self._client, self._config, self._serialize, self._deserialize) + self.digital_twins_endpoint = DigitalTwinsEndpointOperations( + self._client, self._config, self._serialize, self._deserialize + ) self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) - self.private_link_resources = PrivateLinkResourcesOperations(self._client, self._config, self._serialize, self._deserialize) - self.private_endpoint_connections = PrivateEndpointConnectionsOperations(self._client, self._config, self._serialize, self._deserialize) - self.time_series_database_connections = TimeSeriesDatabaseConnectionsOperations(self._client, self._config, self._serialize, self._deserialize) - - - def _send_request( - self, - request: HttpRequest, - **kwargs: Any - ) -> HttpResponse: + self.private_link_resources = PrivateLinkResourcesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.private_endpoint_connections = PrivateEndpointConnectionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.time_series_database_connections = TimeSeriesDatabaseConnectionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + + def _send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: """Runs the network request through the client's chained policies. >>> from azure.core.rest import HttpRequest @@ -90,7 +102,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 @@ -103,15 +115,12 @@ def _send_request( request_copy.url = self._client.format_url(request_copy.url) return self._client.send_request(request_copy, **kwargs) - def close(self): - # type: () -> None + def close(self) -> None: self._client.close() - def __enter__(self): - # type: () -> AzureDigitalTwinsManagementClient + def __enter__(self) -> "AzureDigitalTwinsManagementClient": self._client.__enter__() return self - def __exit__(self, *exc_details): - # type: (Any) -> None + def __exit__(self, *exc_details) -> None: self._client.__exit__(*exc_details) diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/_configuration.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/_configuration.py index d2aa27d221a09..81964d7b507f2 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/_configuration.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/_configuration.py @@ -6,6 +6,7 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, TYPE_CHECKING from azure.core.configuration import Configuration @@ -14,6 +15,11 @@ from ._version import VERSION +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports + if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential @@ -25,23 +31,18 @@ class AzureDigitalTwinsManagementClientConfiguration(Configuration): # pylint: Note that all parameters used to create this instance are saved as instance attributes. - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: The subscription identifier. + :param subscription_id: The subscription identifier. Required. :type subscription_id: str :keyword api_version: Api Version. Default value is "2021-06-30-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(AzureDigitalTwinsManagementClientConfiguration, self).__init__(**kwargs) - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str + api_version: Literal["2021-06-30-preview"] = kwargs.pop("api_version", "2021-06-30-preview") if credential is None: raise ValueError("Parameter 'credential' must not be None.") @@ -51,23 +52,21 @@ def __init__( self.credential = credential self.subscription_id = subscription_id self.api_version = api_version - self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'mgmt-digitaltwins/{}'.format(VERSION)) + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-digitaltwins/{}".format(VERSION)) self._configure(**kwargs) - def _configure( - self, - **kwargs # type: Any - ): - # type: (...) -> None - self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get('retry_policy') or policies.RetryPolicy(**kwargs) - self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get('redirect_policy') or policies.RedirectPolicy(**kwargs) - self.authentication_policy = kwargs.get('authentication_policy') + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: - self.authentication_policy = ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs) + self.authentication_policy = ARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/_metadata.json b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/_metadata.json index 2ef60cb428871..6ec803aad75b8 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/_metadata.json +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/_metadata.json @@ -10,20 +10,20 @@ "azure_arm": true, "has_lro_operations": true, "client_side_validation": false, - "sync_imports": "{\"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}, \"regular\": {\"azurecore\": {\"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"], \"azure.mgmt.core\": [\"ARMPipelineClient\"]}, \"local\": {\"._configuration\": [\"AzureDigitalTwinsManagementClientConfiguration\"]}, \"thirdparty\": {\"msrest\": [\"Deserializer\", \"Serializer\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}}", - "async_imports": "{\"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"], \"azure.core.credentials\": [\"TokenCredential\"]}}, \"regular\": {\"azurecore\": {\"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"], \"azure.mgmt.core\": [\"AsyncARMPipelineClient\"]}, \"local\": {\"._configuration\": [\"AzureDigitalTwinsManagementClientConfiguration\"]}, \"thirdparty\": {\"msrest\": [\"Deserializer\", \"Serializer\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}}" + "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"AzureDigitalTwinsManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"AzureDigitalTwinsManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "global_parameters": { "sync": { "credential": { - "signature": "credential, # type: \"TokenCredential\"", - "description": "Credential needed for the client to connect to Azure.", + "signature": "credential: \"TokenCredential\",", + "description": "Credential needed for the client to connect to Azure. Required.", "docstring_type": "~azure.core.credentials.TokenCredential", "required": true }, "subscription_id": { - "signature": "subscription_id, # type: str", - "description": "The subscription identifier.", + "signature": "subscription_id: str,", + "description": "The subscription identifier. Required.", "docstring_type": "str", "required": true } @@ -31,13 +31,13 @@ "async": { "credential": { "signature": "credential: \"AsyncTokenCredential\",", - "description": "Credential needed for the client to connect to Azure.", + "description": "Credential needed for the client to connect to Azure. Required.", "docstring_type": "~azure.core.credentials_async.AsyncTokenCredential", "required": true }, "subscription_id": { "signature": "subscription_id: str,", - "description": "The subscription identifier.", + "description": "The subscription identifier. Required.", "docstring_type": "str", "required": true } @@ -48,19 +48,19 @@ "service_client_specific": { "sync": { "api_version": { - "signature": "api_version=None, # type: Optional[str]", + "signature": "api_version: Optional[str]=None,", "description": "API version to use if no profile is provided, or if missing in profile.", "docstring_type": "str", "required": false }, "base_url": { - "signature": "base_url=\"https://management.azure.com\", # type: str", + "signature": "base_url: str = \"https://management.azure.com\",", "description": "Service URL", "docstring_type": "str", "required": false }, "profile": { - "signature": "profile=KnownProfiles.default, # type: KnownProfiles", + "signature": "profile: KnownProfiles=KnownProfiles.default,", "description": "A profile definition, from KnownProfiles to dict.", "docstring_type": "azure.profiles.KnownProfiles", "required": false @@ -104,4 +104,4 @@ "private_endpoint_connections": "PrivateEndpointConnectionsOperations", "time_series_database_connections": "TimeSeriesDatabaseConnectionsOperations" } -} \ No newline at end of file +} diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/_patch.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/_patch.py index 74e48ecd07cf3..f99e77fef9861 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/_patch.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/_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/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/_vendor.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/_vendor.py index 138f663c53a4e..9aad73fc743e7 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/_vendor.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/_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/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/_version.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/_version.py index a55d01326aa81..e5754a47ce68f 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/_version.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "6.2.0" +VERSION = "1.0.0b1" diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/aio/__init__.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/aio/__init__.py index 20a6435cbbdb2..e4da5a5dc30c1 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/aio/__init__.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/aio/__init__.py @@ -7,9 +7,17 @@ # -------------------------------------------------------------------------- from ._azure_digital_twins_management_client import AzureDigitalTwinsManagementClient -__all__ = ['AzureDigitalTwinsManagementClient'] -# `._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 * # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "AzureDigitalTwinsManagementClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/aio/_azure_digital_twins_management_client.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/aio/_azure_digital_twins_management_client.py index 72ef9703734e1..f4fd00513f2fd 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/aio/_azure_digital_twins_management_client.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/aio/_azure_digital_twins_management_client.py @@ -9,20 +9,27 @@ from copy import deepcopy from typing import Any, Awaitable, TYPE_CHECKING -from msrest import Deserializer, Serializer - from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient -from .. import models +from .. import models as _models +from ..._serialization import Deserializer, Serializer from ._configuration import AzureDigitalTwinsManagementClientConfiguration -from .operations import DigitalTwinsEndpointOperations, DigitalTwinsOperations, Operations, PrivateEndpointConnectionsOperations, PrivateLinkResourcesOperations, TimeSeriesDatabaseConnectionsOperations +from .operations import ( + DigitalTwinsEndpointOperations, + DigitalTwinsOperations, + Operations, + PrivateEndpointConnectionsOperations, + PrivateLinkResourcesOperations, + TimeSeriesDatabaseConnectionsOperations, +) if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class AzureDigitalTwinsManagementClient: + +class AzureDigitalTwinsManagementClient: # pylint: disable=client-accepts-api-version-keyword """Azure Digital Twins Client for managing DigitalTwinsInstance. :ivar digital_twins: DigitalTwinsOperations operations @@ -42,9 +49,9 @@ class AzureDigitalTwinsManagementClient: :ivar time_series_database_connections: TimeSeriesDatabaseConnectionsOperations operations :vartype time_series_database_connections: azure.mgmt.digitaltwins.v2021_06_30_preview.aio.operations.TimeSeriesDatabaseConnectionsOperations - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: The subscription identifier. + :param subscription_id: The subscription identifier. Required. :type subscription_id: str :param base_url: Service URL. Default value is "https://management.azure.com". :type base_url: str @@ -62,26 +69,31 @@ def __init__( base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: - self._config = AzureDigitalTwinsManagementClientConfiguration(credential=credential, subscription_id=subscription_id, **kwargs) + self._config = AzureDigitalTwinsManagementClientConfiguration( + credential=credential, subscription_id=subscription_id, **kwargs + ) self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) - client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) self._deserialize = Deserializer(client_models) self._serialize.client_side_validation = False self.digital_twins = DigitalTwinsOperations(self._client, self._config, self._serialize, self._deserialize) - self.digital_twins_endpoint = DigitalTwinsEndpointOperations(self._client, self._config, self._serialize, self._deserialize) + self.digital_twins_endpoint = DigitalTwinsEndpointOperations( + self._client, self._config, self._serialize, self._deserialize + ) self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) - self.private_link_resources = PrivateLinkResourcesOperations(self._client, self._config, self._serialize, self._deserialize) - self.private_endpoint_connections = PrivateEndpointConnectionsOperations(self._client, self._config, self._serialize, self._deserialize) - self.time_series_database_connections = TimeSeriesDatabaseConnectionsOperations(self._client, self._config, self._serialize, self._deserialize) - - - def _send_request( - self, - request: HttpRequest, - **kwargs: Any - ) -> Awaitable[AsyncHttpResponse]: + self.private_link_resources = PrivateLinkResourcesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.private_endpoint_connections = PrivateEndpointConnectionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.time_series_database_connections = TimeSeriesDatabaseConnectionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + + def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: """Runs the network request through the client's chained policies. >>> from azure.core.rest import HttpRequest @@ -90,7 +102,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/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/aio/_configuration.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/aio/_configuration.py index 43fc0e2861320..6da71dd9a29c7 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/aio/_configuration.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/aio/_configuration.py @@ -6,6 +6,7 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, TYPE_CHECKING from azure.core.configuration import Configuration @@ -14,6 +15,11 @@ from .._version import VERSION +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports + if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential @@ -25,23 +31,18 @@ class AzureDigitalTwinsManagementClientConfiguration(Configuration): # pylint: Note that all parameters used to create this instance are saved as instance attributes. - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: The subscription identifier. + :param subscription_id: The subscription identifier. Required. :type subscription_id: str :keyword api_version: Api Version. Default value is "2021-06-30-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(AzureDigitalTwinsManagementClientConfiguration, self).__init__(**kwargs) - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str + api_version: Literal["2021-06-30-preview"] = kwargs.pop("api_version", "2021-06-30-preview") if credential is None: raise ValueError("Parameter 'credential' must not be None.") @@ -51,22 +52,21 @@ def __init__( self.credential = credential self.subscription_id = subscription_id self.api_version = api_version - self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'mgmt-digitaltwins/{}'.format(VERSION)) + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-digitaltwins/{}".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/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/aio/_patch.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/aio/_patch.py index 74e48ecd07cf3..f99e77fef9861 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/aio/_patch.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/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/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/aio/operations/__init__.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/aio/operations/__init__.py index b5d50b71ecc92..791d2a1bb74f4 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/aio/operations/__init__.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/aio/operations/__init__.py @@ -13,11 +13,17 @@ from ._private_endpoint_connections_operations import PrivateEndpointConnectionsOperations from ._time_series_database_connections_operations import TimeSeriesDatabaseConnectionsOperations +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + __all__ = [ - 'DigitalTwinsOperations', - 'DigitalTwinsEndpointOperations', - 'Operations', - 'PrivateLinkResourcesOperations', - 'PrivateEndpointConnectionsOperations', - 'TimeSeriesDatabaseConnectionsOperations', + "DigitalTwinsOperations", + "DigitalTwinsEndpointOperations", + "Operations", + "PrivateLinkResourcesOperations", + "PrivateEndpointConnectionsOperations", + "TimeSeriesDatabaseConnectionsOperations", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/aio/operations/_digital_twins_endpoint_operations.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/aio/operations/_digital_twins_endpoint_operations.py index 0bf487cefd9d1..87d2d749d1267 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/aio/operations/_digital_twins_endpoint_operations.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/aio/operations/_digital_twins_endpoint_operations.py @@ -6,96 +6,126 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar, Union +import sys +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models from ..._vendor import _convert_request -from ...operations._digital_twins_endpoint_operations import build_create_or_update_request_initial, build_delete_request_initial, build_get_request, build_list_request -T = TypeVar('T') +from ...operations._digital_twins_endpoint_operations import ( + build_create_or_update_request, + build_delete_request, + build_get_request, + build_list_request, +) + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class DigitalTwinsEndpointOperations: - """DigitalTwinsEndpointOperations 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 DigitalTwinsEndpointOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.digitaltwins.v2021_06_30_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.digitaltwins.v2021_06_30_preview.aio.AzureDigitalTwinsManagementClient`'s + :attr:`digital_twins_endpoint` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list( - self, - resource_group_name: str, - resource_name: str, - **kwargs: Any - ) -> AsyncIterable["_models.DigitalTwinsEndpointResourceListResult"]: + self, resource_group_name: str, resource_name: str, **kwargs: Any + ) -> AsyncIterable["_models.DigitalTwinsEndpointResource"]: """Get DigitalTwinsInstance Endpoints. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either DigitalTwinsEndpointResourceListResult or the - result of cls(response) + :return: An iterator like instance of either DigitalTwinsEndpointResource or the result of + cls(response) :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.digitaltwins.v2021_06_30_preview.models.DigitalTwinsEndpointResourceListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.digitaltwins.v2021_06_30_preview.models.DigitalTwinsEndpointResource] + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") + ) + cls: ClsType[_models.DigitalTwinsEndpointResourceListResult] = kwargs.pop("cls", None) - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsEndpointResourceListResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list.metadata['url'], + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: - - request = build_list_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - resource_name=resource_name, - api_version=api_version, - template_url=next_link, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) @@ -106,16 +136,14 @@ async def extract_data(pipeline_response): deserialized = self._deserialize("DigitalTwinsEndpointResourceListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -126,59 +154,63 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints"} # type: ignore + list.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints" + } @distributed_trace_async async def get( - self, - resource_group_name: str, - resource_name: str, - endpoint_name: str, - **kwargs: Any - ) -> "_models.DigitalTwinsEndpointResource": + self, resource_group_name: str, resource_name: str, endpoint_name: str, **kwargs: Any + ) -> _models.DigitalTwinsEndpointResource: """Get DigitalTwinsInstances Endpoint. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param endpoint_name: Name of Endpoint Resource. + :param endpoint_name: Name of Endpoint Resource. Required. :type endpoint_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: DigitalTwinsEndpointResource, or the result of cls(response) + :return: DigitalTwinsEndpointResource or the result of cls(response) :rtype: ~azure.mgmt.digitaltwins.v2021_06_30_preview.models.DigitalTwinsEndpointResource - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsEndpointResource"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") + ) + cls: ClsType[_models.DigitalTwinsEndpointResource] = kwargs.pop("cls", None) - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, endpoint_name=endpoint_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -186,72 +218,174 @@ async def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('DigitalTwinsEndpointResource', pipeline_response) + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}"} # type: ignore - + get.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}" + } async def _create_or_update_initial( self, resource_group_name: str, resource_name: str, endpoint_name: str, - endpoint_description: "_models.DigitalTwinsEndpointResource", + endpoint_description: Union[_models.DigitalTwinsEndpointResource, IO], **kwargs: Any - ) -> "_models.DigitalTwinsEndpointResource": - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsEndpointResource"] + ) -> _models.DigitalTwinsEndpointResource: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(endpoint_description, 'DigitalTwinsEndpointResource') - - request = build_create_or_update_request_initial( - subscription_id=self._config.subscription_id, + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") + ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DigitalTwinsEndpointResource] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(endpoint_description, (IO, bytes)): + _content = endpoint_description + else: + _json = self._serialize.body(endpoint_description, "DigitalTwinsEndpointResource") + + request = build_create_or_update_request( resource_group_name=resource_group_name, resource_name=resource_name, 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_initial.metadata['url'], + content=_content, + template_url=self._create_or_update_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('DigitalTwinsEndpointResource', pipeline_response) + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('DigitalTwinsEndpointResource', pipeline_response) + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized + return deserialized # type: ignore + + _create_or_update_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}" + } + + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + endpoint_name: str, + endpoint_description: _models.DigitalTwinsEndpointResource, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.DigitalTwinsEndpointResource]: + """Create or update DigitalTwinsInstance endpoint. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param endpoint_name: Name of Endpoint Resource. Required. + :type endpoint_name: str + :param endpoint_description: The DigitalTwinsInstance endpoint metadata and security metadata. + Required. + :type endpoint_description: + ~azure.mgmt.digitaltwins.v2021_06_30_preview.models.DigitalTwinsEndpointResource + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either DigitalTwinsEndpointResource or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2021_06_30_preview.models.DigitalTwinsEndpointResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ - _create_or_update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}"} # type: ignore + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + endpoint_name: str, + endpoint_description: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.DigitalTwinsEndpointResource]: + """Create or update DigitalTwinsInstance endpoint. + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param endpoint_name: Name of Endpoint Resource. Required. + :type endpoint_name: str + :param endpoint_description: The DigitalTwinsInstance endpoint metadata and security metadata. + Required. + :type endpoint_description: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either DigitalTwinsEndpointResource or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2021_06_30_preview.models.DigitalTwinsEndpointResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace_async async def begin_create_or_update( @@ -259,21 +393,25 @@ async def begin_create_or_update( resource_group_name: str, resource_name: str, endpoint_name: str, - endpoint_description: "_models.DigitalTwinsEndpointResource", + endpoint_description: Union[_models.DigitalTwinsEndpointResource, IO], **kwargs: Any - ) -> AsyncLROPoller["_models.DigitalTwinsEndpointResource"]: + ) -> AsyncLROPoller[_models.DigitalTwinsEndpointResource]: """Create or update DigitalTwinsInstance endpoint. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param endpoint_name: Name of Endpoint Resource. + :param endpoint_name: Name of Endpoint Resource. Required. :type endpoint_name: str :param endpoint_description: The DigitalTwinsInstance endpoint metadata and security metadata. + Is either a model type or a IO type. Required. :type endpoint_description: - ~azure.mgmt.digitaltwins.v2021_06_30_preview.models.DigitalTwinsEndpointResource + ~azure.mgmt.digitaltwins.v2021_06_30_preview.models.DigitalTwinsEndpointResource or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for @@ -286,17 +424,19 @@ async def begin_create_or_update( result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2021_06_30_preview.models.DigitalTwinsEndpointResource] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsEndpointResource"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DigitalTwinsEndpointResource] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = await self._create_or_update_initial( resource_group_name=resource_group_name, @@ -305,102 +445,109 @@ async def begin_create_or_update( endpoint_description=endpoint_description, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('DigitalTwinsEndpointResource', pipeline_response) + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - begin_create_or_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}"} # type: ignore + begin_create_or_update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}" + } async def _delete_initial( - self, - resource_group_name: str, - resource_name: str, - endpoint_name: str, - **kwargs: Any - ) -> Optional["_models.DigitalTwinsEndpointResource"]: - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.DigitalTwinsEndpointResource"]] + self, resource_group_name: str, resource_name: str, endpoint_name: str, **kwargs: Any + ) -> Optional[_models.DigitalTwinsEndpointResource]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - request = build_delete_request_initial( - subscription_id=self._config.subscription_id, + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") + ) + cls: ClsType[Optional[_models.DigitalTwinsEndpointResource]] = kwargs.pop("cls", None) + + request = build_delete_request( resource_group_name=resource_group_name, resource_name=resource_name, endpoint_name=endpoint_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._delete_initial.metadata['url'], + template_url=self._delete_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('DigitalTwinsEndpointResource', pipeline_response) + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) if response.status_code == 202: - deserialized = self._deserialize('DigitalTwinsEndpointResource', pipeline_response) + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _delete_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}"} # type: ignore - + _delete_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}" + } @distributed_trace_async async def begin_delete( - self, - resource_group_name: str, - resource_name: str, - endpoint_name: str, - **kwargs: Any - ) -> AsyncLROPoller["_models.DigitalTwinsEndpointResource"]: + self, resource_group_name: str, resource_name: str, endpoint_name: str, **kwargs: Any + ) -> AsyncLROPoller[_models.DigitalTwinsEndpointResource]: """Delete a DigitalTwinsInstance endpoint. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param endpoint_name: Name of Endpoint Resource. + :param endpoint_name: Name of Endpoint Resource. Required. :type endpoint_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. @@ -414,45 +561,52 @@ async def begin_delete( result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2021_06_30_preview.models.DigitalTwinsEndpointResource] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsEndpointResource"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + cls: ClsType[_models.DigitalTwinsEndpointResource] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = await self._delete_initial( resource_group_name=resource_group_name, resource_name=resource_name, endpoint_name=endpoint_name, api_version=api_version, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('DigitalTwinsEndpointResource', pipeline_response) + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - begin_delete.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}"} # type: ignore + begin_delete.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}" + } diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/aio/operations/_digital_twins_operations.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/aio/operations/_digital_twins_operations.py index 2e8be989b7870..7dde3ee0e2d59 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/aio/operations/_digital_twins_operations.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/aio/operations/_digital_twins_operations.py @@ -6,90 +6,114 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar, Union +import sys +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models from ..._vendor import _convert_request -from ...operations._digital_twins_operations import build_check_name_availability_request, build_create_or_update_request_initial, build_delete_request_initial, build_get_request, build_list_by_resource_group_request, build_list_request, build_update_request_initial -T = TypeVar('T') +from ...operations._digital_twins_operations import ( + build_check_name_availability_request, + build_create_or_update_request, + build_delete_request, + build_get_request, + build_list_by_resource_group_request, + build_list_request, + build_update_request, +) + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class DigitalTwinsOperations: - """DigitalTwinsOperations 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 DigitalTwinsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.digitaltwins.v2021_06_30_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.digitaltwins.v2021_06_30_preview.aio.AzureDigitalTwinsManagementClient`'s + :attr:`digital_twins` 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, - resource_group_name: str, - resource_name: str, - **kwargs: Any - ) -> "_models.DigitalTwinsDescription": + async def get(self, resource_group_name: str, resource_name: str, **kwargs: Any) -> _models.DigitalTwinsDescription: """Get DigitalTwinsInstances resource. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: DigitalTwinsDescription, or the result of cls(response) + :return: DigitalTwinsDescription or the result of cls(response) :rtype: ~azure.mgmt.digitaltwins.v2021_06_30_preview.models.DigitalTwinsDescription - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescription"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") + ) + cls: ClsType[_models.DigitalTwinsDescription] = kwargs.pop("cls", None) - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -97,91 +121,193 @@ async def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}"} # type: ignore - + get.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } async def _create_or_update_initial( self, resource_group_name: str, resource_name: str, - digital_twins_create: "_models.DigitalTwinsDescription", + digital_twins_create: Union[_models.DigitalTwinsDescription, IO], **kwargs: Any - ) -> "_models.DigitalTwinsDescription": - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescription"] + ) -> _models.DigitalTwinsDescription: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + error_map.update(kwargs.pop("error_map", {}) or {}) - _json = self._serialize.body(digital_twins_create, 'DigitalTwinsDescription') + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - request = build_create_or_update_request_initial( - subscription_id=self._config.subscription_id, + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") + ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DigitalTwinsDescription] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(digital_twins_create, (IO, bytes)): + _content = digital_twins_create + else: + _json = self._serialize.body(digital_twins_create, "DigitalTwinsDescription") + + request = build_create_or_update_request( resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._create_or_update_initial.metadata['url'], + content=_content, + template_url=self._create_or_update_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized + return deserialized # type: ignore + + _create_or_update_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } - _create_or_update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}"} # type: ignore + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + digital_twins_create: _models.DigitalTwinsDescription, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.DigitalTwinsDescription]: + """Create or update the metadata of a DigitalTwinsInstance. The usual pattern to modify a property + is to retrieve the DigitalTwinsInstance and security metadata, and then combine them with the + modified values in a new body to update the DigitalTwinsInstance. + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param digital_twins_create: The DigitalTwinsInstance and security metadata. Required. + :type digital_twins_create: + ~azure.mgmt.digitaltwins.v2021_06_30_preview.models.DigitalTwinsDescription + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either DigitalTwinsDescription or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2021_06_30_preview.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + digital_twins_create: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.DigitalTwinsDescription]: + """Create or update the metadata of a DigitalTwinsInstance. The usual pattern to modify a property + is to retrieve the DigitalTwinsInstance and security metadata, and then combine them with the + modified values in a new body to update the DigitalTwinsInstance. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param digital_twins_create: The DigitalTwinsInstance and security metadata. Required. + :type digital_twins_create: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either DigitalTwinsDescription or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2021_06_30_preview.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace_async async def begin_create_or_update( self, resource_group_name: str, resource_name: str, - digital_twins_create: "_models.DigitalTwinsDescription", + digital_twins_create: Union[_models.DigitalTwinsDescription, IO], **kwargs: Any - ) -> AsyncLROPoller["_models.DigitalTwinsDescription"]: + ) -> AsyncLROPoller[_models.DigitalTwinsDescription]: """Create or update the metadata of a DigitalTwinsInstance. The usual pattern to modify a property is to retrieve the DigitalTwinsInstance and security metadata, and then combine them with the modified values in a new body to update the DigitalTwinsInstance. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param digital_twins_create: The DigitalTwinsInstance and security metadata. + :param digital_twins_create: The DigitalTwinsInstance and security metadata. Is either a model + type or a IO type. Required. :type digital_twins_create: - ~azure.mgmt.digitaltwins.v2021_06_30_preview.models.DigitalTwinsDescription + ~azure.mgmt.digitaltwins.v2021_06_30_preview.models.DigitalTwinsDescription or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for @@ -194,17 +320,19 @@ async def begin_create_or_update( result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2021_06_30_preview.models.DigitalTwinsDescription] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescription"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DigitalTwinsDescription] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = await self._create_or_update_initial( resource_group_name=resource_group_name, @@ -212,106 +340,210 @@ async def begin_create_or_update( digital_twins_create=digital_twins_create, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - begin_create_or_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}"} # type: ignore + begin_create_or_update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } async def _update_initial( self, resource_group_name: str, resource_name: str, - digital_twins_patch_description: "_models.DigitalTwinsPatchDescription", + digital_twins_patch_description: Union[_models.DigitalTwinsPatchDescription, IO], **kwargs: Any - ) -> "_models.DigitalTwinsDescription": - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescription"] + ) -> _models.DigitalTwinsDescription: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(digital_twins_patch_description, 'DigitalTwinsPatchDescription') - - request = build_update_request_initial( - subscription_id=self._config.subscription_id, + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") + ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DigitalTwinsDescription] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(digital_twins_patch_description, (IO, bytes)): + _content = digital_twins_patch_description + else: + _json = self._serialize.body(digital_twins_patch_description, "DigitalTwinsPatchDescription") + + request = build_update_request( resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._update_initial.metadata['url'], + content=_content, + template_url=self._update_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if response.status_code == 202: - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized + return deserialized # type: ignore - _update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}"} # type: ignore + _update_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } - - @distributed_trace_async + @overload async def begin_update( self, resource_group_name: str, resource_name: str, - digital_twins_patch_description: "_models.DigitalTwinsPatchDescription", + digital_twins_patch_description: _models.DigitalTwinsPatchDescription, + *, + content_type: str = "application/json", **kwargs: Any - ) -> AsyncLROPoller["_models.DigitalTwinsDescription"]: + ) -> AsyncLROPoller[_models.DigitalTwinsDescription]: """Update metadata of DigitalTwinsInstance. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str :param digital_twins_patch_description: The DigitalTwinsInstance and security metadata. + Required. :type digital_twins_patch_description: ~azure.mgmt.digitaltwins.v2021_06_30_preview.models.DigitalTwinsPatchDescription + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either DigitalTwinsDescription or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2021_06_30_preview.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_update( + self, + resource_group_name: str, + resource_name: str, + digital_twins_patch_description: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.DigitalTwinsDescription]: + """Update metadata of DigitalTwinsInstance. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param digital_twins_patch_description: The DigitalTwinsInstance and security metadata. + Required. + :type digital_twins_patch_description: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either DigitalTwinsDescription or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2021_06_30_preview.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_update( + self, + resource_group_name: str, + resource_name: str, + digital_twins_patch_description: Union[_models.DigitalTwinsPatchDescription, IO], + **kwargs: Any + ) -> AsyncLROPoller[_models.DigitalTwinsDescription]: + """Update metadata of DigitalTwinsInstance. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param digital_twins_patch_description: The DigitalTwinsInstance and security metadata. Is + either a model type or a IO type. Required. + :type digital_twins_patch_description: + ~azure.mgmt.digitaltwins.v2021_06_30_preview.models.DigitalTwinsPatchDescription or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for @@ -324,17 +556,19 @@ async def begin_update( result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2021_06_30_preview.models.DigitalTwinsDescription] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescription"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DigitalTwinsDescription] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = await self._update_initial( resource_group_name=resource_group_name, @@ -342,97 +576,106 @@ async def begin_update( digital_twins_patch_description=digital_twins_patch_description, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - begin_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}"} # type: ignore + begin_update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } async def _delete_initial( - self, - resource_group_name: str, - resource_name: str, - **kwargs: Any - ) -> Optional["_models.DigitalTwinsDescription"]: - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.DigitalTwinsDescription"]] + self, resource_group_name: str, resource_name: str, **kwargs: Any + ) -> Optional[_models.DigitalTwinsDescription]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - request = build_delete_request_initial( - subscription_id=self._config.subscription_id, + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") + ) + cls: ClsType[Optional[_models.DigitalTwinsDescription]] = kwargs.pop("cls", None) + + request = build_delete_request( resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._delete_initial.metadata['url'], + template_url=self._delete_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if response.status_code == 202: - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _delete_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}"} # type: ignore - + _delete_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } @distributed_trace_async async def begin_delete( - self, - resource_group_name: str, - resource_name: str, - **kwargs: Any - ) -> AsyncLROPoller["_models.DigitalTwinsDescription"]: + self, resource_group_name: str, resource_name: str, **kwargs: Any + ) -> AsyncLROPoller[_models.DigitalTwinsDescription]: """Delete a DigitalTwinsInstance. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. @@ -446,86 +689,107 @@ async def begin_delete( result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2021_06_30_preview.models.DigitalTwinsDescription] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescription"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + cls: ClsType[_models.DigitalTwinsDescription] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = await self._delete_initial( resource_group_name=resource_group_name, resource_name=resource_name, api_version=api_version, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - begin_delete.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}"} # type: ignore + begin_delete.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } @distributed_trace - def list( - self, - **kwargs: Any - ) -> AsyncIterable["_models.DigitalTwinsDescriptionListResult"]: + def list(self, **kwargs: Any) -> AsyncIterable["_models.DigitalTwinsDescription"]: """Get all the DigitalTwinsInstances in a subscription. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either DigitalTwinsDescriptionListResult or the result of + :return: An iterator like instance of either DigitalTwinsDescription or the result of cls(response) :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.digitaltwins.v2021_06_30_preview.models.DigitalTwinsDescriptionListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.digitaltwins.v2021_06_30_preview.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") + ) + cls: ClsType[_models.DigitalTwinsDescriptionListResult] = kwargs.pop("cls", None) - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescriptionListResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list.metadata['url'], + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: - - request = build_list_request( - subscription_id=self._config.subscription_id, - api_version=api_version, - template_url=next_link, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) @@ -536,16 +800,14 @@ async def extract_data(pipeline_response): deserialized = self._deserialize("DigitalTwinsDescriptionListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -556,56 +818,68 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.DigitalTwins/digitalTwinsInstances"} # type: ignore + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.DigitalTwins/digitalTwinsInstances"} @distributed_trace def list_by_resource_group( - self, - resource_group_name: str, - **kwargs: Any - ) -> AsyncIterable["_models.DigitalTwinsDescriptionListResult"]: + self, resource_group_name: str, **kwargs: Any + ) -> AsyncIterable["_models.DigitalTwinsDescription"]: """Get all the DigitalTwinsInstances in a resource group. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. 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 DigitalTwinsDescriptionListResult or the result of + :return: An iterator like instance of either DigitalTwinsDescription or the result of cls(response) :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.digitaltwins.v2021_06_30_preview.models.DigitalTwinsDescriptionListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.digitaltwins.v2021_06_30_preview.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") + ) + cls: ClsType[_models.DigitalTwinsDescriptionListResult] = kwargs.pop("cls", None) - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescriptionListResult"] 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( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata['url'], + template_url=self.list_by_resource_group.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: - - request = build_list_by_resource_group_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - api_version=api_version, - template_url=next_link, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) @@ -616,16 +890,14 @@ async def extract_data(pipeline_response): deserialized = self._deserialize("DigitalTwinsDescriptionListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -636,59 +908,129 @@ 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.DigitalTwins/digitalTwinsInstances"} # type: ignore + list_by_resource_group.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances" + } - @distributed_trace_async + @overload async def check_name_availability( self, location: str, - digital_twins_instance_check_name: "_models.CheckNameRequest", + digital_twins_instance_check_name: _models.CheckNameRequest, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.CheckNameResult": + ) -> _models.CheckNameResult: """Check if a DigitalTwinsInstance name is available. - :param location: Location of DigitalTwinsInstance. + :param location: Location of DigitalTwinsInstance. Required. :type location: str :param digital_twins_instance_check_name: Set the name parameter in the DigitalTwinsInstanceCheckName structure to the name of the DigitalTwinsInstance to check. + Required. :type digital_twins_instance_check_name: ~azure.mgmt.digitaltwins.v2021_06_30_preview.models.CheckNameRequest + :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: CheckNameResult, or the result of cls(response) + :return: CheckNameResult or the result of cls(response) :rtype: ~azure.mgmt.digitaltwins.v2021_06_30_preview.models.CheckNameResult - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def check_name_availability( + self, + location: str, + digital_twins_instance_check_name: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.CheckNameResult: + """Check if a DigitalTwinsInstance name is available. + + :param location: Location of DigitalTwinsInstance. Required. + :type location: str + :param digital_twins_instance_check_name: Set the name parameter in the + DigitalTwinsInstanceCheckName structure to the name of the DigitalTwinsInstance to check. + Required. + :type digital_twins_instance_check_name: 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: CheckNameResult or the result of cls(response) + :rtype: ~azure.mgmt.digitaltwins.v2021_06_30_preview.models.CheckNameResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def check_name_availability( + self, location: str, digital_twins_instance_check_name: Union[_models.CheckNameRequest, IO], **kwargs: Any + ) -> _models.CheckNameResult: + """Check if a DigitalTwinsInstance name is available. + + :param location: Location of DigitalTwinsInstance. Required. + :type location: str + :param digital_twins_instance_check_name: Set the name parameter in the + DigitalTwinsInstanceCheckName structure to the name of the DigitalTwinsInstance to check. Is + either a model type or a IO type. Required. + :type digital_twins_instance_check_name: + ~azure.mgmt.digitaltwins.v2021_06_30_preview.models.CheckNameRequest 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: CheckNameResult or the result of cls(response) + :rtype: ~azure.mgmt.digitaltwins.v2021_06_30_preview.models.CheckNameResult + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.CheckNameResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(digital_twins_instance_check_name, 'CheckNameRequest') + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") + ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.CheckNameResult] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(digital_twins_instance_check_name, (IO, bytes)): + _content = digital_twins_instance_check_name + else: + _json = self._serialize.body(digital_twins_instance_check_name, "CheckNameRequest") request = build_check_name_availability_request( - subscription_id=self._config.subscription_id, location=location, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self.check_name_availability.metadata['url'], + content=_content, + template_url=self.check_name_availability.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -696,12 +1038,13 @@ async def check_name_availability( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('CheckNameResult', pipeline_response) + deserialized = self._deserialize("CheckNameResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - check_name_availability.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.DigitalTwins/locations/{location}/checkNameAvailability"} # type: ignore - + check_name_availability.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.DigitalTwins/locations/{location}/checkNameAvailability" + } diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/aio/operations/_operations.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/aio/operations/_operations.py index d71aa2b25c39f..e598b30b77dbf 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/aio/operations/_operations.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/aio/operations/_operations.py @@ -6,79 +6,107 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models from ..._vendor import _convert_request from ...operations._operations import build_list_request -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class Operations: - """Operations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class Operations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.digitaltwins.v2021_06_30_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.digitaltwins.v2021_06_30_preview.aio.AzureDigitalTwinsManagementClient`'s + :attr:`operations` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace - def list( - self, - **kwargs: Any - ) -> AsyncIterable["_models.OperationListResult"]: + def list(self, **kwargs: Any) -> AsyncIterable["_models.Operation"]: """Lists all of the available DigitalTwins service REST API operations. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either OperationListResult or the result of cls(response) + :return: An iterator like instance of either Operation or the result of cls(response) :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.digitaltwins.v2021_06_30_preview.models.OperationListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.digitaltwins.v2021_06_30_preview.models.Operation] + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") + ) + cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) - cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationListResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( api_version=api_version, - template_url=self.list.metadata['url'], + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: - - request = build_list_request( - api_version=api_version, - template_url=next_link, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) @@ -89,16 +117,14 @@ async def extract_data(pipeline_response): deserialized = self._deserialize("OperationListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -109,8 +135,6 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/providers/Microsoft.DigitalTwins/operations"} # type: ignore + list.metadata = {"url": "/providers/Microsoft.DigitalTwins/operations"} diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/aio/operations/_patch.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/aio/operations/_patch.py new file mode 100644 index 0000000000000..f7dd32510333d --- /dev/null +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/aio/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/aio/operations/_private_endpoint_connections_operations.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/aio/operations/_private_endpoint_connections_operations.py index befa9bc3674c4..c8bf54a031f5e 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/aio/operations/_private_endpoint_connections_operations.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/aio/operations/_private_endpoint_connections_operations.py @@ -6,88 +6,110 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Optional, TypeVar, Union - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import sys +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, cast, 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.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod 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 azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models from ..._vendor import _convert_request -from ...operations._private_endpoint_connections_operations import build_create_or_update_request_initial, build_delete_request_initial, build_get_request, build_list_request -T = TypeVar('T') +from ...operations._private_endpoint_connections_operations import ( + build_create_or_update_request, + build_delete_request, + build_get_request, + build_list_request, +) + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class PrivateEndpointConnectionsOperations: - """PrivateEndpointConnectionsOperations 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 PrivateEndpointConnectionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.digitaltwins.v2021_06_30_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.digitaltwins.v2021_06_30_preview.aio.AzureDigitalTwinsManagementClient`'s + :attr:`private_endpoint_connections` 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 list( - self, - resource_group_name: str, - resource_name: str, - **kwargs: Any - ) -> "_models.PrivateEndpointConnectionsResponse": + self, resource_group_name: str, resource_name: str, **kwargs: Any + ) -> _models.PrivateEndpointConnectionsResponse: """List private endpoint connection properties. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: PrivateEndpointConnectionsResponse, or the result of cls(response) + :return: PrivateEndpointConnectionsResponse or the result of cls(response) :rtype: ~azure.mgmt.digitaltwins.v2021_06_30_preview.models.PrivateEndpointConnectionsResponse - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnectionsResponse"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") + ) + cls: ClsType[_models.PrivateEndpointConnectionsResponse] = kwargs.pop("cls", None) - request = build_list_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list.metadata['url'], + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -95,63 +117,68 @@ async def list( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('PrivateEndpointConnectionsResponse', pipeline_response) + deserialized = self._deserialize("PrivateEndpointConnectionsResponse", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - list.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections"} # type: ignore - + list.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections" + } @distributed_trace_async async def get( - self, - resource_group_name: str, - resource_name: str, - private_endpoint_connection_name: str, - **kwargs: Any - ) -> "_models.PrivateEndpointConnection": + self, resource_group_name: str, resource_name: str, private_endpoint_connection_name: str, **kwargs: Any + ) -> _models.PrivateEndpointConnection: """Get private endpoint connection properties for the given private endpoint. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param private_endpoint_connection_name: The name of the private endpoint connection. + :param private_endpoint_connection_name: The name of the private endpoint connection. Required. :type private_endpoint_connection_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: PrivateEndpointConnection, or the result of cls(response) + :return: PrivateEndpointConnection or the result of cls(response) :rtype: ~azure.mgmt.digitaltwins.v2021_06_30_preview.models.PrivateEndpointConnection - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnection"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") + ) + cls: ClsType[_models.PrivateEndpointConnection] = kwargs.pop("cls", None) - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, private_endpoint_connection_name=private_endpoint_connection_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -159,76 +186,79 @@ async def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore - + get.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}" + } async def _delete_initial( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - resource_name: str, - private_endpoint_connection_name: str, - **kwargs: Any + self, resource_group_name: str, resource_name: str, private_endpoint_connection_name: str, **kwargs: Any ) -> None: - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - request = build_delete_request_initial( - subscription_id=self._config.subscription_id, + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") + ) + cls: ClsType[None] = kwargs.pop("cls", None) + + request = build_delete_request( resource_group_name=resource_group_name, resource_name=resource_name, private_endpoint_connection_name=private_endpoint_connection_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._delete_initial.metadata['url'], + template_url=self._delete_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - _delete_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore - + _delete_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}" + } @distributed_trace_async - async def begin_delete( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - resource_name: str, - private_endpoint_connection_name: str, - **kwargs: Any + async def begin_delete( + self, resource_group_name: str, resource_name: str, private_endpoint_connection_name: str, **kwargs: Any ) -> AsyncLROPoller[None]: """Delete private endpoint connection with the specified name. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param private_endpoint_connection_name: The name of the private endpoint connection. + :param private_endpoint_connection_name: The name of the private endpoint connection. Required. :type private_endpoint_connection_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. @@ -240,124 +270,156 @@ async def begin_delete( # pylint: disable=inconsistent-return-statements Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType[None] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: - raw_result = await self._delete_initial( + raw_result = await self._delete_initial( # type: ignore resource_group_name=resource_group_name, resource_name=resource_name, private_endpoint_connection_name=private_endpoint_connection_name, api_version=api_version, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - - if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - begin_delete.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore + begin_delete.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}" + } async def _create_or_update_initial( self, resource_group_name: str, resource_name: str, private_endpoint_connection_name: str, - private_endpoint_connection: "_models.PrivateEndpointConnection", + private_endpoint_connection: Union[_models.PrivateEndpointConnection, IO], **kwargs: Any - ) -> "_models.PrivateEndpointConnection": - cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnection"] + ) -> _models.PrivateEndpointConnection: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + error_map.update(kwargs.pop("error_map", {}) or {}) - _json = self._serialize.body(private_endpoint_connection, 'PrivateEndpointConnection') + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - request = build_create_or_update_request_initial( - subscription_id=self._config.subscription_id, + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") + ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PrivateEndpointConnection] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(private_endpoint_connection, (IO, bytes)): + _content = private_endpoint_connection + else: + _json = self._serialize.body(private_endpoint_connection, "PrivateEndpointConnection") + + request = build_create_or_update_request( resource_group_name=resource_group_name, resource_name=resource_name, private_endpoint_connection_name=private_endpoint_connection_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._create_or_update_initial.metadata['url'], + content=_content, + template_url=self._create_or_update_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) if response.status_code == 202: - deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - _create_or_update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore + return deserialized # type: ignore + _create_or_update_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}" + } - @distributed_trace_async + @overload async def begin_create_or_update( self, resource_group_name: str, resource_name: str, private_endpoint_connection_name: str, - private_endpoint_connection: "_models.PrivateEndpointConnection", + private_endpoint_connection: _models.PrivateEndpointConnection, + *, + content_type: str = "application/json", **kwargs: Any - ) -> AsyncLROPoller["_models.PrivateEndpointConnection"]: + ) -> AsyncLROPoller[_models.PrivateEndpointConnection]: """Update the status of a private endpoint connection with the given name. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param private_endpoint_connection_name: The name of the private endpoint connection. + :param private_endpoint_connection_name: The name of the private endpoint connection. Required. :type private_endpoint_connection_name: str :param private_endpoint_connection: The private endpoint connection with updated properties. + Required. :type private_endpoint_connection: ~azure.mgmt.digitaltwins.v2021_06_30_preview.models.PrivateEndpointConnection + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for @@ -370,17 +432,100 @@ async def begin_create_or_update( result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2021_06_30_preview.models.PrivateEndpointConnection] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnection"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval + + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + private_endpoint_connection_name: str, + private_endpoint_connection: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.PrivateEndpointConnection]: + """Update the status of a private endpoint connection with the given name. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param private_endpoint_connection_name: The name of the private endpoint connection. Required. + :type private_endpoint_connection_name: str + :param private_endpoint_connection: The private endpoint connection with updated properties. + Required. + :type private_endpoint_connection: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either PrivateEndpointConnection or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2021_06_30_preview.models.PrivateEndpointConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + private_endpoint_connection_name: str, + private_endpoint_connection: Union[_models.PrivateEndpointConnection, IO], + **kwargs: Any + ) -> AsyncLROPoller[_models.PrivateEndpointConnection]: + """Update the status of a private endpoint connection with the given name. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param private_endpoint_connection_name: The name of the private endpoint connection. Required. + :type private_endpoint_connection_name: str + :param private_endpoint_connection: The private endpoint connection with updated properties. Is + either a model type or a IO type. Required. + :type private_endpoint_connection: + ~azure.mgmt.digitaltwins.v2021_06_30_preview.models.PrivateEndpointConnection or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either PrivateEndpointConnection or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2021_06_30_preview.models.PrivateEndpointConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PrivateEndpointConnection] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = await self._create_or_update_initial( resource_group_name=resource_group_name, @@ -389,29 +534,34 @@ async def begin_create_or_update( private_endpoint_connection=private_endpoint_connection, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - begin_create_or_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore + begin_create_or_update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}" + } diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/aio/operations/_private_link_resources_operations.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/aio/operations/_private_link_resources_operations.py index 498eeb0f414ce..812b942230f27 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/aio/operations/_private_link_resources_operations.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/aio/operations/_private_link_resources_operations.py @@ -6,86 +6,103 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, Callable, Dict, Optional, TypeVar -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_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models from ..._vendor import _convert_request from ...operations._private_link_resources_operations import build_get_request, build_list_request -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class PrivateLinkResourcesOperations: - """PrivateLinkResourcesOperations 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 PrivateLinkResourcesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.digitaltwins.v2021_06_30_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.digitaltwins.v2021_06_30_preview.aio.AzureDigitalTwinsManagementClient`'s + :attr:`private_link_resources` 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 list( - self, - resource_group_name: str, - resource_name: str, - **kwargs: Any - ) -> "_models.GroupIdInformationResponse": + self, resource_group_name: str, resource_name: str, **kwargs: Any + ) -> _models.GroupIdInformationResponse: """List private link resources for given Digital Twin. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: GroupIdInformationResponse, or the result of cls(response) + :return: GroupIdInformationResponse or the result of cls(response) :rtype: ~azure.mgmt.digitaltwins.v2021_06_30_preview.models.GroupIdInformationResponse - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.GroupIdInformationResponse"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") + ) + cls: ClsType[_models.GroupIdInformationResponse] = kwargs.pop("cls", None) - request = build_list_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list.metadata['url'], + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -93,63 +110,68 @@ async def list( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('GroupIdInformationResponse', pipeline_response) + deserialized = self._deserialize("GroupIdInformationResponse", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - list.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateLinkResources"} # type: ignore - + list.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateLinkResources" + } @distributed_trace_async async def get( - self, - resource_group_name: str, - resource_name: str, - resource_id: str, - **kwargs: Any - ) -> "_models.GroupIdInformation": + self, resource_group_name: str, resource_name: str, resource_id: str, **kwargs: Any + ) -> _models.GroupIdInformation: """Get the specified private link resource for the given Digital Twin. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param resource_id: The name of the private link resource. + :param resource_id: The name of the private link resource. Required. :type resource_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: GroupIdInformation, or the result of cls(response) + :return: GroupIdInformation or the result of cls(response) :rtype: ~azure.mgmt.digitaltwins.v2021_06_30_preview.models.GroupIdInformation - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.GroupIdInformation"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") + ) + cls: ClsType[_models.GroupIdInformation] = kwargs.pop("cls", None) - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, resource_id=resource_id, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -157,12 +179,13 @@ async def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('GroupIdInformation', pipeline_response) + deserialized = self._deserialize("GroupIdInformation", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateLinkResources/{resourceId}"} # type: ignore - + get.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateLinkResources/{resourceId}" + } diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/aio/operations/_time_series_database_connections_operations.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/aio/operations/_time_series_database_connections_operations.py index 53cf6cb2d3108..662108a46eb93 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/aio/operations/_time_series_database_connections_operations.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/aio/operations/_time_series_database_connections_operations.py @@ -6,96 +6,126 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar, Union +import sys +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models from ..._vendor import _convert_request -from ...operations._time_series_database_connections_operations import build_create_or_update_request_initial, build_delete_request_initial, build_get_request, build_list_request -T = TypeVar('T') +from ...operations._time_series_database_connections_operations import ( + build_create_or_update_request, + build_delete_request, + build_get_request, + build_list_request, +) + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class TimeSeriesDatabaseConnectionsOperations: - """TimeSeriesDatabaseConnectionsOperations 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 TimeSeriesDatabaseConnectionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.digitaltwins.v2021_06_30_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.digitaltwins.v2021_06_30_preview.aio.AzureDigitalTwinsManagementClient`'s + :attr:`time_series_database_connections` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list( - self, - resource_group_name: str, - resource_name: str, - **kwargs: Any - ) -> AsyncIterable["_models.TimeSeriesDatabaseConnectionListResult"]: + self, resource_group_name: str, resource_name: str, **kwargs: Any + ) -> AsyncIterable["_models.TimeSeriesDatabaseConnection"]: """Get all existing time series database connections for this DigitalTwins instance. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either TimeSeriesDatabaseConnectionListResult or the - result of cls(response) + :return: An iterator like instance of either TimeSeriesDatabaseConnection or the result of + cls(response) :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.digitaltwins.v2021_06_30_preview.models.TimeSeriesDatabaseConnectionListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.digitaltwins.v2021_06_30_preview.models.TimeSeriesDatabaseConnection] + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") + ) + cls: ClsType[_models.TimeSeriesDatabaseConnectionListResult] = kwargs.pop("cls", None) - cls = kwargs.pop('cls', None) # type: ClsType["_models.TimeSeriesDatabaseConnectionListResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list.metadata['url'], + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: - - request = build_list_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - resource_name=resource_name, - api_version=api_version, - template_url=next_link, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) @@ -106,16 +136,14 @@ async def extract_data(pipeline_response): deserialized = self._deserialize("TimeSeriesDatabaseConnectionListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -126,59 +154,63 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections"} # type: ignore + list.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections" + } @distributed_trace_async async def get( - self, - resource_group_name: str, - resource_name: str, - time_series_database_connection_name: str, - **kwargs: Any - ) -> "_models.TimeSeriesDatabaseConnection": + self, resource_group_name: str, resource_name: str, time_series_database_connection_name: str, **kwargs: Any + ) -> _models.TimeSeriesDatabaseConnection: """Get the description of an existing time series database connection. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param time_series_database_connection_name: Name of time series database connection. + :param time_series_database_connection_name: Name of time series database connection. Required. :type time_series_database_connection_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: TimeSeriesDatabaseConnection, or the result of cls(response) + :return: TimeSeriesDatabaseConnection or the result of cls(response) :rtype: ~azure.mgmt.digitaltwins.v2021_06_30_preview.models.TimeSeriesDatabaseConnection - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.TimeSeriesDatabaseConnection"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") + ) + cls: ClsType[_models.TimeSeriesDatabaseConnection] = kwargs.pop("cls", None) - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, time_series_database_connection_name=time_series_database_connection_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -186,72 +218,174 @@ async def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('TimeSeriesDatabaseConnection', pipeline_response) + deserialized = self._deserialize("TimeSeriesDatabaseConnection", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections/{timeSeriesDatabaseConnectionName}"} # type: ignore - + get.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections/{timeSeriesDatabaseConnectionName}" + } async def _create_or_update_initial( self, resource_group_name: str, resource_name: str, time_series_database_connection_name: str, - time_series_database_connection_description: "_models.TimeSeriesDatabaseConnection", + time_series_database_connection_description: Union[_models.TimeSeriesDatabaseConnection, IO], **kwargs: Any - ) -> "_models.TimeSeriesDatabaseConnection": - cls = kwargs.pop('cls', None) # type: ClsType["_models.TimeSeriesDatabaseConnection"] + ) -> _models.TimeSeriesDatabaseConnection: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(time_series_database_connection_description, 'TimeSeriesDatabaseConnection') - - request = build_create_or_update_request_initial( - subscription_id=self._config.subscription_id, + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") + ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.TimeSeriesDatabaseConnection] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(time_series_database_connection_description, (IO, bytes)): + _content = time_series_database_connection_description + else: + _json = self._serialize.body(time_series_database_connection_description, "TimeSeriesDatabaseConnection") + + request = build_create_or_update_request( resource_group_name=resource_group_name, resource_name=resource_name, time_series_database_connection_name=time_series_database_connection_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._create_or_update_initial.metadata['url'], + content=_content, + template_url=self._create_or_update_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('TimeSeriesDatabaseConnection', pipeline_response) + deserialized = self._deserialize("TimeSeriesDatabaseConnection", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('TimeSeriesDatabaseConnection', pipeline_response) + deserialized = self._deserialize("TimeSeriesDatabaseConnection", pipeline_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized + return deserialized # type: ignore + + _create_or_update_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections/{timeSeriesDatabaseConnectionName}" + } + + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + time_series_database_connection_name: str, + time_series_database_connection_description: _models.TimeSeriesDatabaseConnection, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.TimeSeriesDatabaseConnection]: + """Create or update a time series database connection. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param time_series_database_connection_name: Name of time series database connection. Required. + :type time_series_database_connection_name: str + :param time_series_database_connection_description: The time series database connection + description. Required. + :type time_series_database_connection_description: + ~azure.mgmt.digitaltwins.v2021_06_30_preview.models.TimeSeriesDatabaseConnection + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either TimeSeriesDatabaseConnection or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2021_06_30_preview.models.TimeSeriesDatabaseConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ - _create_or_update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections/{timeSeriesDatabaseConnectionName}"} # type: ignore + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + time_series_database_connection_name: str, + time_series_database_connection_description: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.TimeSeriesDatabaseConnection]: + """Create or update a time series database connection. + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param time_series_database_connection_name: Name of time series database connection. Required. + :type time_series_database_connection_name: str + :param time_series_database_connection_description: The time series database connection + description. Required. + :type time_series_database_connection_description: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either TimeSeriesDatabaseConnection or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2021_06_30_preview.models.TimeSeriesDatabaseConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace_async async def begin_create_or_update( @@ -259,22 +393,25 @@ async def begin_create_or_update( resource_group_name: str, resource_name: str, time_series_database_connection_name: str, - time_series_database_connection_description: "_models.TimeSeriesDatabaseConnection", + time_series_database_connection_description: Union[_models.TimeSeriesDatabaseConnection, IO], **kwargs: Any - ) -> AsyncLROPoller["_models.TimeSeriesDatabaseConnection"]: + ) -> AsyncLROPoller[_models.TimeSeriesDatabaseConnection]: """Create or update a time series database connection. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param time_series_database_connection_name: Name of time series database connection. + :param time_series_database_connection_name: Name of time series database connection. Required. :type time_series_database_connection_name: str :param time_series_database_connection_description: The time series database connection - description. + description. Is either a model type or a IO type. Required. :type time_series_database_connection_description: - ~azure.mgmt.digitaltwins.v2021_06_30_preview.models.TimeSeriesDatabaseConnection + ~azure.mgmt.digitaltwins.v2021_06_30_preview.models.TimeSeriesDatabaseConnection or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for @@ -287,17 +424,19 @@ async def begin_create_or_update( result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2021_06_30_preview.models.TimeSeriesDatabaseConnection] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.TimeSeriesDatabaseConnection"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.TimeSeriesDatabaseConnection] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = await self._create_or_update_initial( resource_group_name=resource_group_name, @@ -306,102 +445,109 @@ async def begin_create_or_update( time_series_database_connection_description=time_series_database_connection_description, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('TimeSeriesDatabaseConnection', pipeline_response) + deserialized = self._deserialize("TimeSeriesDatabaseConnection", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - begin_create_or_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections/{timeSeriesDatabaseConnectionName}"} # type: ignore + begin_create_or_update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections/{timeSeriesDatabaseConnectionName}" + } async def _delete_initial( - self, - resource_group_name: str, - resource_name: str, - time_series_database_connection_name: str, - **kwargs: Any - ) -> Optional["_models.TimeSeriesDatabaseConnection"]: - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.TimeSeriesDatabaseConnection"]] + self, resource_group_name: str, resource_name: str, time_series_database_connection_name: str, **kwargs: Any + ) -> Optional[_models.TimeSeriesDatabaseConnection]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - request = build_delete_request_initial( - subscription_id=self._config.subscription_id, + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") + ) + cls: ClsType[Optional[_models.TimeSeriesDatabaseConnection]] = kwargs.pop("cls", None) + + request = build_delete_request( resource_group_name=resource_group_name, resource_name=resource_name, time_series_database_connection_name=time_series_database_connection_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._delete_initial.metadata['url'], + template_url=self._delete_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('TimeSeriesDatabaseConnection', pipeline_response) + deserialized = self._deserialize("TimeSeriesDatabaseConnection", pipeline_response) if response.status_code == 202: - deserialized = self._deserialize('TimeSeriesDatabaseConnection', pipeline_response) + deserialized = self._deserialize("TimeSeriesDatabaseConnection", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _delete_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections/{timeSeriesDatabaseConnectionName}"} # type: ignore - + _delete_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections/{timeSeriesDatabaseConnectionName}" + } @distributed_trace_async async def begin_delete( - self, - resource_group_name: str, - resource_name: str, - time_series_database_connection_name: str, - **kwargs: Any - ) -> AsyncLROPoller["_models.TimeSeriesDatabaseConnection"]: + self, resource_group_name: str, resource_name: str, time_series_database_connection_name: str, **kwargs: Any + ) -> AsyncLROPoller[_models.TimeSeriesDatabaseConnection]: """Delete a time series database connection. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param time_series_database_connection_name: Name of time series database connection. + :param time_series_database_connection_name: Name of time series database connection. Required. :type time_series_database_connection_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. @@ -415,45 +561,52 @@ async def begin_delete( result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2021_06_30_preview.models.TimeSeriesDatabaseConnection] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.TimeSeriesDatabaseConnection"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + cls: ClsType[_models.TimeSeriesDatabaseConnection] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = await self._delete_initial( resource_group_name=resource_group_name, resource_name=resource_name, time_series_database_connection_name=time_series_database_connection_name, api_version=api_version, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('TimeSeriesDatabaseConnection', pipeline_response) + deserialized = self._deserialize("TimeSeriesDatabaseConnection", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - begin_delete.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections/{timeSeriesDatabaseConnectionName}"} # type: ignore + begin_delete.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections/{timeSeriesDatabaseConnectionName}" + } diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/models/__init__.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/models/__init__.py index 3893252166778..1816c624f2c49 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/models/__init__.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/models/__init__.py @@ -41,67 +41,69 @@ from ._models_py3 import TimeSeriesDatabaseConnectionListResult from ._models_py3 import TimeSeriesDatabaseConnectionProperties - -from ._azure_digital_twins_management_client_enums import ( - AuthenticationType, - ConnectionPropertiesProvisioningState, - ConnectionType, - CreatedByType, - DigitalTwinsIdentityType, - EndpointProvisioningState, - EndpointType, - PrivateLinkServiceConnectionStatus, - ProvisioningState, - PublicNetworkAccess, - Reason, - TimeSeriesDatabaseConnectionState, -) +from ._azure_digital_twins_management_client_enums import AuthenticationType +from ._azure_digital_twins_management_client_enums import ConnectionPropertiesProvisioningState +from ._azure_digital_twins_management_client_enums import ConnectionType +from ._azure_digital_twins_management_client_enums import CreatedByType +from ._azure_digital_twins_management_client_enums import DigitalTwinsIdentityType +from ._azure_digital_twins_management_client_enums import EndpointProvisioningState +from ._azure_digital_twins_management_client_enums import EndpointType +from ._azure_digital_twins_management_client_enums import PrivateLinkServiceConnectionStatus +from ._azure_digital_twins_management_client_enums import ProvisioningState +from ._azure_digital_twins_management_client_enums import PublicNetworkAccess +from ._azure_digital_twins_management_client_enums import Reason +from ._azure_digital_twins_management_client_enums import TimeSeriesDatabaseConnectionState +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk __all__ = [ - 'AzureDataExplorerConnectionProperties', - 'CheckNameRequest', - 'CheckNameResult', - 'ConnectionProperties', - 'ConnectionPropertiesPrivateLinkServiceConnectionState', - 'ConnectionState', - 'DigitalTwinsDescription', - 'DigitalTwinsDescriptionListResult', - 'DigitalTwinsEndpointResource', - 'DigitalTwinsEndpointResourceListResult', - 'DigitalTwinsEndpointResourceProperties', - 'DigitalTwinsIdentity', - 'DigitalTwinsPatchDescription', - 'DigitalTwinsPatchProperties', - 'DigitalTwinsResource', - 'ErrorDefinition', - 'ErrorResponse', - 'EventGrid', - 'EventHub', - 'ExternalResource', - 'GroupIdInformation', - 'GroupIdInformationProperties', - 'GroupIdInformationResponse', - 'Operation', - 'OperationDisplay', - 'OperationListResult', - 'PrivateEndpoint', - 'PrivateEndpointConnection', - 'PrivateEndpointConnectionsResponse', - 'ServiceBus', - 'SystemData', - 'TimeSeriesDatabaseConnection', - 'TimeSeriesDatabaseConnectionListResult', - 'TimeSeriesDatabaseConnectionProperties', - 'AuthenticationType', - 'ConnectionPropertiesProvisioningState', - 'ConnectionType', - 'CreatedByType', - 'DigitalTwinsIdentityType', - 'EndpointProvisioningState', - 'EndpointType', - 'PrivateLinkServiceConnectionStatus', - 'ProvisioningState', - 'PublicNetworkAccess', - 'Reason', - 'TimeSeriesDatabaseConnectionState', + "AzureDataExplorerConnectionProperties", + "CheckNameRequest", + "CheckNameResult", + "ConnectionProperties", + "ConnectionPropertiesPrivateLinkServiceConnectionState", + "ConnectionState", + "DigitalTwinsDescription", + "DigitalTwinsDescriptionListResult", + "DigitalTwinsEndpointResource", + "DigitalTwinsEndpointResourceListResult", + "DigitalTwinsEndpointResourceProperties", + "DigitalTwinsIdentity", + "DigitalTwinsPatchDescription", + "DigitalTwinsPatchProperties", + "DigitalTwinsResource", + "ErrorDefinition", + "ErrorResponse", + "EventGrid", + "EventHub", + "ExternalResource", + "GroupIdInformation", + "GroupIdInformationProperties", + "GroupIdInformationResponse", + "Operation", + "OperationDisplay", + "OperationListResult", + "PrivateEndpoint", + "PrivateEndpointConnection", + "PrivateEndpointConnectionsResponse", + "ServiceBus", + "SystemData", + "TimeSeriesDatabaseConnection", + "TimeSeriesDatabaseConnectionListResult", + "TimeSeriesDatabaseConnectionProperties", + "AuthenticationType", + "ConnectionPropertiesProvisioningState", + "ConnectionType", + "CreatedByType", + "DigitalTwinsIdentityType", + "EndpointProvisioningState", + "EndpointType", + "PrivateLinkServiceConnectionStatus", + "ProvisioningState", + "PublicNetworkAccess", + "Reason", + "TimeSeriesDatabaseConnectionState", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/models/_azure_digital_twins_management_client_enums.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/models/_azure_digital_twins_management_client_enums.py index 08e58780ab8ea..0bf112301ae10 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/models/_azure_digital_twins_management_client_enums.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/models/_azure_digital_twins_management_client_enums.py @@ -7,11 +7,10 @@ # -------------------------------------------------------------------------- from enum import Enum -from six import with_metaclass from azure.core import CaseInsensitiveEnumMeta -class AuthenticationType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): +class AuthenticationType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Specifies the authentication type being used for connecting to the endpoint. Defaults to 'KeyBased'. If 'KeyBased' is selected, a connection string must be specified (at least the primary connection string). If 'IdentityBased' is select, the endpointUri and entityPath @@ -21,31 +20,32 @@ class AuthenticationType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): KEY_BASED = "KeyBased" IDENTITY_BASED = "IdentityBased" -class ConnectionPropertiesProvisioningState(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The provisioning state. - """ + +class ConnectionPropertiesProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The provisioning state.""" PENDING = "Pending" APPROVED = "Approved" REJECTED = "Rejected" DISCONNECTED = "Disconnected" -class ConnectionType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The type of time series connection resource. - """ + +class ConnectionType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of time series connection resource.""" AZURE_DATA_EXPLORER = "AzureDataExplorer" -class CreatedByType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The type of identity that created the resource. - """ + +class CreatedByType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of identity that created the resource.""" USER = "User" APPLICATION = "Application" MANAGED_IDENTITY = "ManagedIdentity" KEY = "Key" -class DigitalTwinsIdentityType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): + +class DigitalTwinsIdentityType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The type of Managed Identity used by the DigitalTwinsInstance. Only SystemAssigned is supported. """ @@ -53,9 +53,9 @@ class DigitalTwinsIdentityType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum NONE = "None" SYSTEM_ASSIGNED = "SystemAssigned" -class EndpointProvisioningState(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The provisioning state. - """ + +class EndpointProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The provisioning state.""" PROVISIONING = "Provisioning" DELETING = "Deleting" @@ -69,26 +69,26 @@ class EndpointProvisioningState(with_metaclass(CaseInsensitiveEnumMeta, str, Enu MOVING = "Moving" DISABLED = "Disabled" -class EndpointType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The type of Digital Twins endpoint - """ + +class EndpointType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of Digital Twins endpoint.""" EVENT_HUB = "EventHub" EVENT_GRID = "EventGrid" SERVICE_BUS = "ServiceBus" -class PrivateLinkServiceConnectionStatus(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The status of a private endpoint connection. - """ + +class PrivateLinkServiceConnectionStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The status of a private endpoint connection.""" PENDING = "Pending" APPROVED = "Approved" REJECTED = "Rejected" DISCONNECTED = "Disconnected" -class ProvisioningState(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The provisioning state. - """ + +class ProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The provisioning state.""" PROVISIONING = "Provisioning" DELETING = "Deleting" @@ -102,23 +102,23 @@ class ProvisioningState(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): RESTORING = "Restoring" MOVING = "Moving" -class PublicNetworkAccess(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """Public network access for the DigitalTwinsInstance. - """ + +class PublicNetworkAccess(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Public network access for the DigitalTwinsInstance.""" ENABLED = "Enabled" DISABLED = "Disabled" -class Reason(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """Message providing the reason why the given name is invalid. - """ + +class Reason(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Message providing the reason why the given name is invalid.""" INVALID = "Invalid" ALREADY_EXISTS = "AlreadyExists" -class TimeSeriesDatabaseConnectionState(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The provisioning state. - """ + +class TimeSeriesDatabaseConnectionState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The provisioning state.""" PROVISIONING = "Provisioning" DELETING = "Deleting" diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/models/_models_py3.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/models/_models_py3.py index 1e83c019be9fd..c6f0c046f0fff 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/models/_models_py3.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/models/_models_py3.py @@ -1,4 +1,5 @@ # coding=utf-8 +# pylint: disable=too-many-lines # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. @@ -7,57 +8,52 @@ # -------------------------------------------------------------------------- import datetime -from typing import Dict, List, Optional, Union +from typing import Dict, List, Optional, TYPE_CHECKING, Union -from azure.core.exceptions import HttpResponseError -import msrest.serialization +from ... import _serialization -from ._azure_digital_twins_management_client_enums import * +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from .. import models as _models -class TimeSeriesDatabaseConnectionProperties(msrest.serialization.Model): +class TimeSeriesDatabaseConnectionProperties(_serialization.Model): """Properties of a time series database connection resource. - You probably want to use the sub-classes and not this class directly. Known - sub-classes are: AzureDataExplorerConnectionProperties. + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + AzureDataExplorerConnectionProperties Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. - :ivar connection_type: Required. The type of time series connection resource.Constant filled by - server. Possible values include: "AzureDataExplorer". + :ivar connection_type: The type of time series connection resource. Required. + "AzureDataExplorer" :vartype connection_type: str or ~azure.mgmt.digitaltwins.v2021_06_30_preview.models.ConnectionType - :ivar provisioning_state: The provisioning state. Possible values include: "Provisioning", - "Deleting", "Succeeded", "Failed", "Canceled", "Deleted", "Warning", "Suspending", "Restoring", - "Moving", "Disabled". + :ivar provisioning_state: The provisioning state. Known values are: "Provisioning", "Deleting", + "Succeeded", "Failed", "Canceled", "Deleted", "Warning", "Suspending", "Restoring", "Moving", + and "Disabled". :vartype provisioning_state: str or ~azure.mgmt.digitaltwins.v2021_06_30_preview.models.TimeSeriesDatabaseConnectionState """ _validation = { - 'connection_type': {'required': True}, - 'provisioning_state': {'readonly': True}, + "connection_type": {"required": True}, + "provisioning_state": {"readonly": True}, } _attribute_map = { - 'connection_type': {'key': 'connectionType', 'type': 'str'}, - 'provisioning_state': {'key': 'provisioningState', 'type': 'str'}, + "connection_type": {"key": "connectionType", "type": "str"}, + "provisioning_state": {"key": "provisioningState", "type": "str"}, } - _subtype_map = { - 'connection_type': {'AzureDataExplorer': 'AzureDataExplorerConnectionProperties'} - } + _subtype_map = {"connection_type": {"AzureDataExplorer": "AzureDataExplorerConnectionProperties"}} - def __init__( - self, - **kwargs - ): - """ - """ - super(TimeSeriesDatabaseConnectionProperties, self).__init__(**kwargs) - self.connection_type = None # type: Optional[str] + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.connection_type: Optional[str] = None self.provisioning_state = None @@ -68,30 +64,30 @@ class AzureDataExplorerConnectionProperties(TimeSeriesDatabaseConnectionProperti All required parameters must be populated in order to send to Azure. - :ivar connection_type: Required. The type of time series connection resource.Constant filled by - server. Possible values include: "AzureDataExplorer". + :ivar connection_type: The type of time series connection resource. Required. + "AzureDataExplorer" :vartype connection_type: str or ~azure.mgmt.digitaltwins.v2021_06_30_preview.models.ConnectionType - :ivar provisioning_state: The provisioning state. Possible values include: "Provisioning", - "Deleting", "Succeeded", "Failed", "Canceled", "Deleted", "Warning", "Suspending", "Restoring", - "Moving", "Disabled". + :ivar provisioning_state: The provisioning state. Known values are: "Provisioning", "Deleting", + "Succeeded", "Failed", "Canceled", "Deleted", "Warning", "Suspending", "Restoring", "Moving", + and "Disabled". :vartype provisioning_state: str or ~azure.mgmt.digitaltwins.v2021_06_30_preview.models.TimeSeriesDatabaseConnectionState - :ivar adx_resource_id: Required. The resource ID of the Azure Data Explorer cluster. + :ivar adx_resource_id: The resource ID of the Azure Data Explorer cluster. Required. :vartype adx_resource_id: str - :ivar adx_endpoint_uri: Required. The URI of the Azure Data Explorer endpoint. + :ivar adx_endpoint_uri: The URI of the Azure Data Explorer endpoint. Required. :vartype adx_endpoint_uri: str - :ivar adx_database_name: Required. The name of the Azure Data Explorer database. + :ivar adx_database_name: The name of the Azure Data Explorer database. Required. :vartype adx_database_name: str - :ivar adx_table_name: The name of the Azure Data Explorer table. + :ivar adx_table_name: The name of the Azure Data Explorer table. Defaults to AdtPropertyEvents. :vartype adx_table_name: str - :ivar event_hub_endpoint_uri: Required. The URL of the EventHub namespace for identity-based - authentication. It must include the protocol sb://. + :ivar event_hub_endpoint_uri: The URL of the EventHub namespace for identity-based + authentication. It must include the protocol sb://. Required. :vartype event_hub_endpoint_uri: str - :ivar event_hub_entity_path: Required. The EventHub name in the EventHub namespace for - identity-based authentication. + :ivar event_hub_entity_path: The EventHub name in the EventHub namespace for identity-based + authentication. Required. :vartype event_hub_entity_path: str - :ivar event_hub_namespace_resource_id: Required. The resource ID of the EventHub namespace. + :ivar event_hub_namespace_resource_id: The resource ID of the EventHub namespace. Required. :vartype event_hub_namespace_resource_id: str :ivar event_hub_consumer_group: The EventHub consumer group to use when ADX reads from EventHub. Defaults to $Default. @@ -99,27 +95,27 @@ class AzureDataExplorerConnectionProperties(TimeSeriesDatabaseConnectionProperti """ _validation = { - 'connection_type': {'required': True}, - 'provisioning_state': {'readonly': True}, - 'adx_resource_id': {'required': True}, - 'adx_endpoint_uri': {'required': True}, - 'adx_database_name': {'required': True}, - 'event_hub_endpoint_uri': {'required': True}, - 'event_hub_entity_path': {'required': True}, - 'event_hub_namespace_resource_id': {'required': True}, + "connection_type": {"required": True}, + "provisioning_state": {"readonly": True}, + "adx_resource_id": {"required": True}, + "adx_endpoint_uri": {"required": True}, + "adx_database_name": {"required": True}, + "event_hub_endpoint_uri": {"required": True}, + "event_hub_entity_path": {"required": True}, + "event_hub_namespace_resource_id": {"required": True}, } _attribute_map = { - 'connection_type': {'key': 'connectionType', 'type': 'str'}, - 'provisioning_state': {'key': 'provisioningState', 'type': 'str'}, - 'adx_resource_id': {'key': 'adxResourceId', 'type': 'str'}, - 'adx_endpoint_uri': {'key': 'adxEndpointUri', 'type': 'str'}, - 'adx_database_name': {'key': 'adxDatabaseName', 'type': 'str'}, - 'adx_table_name': {'key': 'adxTableName', 'type': 'str'}, - 'event_hub_endpoint_uri': {'key': 'eventHubEndpointUri', 'type': 'str'}, - 'event_hub_entity_path': {'key': 'eventHubEntityPath', 'type': 'str'}, - 'event_hub_namespace_resource_id': {'key': 'eventHubNamespaceResourceId', 'type': 'str'}, - 'event_hub_consumer_group': {'key': 'eventHubConsumerGroup', 'type': 'str'}, + "connection_type": {"key": "connectionType", "type": "str"}, + "provisioning_state": {"key": "provisioningState", "type": "str"}, + "adx_resource_id": {"key": "adxResourceId", "type": "str"}, + "adx_endpoint_uri": {"key": "adxEndpointUri", "type": "str"}, + "adx_database_name": {"key": "adxDatabaseName", "type": "str"}, + "adx_table_name": {"key": "adxTableName", "type": "str"}, + "event_hub_endpoint_uri": {"key": "eventHubEndpointUri", "type": "str"}, + "event_hub_entity_path": {"key": "eventHubEntityPath", "type": "str"}, + "event_hub_namespace_resource_id": {"key": "eventHubNamespaceResourceId", "type": "str"}, + "event_hub_consumer_group": {"key": "eventHubConsumerGroup", "type": "str"}, } def __init__( @@ -131,33 +127,34 @@ def __init__( event_hub_endpoint_uri: str, event_hub_entity_path: str, event_hub_namespace_resource_id: str, - adx_table_name: Optional[str] = None, - event_hub_consumer_group: Optional[str] = None, + adx_table_name: str = "AdtPropertyEvents", + event_hub_consumer_group: str = "$Default", **kwargs ): """ - :keyword adx_resource_id: Required. The resource ID of the Azure Data Explorer cluster. + :keyword adx_resource_id: The resource ID of the Azure Data Explorer cluster. Required. :paramtype adx_resource_id: str - :keyword adx_endpoint_uri: Required. The URI of the Azure Data Explorer endpoint. + :keyword adx_endpoint_uri: The URI of the Azure Data Explorer endpoint. Required. :paramtype adx_endpoint_uri: str - :keyword adx_database_name: Required. The name of the Azure Data Explorer database. + :keyword adx_database_name: The name of the Azure Data Explorer database. Required. :paramtype adx_database_name: str - :keyword adx_table_name: The name of the Azure Data Explorer table. + :keyword adx_table_name: The name of the Azure Data Explorer table. Defaults to + AdtPropertyEvents. :paramtype adx_table_name: str - :keyword event_hub_endpoint_uri: Required. The URL of the EventHub namespace for identity-based - authentication. It must include the protocol sb://. + :keyword event_hub_endpoint_uri: The URL of the EventHub namespace for identity-based + authentication. It must include the protocol sb://. Required. :paramtype event_hub_endpoint_uri: str - :keyword event_hub_entity_path: Required. The EventHub name in the EventHub namespace for - identity-based authentication. + :keyword event_hub_entity_path: The EventHub name in the EventHub namespace for identity-based + authentication. Required. :paramtype event_hub_entity_path: str - :keyword event_hub_namespace_resource_id: Required. The resource ID of the EventHub namespace. + :keyword event_hub_namespace_resource_id: The resource ID of the EventHub namespace. Required. :paramtype event_hub_namespace_resource_id: str :keyword event_hub_consumer_group: The EventHub consumer group to use when ADX reads from EventHub. Defaults to $Default. :paramtype event_hub_consumer_group: str """ - super(AzureDataExplorerConnectionProperties, self).__init__(**kwargs) - self.connection_type = 'AzureDataExplorer' # type: str + super().__init__(**kwargs) + self.connection_type: str = "AzureDataExplorer" self.adx_resource_id = adx_resource_id self.adx_endpoint_uri = adx_endpoint_uri self.adx_database_name = adx_database_name @@ -168,47 +165,42 @@ def __init__( self.event_hub_consumer_group = event_hub_consumer_group -class CheckNameRequest(msrest.serialization.Model): +class CheckNameRequest(_serialization.Model): """The result returned from a database check name availability request. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. - :ivar name: Required. Resource name. + :ivar name: Resource name. Required. :vartype name: str :ivar type: The type of resource, for instance Microsoft.DigitalTwins/digitalTwinsInstances. - Has constant value: "Microsoft.DigitalTwins/digitalTwinsInstances". + Required. Default value is "Microsoft.DigitalTwins/digitalTwinsInstances". :vartype type: str """ _validation = { - 'name': {'required': True}, - 'type': {'required': True, 'constant': True}, + "name": {"required": True}, + "type": {"required": True, "constant": True}, } _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, } type = "Microsoft.DigitalTwins/digitalTwinsInstances" - def __init__( - self, - *, - name: str, - **kwargs - ): + def __init__(self, *, name: str, **kwargs): """ - :keyword name: Required. Resource name. + :keyword name: Resource name. Required. :paramtype name: str """ - super(CheckNameRequest, self).__init__(**kwargs) + super().__init__(**kwargs) self.name = name -class CheckNameResult(msrest.serialization.Model): +class CheckNameResult(_serialization.Model): """The result returned from a check name availability request. :ivar name_available: Specifies a Boolean value that indicates if the name is available. @@ -216,15 +208,15 @@ class CheckNameResult(msrest.serialization.Model): :ivar message: Message indicating an unavailable name due to a conflict, or a description of the naming rules that are violated. :vartype message: str - :ivar reason: Message providing the reason why the given name is invalid. Possible values - include: "Invalid", "AlreadyExists". + :ivar reason: Message providing the reason why the given name is invalid. Known values are: + "Invalid" and "AlreadyExists". :vartype reason: str or ~azure.mgmt.digitaltwins.v2021_06_30_preview.models.Reason """ _attribute_map = { - 'name_available': {'key': 'nameAvailable', 'type': 'bool'}, - 'message': {'key': 'message', 'type': 'str'}, - 'reason': {'key': 'reason', 'type': 'str'}, + "name_available": {"key": "nameAvailable", "type": "bool"}, + "message": {"key": "message", "type": "str"}, + "reason": {"key": "reason", "type": "str"}, } def __init__( @@ -232,7 +224,7 @@ def __init__( *, name_available: Optional[bool] = None, message: Optional[str] = None, - reason: Optional[Union[str, "Reason"]] = None, + reason: Optional[Union[str, "_models.Reason"]] = None, **kwargs ): """ @@ -241,23 +233,23 @@ def __init__( :keyword message: Message indicating an unavailable name due to a conflict, or a description of the naming rules that are violated. :paramtype message: str - :keyword reason: Message providing the reason why the given name is invalid. Possible values - include: "Invalid", "AlreadyExists". + :keyword reason: Message providing the reason why the given name is invalid. Known values are: + "Invalid" and "AlreadyExists". :paramtype reason: str or ~azure.mgmt.digitaltwins.v2021_06_30_preview.models.Reason """ - super(CheckNameResult, self).__init__(**kwargs) + super().__init__(**kwargs) self.name_available = name_available self.message = message self.reason = reason -class ConnectionProperties(msrest.serialization.Model): +class ConnectionProperties(_serialization.Model): """The properties of a private endpoint connection. Variables are only populated by the server, and will be ignored when sending a request. - :ivar provisioning_state: The provisioning state. Possible values include: "Pending", - "Approved", "Rejected", "Disconnected". + :ivar provisioning_state: The provisioning state. Known values are: "Pending", "Approved", + "Rejected", and "Disconnected". :vartype provisioning_state: str or ~azure.mgmt.digitaltwins.v2021_06_30_preview.models.ConnectionPropertiesProvisioningState :ivar private_endpoint: The private endpoint. @@ -270,22 +262,27 @@ class ConnectionProperties(msrest.serialization.Model): """ _validation = { - 'provisioning_state': {'readonly': True}, + "provisioning_state": {"readonly": True}, } _attribute_map = { - 'provisioning_state': {'key': 'provisioningState', 'type': 'str'}, - 'private_endpoint': {'key': 'privateEndpoint', 'type': 'PrivateEndpoint'}, - 'group_ids': {'key': 'groupIds', 'type': '[str]'}, - 'private_link_service_connection_state': {'key': 'privateLinkServiceConnectionState', 'type': 'ConnectionPropertiesPrivateLinkServiceConnectionState'}, + "provisioning_state": {"key": "provisioningState", "type": "str"}, + "private_endpoint": {"key": "privateEndpoint", "type": "PrivateEndpoint"}, + "group_ids": {"key": "groupIds", "type": "[str]"}, + "private_link_service_connection_state": { + "key": "privateLinkServiceConnectionState", + "type": "ConnectionPropertiesPrivateLinkServiceConnectionState", + }, } def __init__( self, *, - private_endpoint: Optional["PrivateEndpoint"] = None, + private_endpoint: Optional["_models.PrivateEndpoint"] = None, group_ids: Optional[List[str]] = None, - private_link_service_connection_state: Optional["ConnectionPropertiesPrivateLinkServiceConnectionState"] = None, + private_link_service_connection_state: Optional[ + "_models.ConnectionPropertiesPrivateLinkServiceConnectionState" + ] = None, **kwargs ): """ @@ -298,60 +295,60 @@ def __init__( :paramtype private_link_service_connection_state: ~azure.mgmt.digitaltwins.v2021_06_30_preview.models.ConnectionPropertiesPrivateLinkServiceConnectionState """ - super(ConnectionProperties, self).__init__(**kwargs) + super().__init__(**kwargs) self.provisioning_state = None self.private_endpoint = private_endpoint self.group_ids = group_ids self.private_link_service_connection_state = private_link_service_connection_state -class ConnectionState(msrest.serialization.Model): +class ConnectionState(_serialization.Model): """The current state of a private endpoint connection. All required parameters must be populated in order to send to Azure. - :ivar status: Required. The status of a private endpoint connection. Possible values include: - "Pending", "Approved", "Rejected", "Disconnected". + :ivar status: The status of a private endpoint connection. Required. Known values are: + "Pending", "Approved", "Rejected", and "Disconnected". :vartype status: str or ~azure.mgmt.digitaltwins.v2021_06_30_preview.models.PrivateLinkServiceConnectionStatus - :ivar description: Required. The description for the current state of a private endpoint - connection. + :ivar description: The description for the current state of a private endpoint connection. + Required. :vartype description: str :ivar actions_required: Actions required for a private endpoint connection. :vartype actions_required: str """ _validation = { - 'status': {'required': True}, - 'description': {'required': True}, + "status": {"required": True}, + "description": {"required": True}, } _attribute_map = { - 'status': {'key': 'status', 'type': 'str'}, - 'description': {'key': 'description', 'type': 'str'}, - 'actions_required': {'key': 'actionsRequired', 'type': 'str'}, + "status": {"key": "status", "type": "str"}, + "description": {"key": "description", "type": "str"}, + "actions_required": {"key": "actionsRequired", "type": "str"}, } def __init__( self, *, - status: Union[str, "PrivateLinkServiceConnectionStatus"], + status: Union[str, "_models.PrivateLinkServiceConnectionStatus"], description: str, actions_required: Optional[str] = None, **kwargs ): """ - :keyword status: Required. The status of a private endpoint connection. Possible values - include: "Pending", "Approved", "Rejected", "Disconnected". + :keyword status: The status of a private endpoint connection. Required. Known values are: + "Pending", "Approved", "Rejected", and "Disconnected". :paramtype status: str or ~azure.mgmt.digitaltwins.v2021_06_30_preview.models.PrivateLinkServiceConnectionStatus - :keyword description: Required. The description for the current state of a private endpoint - connection. + :keyword description: The description for the current state of a private endpoint connection. + Required. :paramtype description: str :keyword actions_required: Actions required for a private endpoint connection. :paramtype actions_required: str """ - super(ConnectionState, self).__init__(**kwargs) + super().__init__(**kwargs) self.status = status self.description = description self.actions_required = actions_required @@ -362,51 +359,51 @@ class ConnectionPropertiesPrivateLinkServiceConnectionState(ConnectionState): All required parameters must be populated in order to send to Azure. - :ivar status: Required. The status of a private endpoint connection. Possible values include: - "Pending", "Approved", "Rejected", "Disconnected". + :ivar status: The status of a private endpoint connection. Required. Known values are: + "Pending", "Approved", "Rejected", and "Disconnected". :vartype status: str or ~azure.mgmt.digitaltwins.v2021_06_30_preview.models.PrivateLinkServiceConnectionStatus - :ivar description: Required. The description for the current state of a private endpoint - connection. + :ivar description: The description for the current state of a private endpoint connection. + Required. :vartype description: str :ivar actions_required: Actions required for a private endpoint connection. :vartype actions_required: str """ _validation = { - 'status': {'required': True}, - 'description': {'required': True}, + "status": {"required": True}, + "description": {"required": True}, } _attribute_map = { - 'status': {'key': 'status', 'type': 'str'}, - 'description': {'key': 'description', 'type': 'str'}, - 'actions_required': {'key': 'actionsRequired', 'type': 'str'}, + "status": {"key": "status", "type": "str"}, + "description": {"key": "description", "type": "str"}, + "actions_required": {"key": "actionsRequired", "type": "str"}, } def __init__( self, *, - status: Union[str, "PrivateLinkServiceConnectionStatus"], + status: Union[str, "_models.PrivateLinkServiceConnectionStatus"], description: str, actions_required: Optional[str] = None, **kwargs ): """ - :keyword status: Required. The status of a private endpoint connection. Possible values - include: "Pending", "Approved", "Rejected", "Disconnected". + :keyword status: The status of a private endpoint connection. Required. Known values are: + "Pending", "Approved", "Rejected", and "Disconnected". :paramtype status: str or ~azure.mgmt.digitaltwins.v2021_06_30_preview.models.PrivateLinkServiceConnectionStatus - :keyword description: Required. The description for the current state of a private endpoint - connection. + :keyword description: The description for the current state of a private endpoint connection. + Required. :paramtype description: str :keyword actions_required: Actions required for a private endpoint connection. :paramtype actions_required: str """ - super(ConnectionPropertiesPrivateLinkServiceConnectionState, self).__init__(status=status, description=description, actions_required=actions_required, **kwargs) + super().__init__(status=status, description=description, actions_required=actions_required, **kwargs) -class DigitalTwinsResource(msrest.serialization.Model): +class DigitalTwinsResource(_serialization.Model): """The common properties of a DigitalTwinsInstance. Variables are only populated by the server, and will be ignored when sending a request. @@ -419,9 +416,9 @@ class DigitalTwinsResource(msrest.serialization.Model): :vartype name: str :ivar type: The resource type. :vartype type: str - :ivar location: Required. The resource location. + :ivar location: The resource location. Required. :vartype location: str - :ivar tags: A set of tags. The resource tags. + :ivar tags: The resource tags. :vartype tags: dict[str, str] :ivar identity: The managed identity for the DigitalTwinsInstance. :vartype identity: ~azure.mgmt.digitaltwins.v2021_06_30_preview.models.DigitalTwinsIdentity @@ -431,21 +428,21 @@ class DigitalTwinsResource(msrest.serialization.Model): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True, 'pattern': r'^(?!-)[A-Za-z0-9-]{3,63}(?= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False + def build_list_request( - subscription_id: str, - resource_group_name: str, - resource_name: str, - **kwargs: Any + resource_group_name: str, resource_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") + ) + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints", + ) # 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', max_length=90, min_length=1), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=63, min_length=3, pattern=r'^(?!-)[A-Za-z0-9-]{3,63}(? HttpRequest: - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") + ) + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}", + ) # 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', max_length=90, min_length=1), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=63, min_length=3, pattern=r'^(?!-)[A-Za-z0-9-]{3,63}(? HttpRequest: - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str - content_type = kwargs.pop('content_type', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") + ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}", + ) # 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', max_length=90, min_length=1), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=63, min_length=3, pattern=r'^(?!-)[A-Za-z0-9-]{3,63}(? HttpRequest: - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") + ) + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}", + ) # 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', max_length=90, min_length=1), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=63, min_length=3, pattern=r'^(?!-)[A-Za-z0-9-]{3,63}(? Iterable["_models.DigitalTwinsEndpointResourceListResult"]: + self, resource_group_name: str, resource_name: str, **kwargs: Any + ) -> Iterable["_models.DigitalTwinsEndpointResource"]: """Get DigitalTwinsInstance Endpoints. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either DigitalTwinsEndpointResourceListResult or the - result of cls(response) + :return: An iterator like instance of either DigitalTwinsEndpointResource or the result of + cls(response) :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.digitaltwins.v2021_06_30_preview.models.DigitalTwinsEndpointResourceListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.paging.ItemPaged[~azure.mgmt.digitaltwins.v2021_06_30_preview.models.DigitalTwinsEndpointResource] + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") + ) + cls: ClsType[_models.DigitalTwinsEndpointResourceListResult] = kwargs.pop("cls", None) - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsEndpointResourceListResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list.metadata['url'], + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: - - request = build_list_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - resource_name=resource_name, - api_version=api_version, - template_url=next_link, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) @@ -267,16 +328,14 @@ def extract_data(pipeline_response): deserialized = self._deserialize("DigitalTwinsEndpointResourceListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -287,59 +346,63 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints"} # type: ignore + list.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints" + } @distributed_trace def get( - self, - resource_group_name: str, - resource_name: str, - endpoint_name: str, - **kwargs: Any - ) -> "_models.DigitalTwinsEndpointResource": + self, resource_group_name: str, resource_name: str, endpoint_name: str, **kwargs: Any + ) -> _models.DigitalTwinsEndpointResource: """Get DigitalTwinsInstances Endpoint. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param endpoint_name: Name of Endpoint Resource. + :param endpoint_name: Name of Endpoint Resource. Required. :type endpoint_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: DigitalTwinsEndpointResource, or the result of cls(response) + :return: DigitalTwinsEndpointResource or the result of cls(response) :rtype: ~azure.mgmt.digitaltwins.v2021_06_30_preview.models.DigitalTwinsEndpointResource - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsEndpointResource"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") + ) + cls: ClsType[_models.DigitalTwinsEndpointResource] = kwargs.pop("cls", None) - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, endpoint_name=endpoint_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -347,72 +410,174 @@ def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('DigitalTwinsEndpointResource', pipeline_response) + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}"} # type: ignore - + get.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}" + } def _create_or_update_initial( self, resource_group_name: str, resource_name: str, endpoint_name: str, - endpoint_description: "_models.DigitalTwinsEndpointResource", + endpoint_description: Union[_models.DigitalTwinsEndpointResource, IO], **kwargs: Any - ) -> "_models.DigitalTwinsEndpointResource": - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsEndpointResource"] + ) -> _models.DigitalTwinsEndpointResource: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(endpoint_description, 'DigitalTwinsEndpointResource') - - request = build_create_or_update_request_initial( - subscription_id=self._config.subscription_id, + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") + ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DigitalTwinsEndpointResource] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(endpoint_description, (IO, bytes)): + _content = endpoint_description + else: + _json = self._serialize.body(endpoint_description, "DigitalTwinsEndpointResource") + + request = build_create_or_update_request( resource_group_name=resource_group_name, resource_name=resource_name, 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_initial.metadata['url'], + content=_content, + template_url=self._create_or_update_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('DigitalTwinsEndpointResource', pipeline_response) + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('DigitalTwinsEndpointResource', pipeline_response) + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized + return deserialized # type: ignore + + _create_or_update_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}" + } + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + endpoint_name: str, + endpoint_description: _models.DigitalTwinsEndpointResource, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.DigitalTwinsEndpointResource]: + """Create or update DigitalTwinsInstance endpoint. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param endpoint_name: Name of Endpoint Resource. Required. + :type endpoint_name: str + :param endpoint_description: The DigitalTwinsInstance endpoint metadata and security metadata. + Required. + :type endpoint_description: + ~azure.mgmt.digitaltwins.v2021_06_30_preview.models.DigitalTwinsEndpointResource + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either DigitalTwinsEndpointResource or the + result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2021_06_30_preview.models.DigitalTwinsEndpointResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ - _create_or_update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}"} # type: ignore + @overload + def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + endpoint_name: str, + endpoint_description: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.DigitalTwinsEndpointResource]: + """Create or update DigitalTwinsInstance endpoint. + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param endpoint_name: Name of Endpoint Resource. Required. + :type endpoint_name: str + :param endpoint_description: The DigitalTwinsInstance endpoint metadata and security metadata. + Required. + :type endpoint_description: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either DigitalTwinsEndpointResource or the + result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2021_06_30_preview.models.DigitalTwinsEndpointResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace def begin_create_or_update( @@ -420,21 +585,25 @@ def begin_create_or_update( resource_group_name: str, resource_name: str, endpoint_name: str, - endpoint_description: "_models.DigitalTwinsEndpointResource", + endpoint_description: Union[_models.DigitalTwinsEndpointResource, IO], **kwargs: Any - ) -> LROPoller["_models.DigitalTwinsEndpointResource"]: + ) -> LROPoller[_models.DigitalTwinsEndpointResource]: """Create or update DigitalTwinsInstance endpoint. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param endpoint_name: Name of Endpoint Resource. + :param endpoint_name: Name of Endpoint Resource. Required. :type endpoint_name: str :param endpoint_description: The DigitalTwinsInstance endpoint metadata and security metadata. + Is either a model type or a IO type. Required. :type endpoint_description: - ~azure.mgmt.digitaltwins.v2021_06_30_preview.models.DigitalTwinsEndpointResource + ~azure.mgmt.digitaltwins.v2021_06_30_preview.models.DigitalTwinsEndpointResource or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this @@ -447,17 +616,19 @@ def begin_create_or_update( result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2021_06_30_preview.models.DigitalTwinsEndpointResource] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsEndpointResource"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DigitalTwinsEndpointResource] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = self._create_or_update_initial( resource_group_name=resource_group_name, @@ -466,102 +637,109 @@ def begin_create_or_update( endpoint_description=endpoint_description, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('DigitalTwinsEndpointResource', pipeline_response) + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - begin_create_or_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}"} # type: ignore + begin_create_or_update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}" + } def _delete_initial( - self, - resource_group_name: str, - resource_name: str, - endpoint_name: str, - **kwargs: Any - ) -> Optional["_models.DigitalTwinsEndpointResource"]: - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.DigitalTwinsEndpointResource"]] + self, resource_group_name: str, resource_name: str, endpoint_name: str, **kwargs: Any + ) -> Optional[_models.DigitalTwinsEndpointResource]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - request = build_delete_request_initial( - subscription_id=self._config.subscription_id, + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") + ) + cls: ClsType[Optional[_models.DigitalTwinsEndpointResource]] = kwargs.pop("cls", None) + + request = build_delete_request( resource_group_name=resource_group_name, resource_name=resource_name, endpoint_name=endpoint_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._delete_initial.metadata['url'], + template_url=self._delete_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('DigitalTwinsEndpointResource', pipeline_response) + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) if response.status_code == 202: - deserialized = self._deserialize('DigitalTwinsEndpointResource', pipeline_response) + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _delete_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}"} # type: ignore - + _delete_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}" + } @distributed_trace def begin_delete( - self, - resource_group_name: str, - resource_name: str, - endpoint_name: str, - **kwargs: Any - ) -> LROPoller["_models.DigitalTwinsEndpointResource"]: + self, resource_group_name: str, resource_name: str, endpoint_name: str, **kwargs: Any + ) -> LROPoller[_models.DigitalTwinsEndpointResource]: """Delete a DigitalTwinsInstance endpoint. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param endpoint_name: Name of Endpoint Resource. + :param endpoint_name: Name of Endpoint Resource. Required. :type endpoint_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. @@ -575,45 +753,52 @@ def begin_delete( result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2021_06_30_preview.models.DigitalTwinsEndpointResource] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsEndpointResource"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + cls: ClsType[_models.DigitalTwinsEndpointResource] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = self._delete_initial( resource_group_name=resource_group_name, resource_name=resource_name, endpoint_name=endpoint_name, api_version=api_version, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('DigitalTwinsEndpointResource', pipeline_response) + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - begin_delete.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}"} # type: ignore + begin_delete.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}" + } diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/operations/_digital_twins_operations.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/operations/_digital_twins_operations.py index 243b138b9dcc5..7e807a5cac552 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/operations/_digital_twins_operations.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/operations/_digital_twins_operations.py @@ -6,361 +6,373 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Iterable, Optional, TypeVar, Union - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import sys +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models +from ..._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') -JSONType = Any + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_get_request( - subscription_id: str, - resource_group_name: str, - resource_name: str, - **kwargs: Any -) -> HttpRequest: - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str - accept = "application/json" +def build_get_request(resource_group_name: str, resource_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") + ) + accept = _headers.pop("Accept", "application/json") + # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}", + ) # 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', max_length=90, min_length=1), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=63, min_length=3, pattern=r'^(?!-)[A-Za-z0-9-]{3,63}(? HttpRequest: - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str - content_type = kwargs.pop('content_type', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") + ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}", + ) # 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', max_length=90, min_length=1), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=63, min_length=3, pattern=r'^(?!-)[A-Za-z0-9-]{3,63}(? HttpRequest: - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str - content_type = kwargs.pop('content_type', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") + ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}", + ) # 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', max_length=90, min_length=1), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=63, min_length=3, pattern=r'^(?!-)[A-Za-z0-9-]{3,63}(? HttpRequest: - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") + ) + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}", + ) # 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', max_length=90, min_length=1), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=63, min_length=3, pattern=r'^(?!-)[A-Za-z0-9-]{3,63}(? HttpRequest: - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str - accept = "application/json" +def build_list_request(subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") + ) + accept = _headers.pop("Accept", "application/json") + # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.DigitalTwins/digitalTwinsInstances") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.DigitalTwins/digitalTwinsInstances" + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # 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_resource_group_request( - subscription_id: str, - resource_group_name: str, - **kwargs: Any -) -> HttpRequest: - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str - accept = "application/json" +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: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") + ) + accept = _headers.pop("Accept", "application/json") + # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances", + ) # 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', max_length=90, min_length=1), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # 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_check_name_availability_request( - subscription_id: str, - location: str, - *, - json: JSONType = None, - content: Any = None, - **kwargs: Any -) -> HttpRequest: - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str - content_type = kwargs.pop('content_type', None) # type: Optional[str] - accept = "application/json" +def build_check_name_availability_request(location: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") + ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.DigitalTwins/locations/{location}/checkNameAvailability") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.DigitalTwins/locations/{location}/checkNameAvailability", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), - "location": _SERIALIZER.url("location", location, 'str', min_length=3), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "location": _SERIALIZER.url("location", location, "str", min_length=3), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # 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) -class DigitalTwinsOperations(object): - """DigitalTwinsOperations 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 DigitalTwinsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.digitaltwins.v2021_06_30_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.digitaltwins.v2021_06_30_preview.AzureDigitalTwinsManagementClient`'s + :attr:`digital_twins` 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, - resource_group_name: str, - resource_name: str, - **kwargs: Any - ) -> "_models.DigitalTwinsDescription": + def get(self, resource_group_name: str, resource_name: str, **kwargs: Any) -> _models.DigitalTwinsDescription: """Get DigitalTwinsInstances resource. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: DigitalTwinsDescription, or the result of cls(response) + :return: DigitalTwinsDescription or the result of cls(response) :rtype: ~azure.mgmt.digitaltwins.v2021_06_30_preview.models.DigitalTwinsDescription - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescription"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") + ) + cls: ClsType[_models.DigitalTwinsDescription] = kwargs.pop("cls", None) - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -368,91 +380,193 @@ def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}"} # type: ignore - + get.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } def _create_or_update_initial( self, resource_group_name: str, resource_name: str, - digital_twins_create: "_models.DigitalTwinsDescription", + digital_twins_create: Union[_models.DigitalTwinsDescription, IO], **kwargs: Any - ) -> "_models.DigitalTwinsDescription": - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescription"] + ) -> _models.DigitalTwinsDescription: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + error_map.update(kwargs.pop("error_map", {}) or {}) - _json = self._serialize.body(digital_twins_create, 'DigitalTwinsDescription') + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - request = build_create_or_update_request_initial( - subscription_id=self._config.subscription_id, + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") + ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DigitalTwinsDescription] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(digital_twins_create, (IO, bytes)): + _content = digital_twins_create + else: + _json = self._serialize.body(digital_twins_create, "DigitalTwinsDescription") + + request = build_create_or_update_request( resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._create_or_update_initial.metadata['url'], + content=_content, + template_url=self._create_or_update_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized + return deserialized # type: ignore - _create_or_update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}"} # type: ignore + _create_or_update_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } + @overload + def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + digital_twins_create: _models.DigitalTwinsDescription, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.DigitalTwinsDescription]: + """Create or update the metadata of a DigitalTwinsInstance. The usual pattern to modify a property + is to retrieve the DigitalTwinsInstance and security metadata, and then combine them with the + modified values in a new body to update the DigitalTwinsInstance. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param digital_twins_create: The DigitalTwinsInstance and security metadata. Required. + :type digital_twins_create: + ~azure.mgmt.digitaltwins.v2021_06_30_preview.models.DigitalTwinsDescription + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either DigitalTwinsDescription or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2021_06_30_preview.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + digital_twins_create: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.DigitalTwinsDescription]: + """Create or update the metadata of a DigitalTwinsInstance. The usual pattern to modify a property + is to retrieve the DigitalTwinsInstance and security metadata, and then combine them with the + modified values in a new body to update the DigitalTwinsInstance. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param digital_twins_create: The DigitalTwinsInstance and security metadata. Required. + :type digital_twins_create: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either DigitalTwinsDescription or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2021_06_30_preview.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace def begin_create_or_update( self, resource_group_name: str, resource_name: str, - digital_twins_create: "_models.DigitalTwinsDescription", + digital_twins_create: Union[_models.DigitalTwinsDescription, IO], **kwargs: Any - ) -> LROPoller["_models.DigitalTwinsDescription"]: + ) -> LROPoller[_models.DigitalTwinsDescription]: """Create or update the metadata of a DigitalTwinsInstance. The usual pattern to modify a property is to retrieve the DigitalTwinsInstance and security metadata, and then combine them with the modified values in a new body to update the DigitalTwinsInstance. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param digital_twins_create: The DigitalTwinsInstance and security metadata. + :param digital_twins_create: The DigitalTwinsInstance and security metadata. Is either a model + type or a IO type. Required. :type digital_twins_create: - ~azure.mgmt.digitaltwins.v2021_06_30_preview.models.DigitalTwinsDescription + ~azure.mgmt.digitaltwins.v2021_06_30_preview.models.DigitalTwinsDescription or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this @@ -465,17 +579,19 @@ def begin_create_or_update( cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2021_06_30_preview.models.DigitalTwinsDescription] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescription"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DigitalTwinsDescription] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = self._create_or_update_initial( resource_group_name=resource_group_name, @@ -483,106 +599,135 @@ def begin_create_or_update( digital_twins_create=digital_twins_create, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - begin_create_or_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}"} # type: ignore + begin_create_or_update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } def _update_initial( self, resource_group_name: str, resource_name: str, - digital_twins_patch_description: "_models.DigitalTwinsPatchDescription", + digital_twins_patch_description: Union[_models.DigitalTwinsPatchDescription, IO], **kwargs: Any - ) -> "_models.DigitalTwinsDescription": - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescription"] + ) -> _models.DigitalTwinsDescription: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + error_map.update(kwargs.pop("error_map", {}) or {}) - _json = self._serialize.body(digital_twins_patch_description, 'DigitalTwinsPatchDescription') + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - request = build_update_request_initial( - subscription_id=self._config.subscription_id, + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") + ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DigitalTwinsDescription] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(digital_twins_patch_description, (IO, bytes)): + _content = digital_twins_patch_description + else: + _json = self._serialize.body(digital_twins_patch_description, "DigitalTwinsPatchDescription") + + request = build_update_request( resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._update_initial.metadata['url'], + content=_content, + template_url=self._update_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if response.status_code == 202: - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - _update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}"} # type: ignore + return deserialized # type: ignore + _update_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } - @distributed_trace + @overload def begin_update( self, resource_group_name: str, resource_name: str, - digital_twins_patch_description: "_models.DigitalTwinsPatchDescription", + digital_twins_patch_description: _models.DigitalTwinsPatchDescription, + *, + content_type: str = "application/json", **kwargs: Any - ) -> LROPoller["_models.DigitalTwinsDescription"]: + ) -> LROPoller[_models.DigitalTwinsDescription]: """Update metadata of DigitalTwinsInstance. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str :param digital_twins_patch_description: The DigitalTwinsInstance and security metadata. + Required. :type digital_twins_patch_description: ~azure.mgmt.digitaltwins.v2021_06_30_preview.models.DigitalTwinsPatchDescription + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this @@ -595,17 +740,94 @@ def begin_update( cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2021_06_30_preview.models.DigitalTwinsDescription] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescription"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval + + @overload + def begin_update( + self, + resource_group_name: str, + resource_name: str, + digital_twins_patch_description: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.DigitalTwinsDescription]: + """Update metadata of DigitalTwinsInstance. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param digital_twins_patch_description: The DigitalTwinsInstance and security metadata. + Required. + :type digital_twins_patch_description: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either DigitalTwinsDescription or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2021_06_30_preview.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_update( + self, + resource_group_name: str, + resource_name: str, + digital_twins_patch_description: Union[_models.DigitalTwinsPatchDescription, IO], + **kwargs: Any + ) -> LROPoller[_models.DigitalTwinsDescription]: + """Update metadata of DigitalTwinsInstance. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param digital_twins_patch_description: The DigitalTwinsInstance and security metadata. Is + either a model type or a IO type. Required. + :type digital_twins_patch_description: + ~azure.mgmt.digitaltwins.v2021_06_30_preview.models.DigitalTwinsPatchDescription or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either DigitalTwinsDescription or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2021_06_30_preview.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DigitalTwinsDescription] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = self._update_initial( resource_group_name=resource_group_name, @@ -613,97 +835,106 @@ def begin_update( digital_twins_patch_description=digital_twins_patch_description, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - begin_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}"} # type: ignore + begin_update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } def _delete_initial( - self, - resource_group_name: str, - resource_name: str, - **kwargs: Any - ) -> Optional["_models.DigitalTwinsDescription"]: - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.DigitalTwinsDescription"]] + self, resource_group_name: str, resource_name: str, **kwargs: Any + ) -> Optional[_models.DigitalTwinsDescription]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - request = build_delete_request_initial( - subscription_id=self._config.subscription_id, + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") + ) + cls: ClsType[Optional[_models.DigitalTwinsDescription]] = kwargs.pop("cls", None) + + request = build_delete_request( resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._delete_initial.metadata['url'], + template_url=self._delete_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if response.status_code == 202: - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _delete_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}"} # type: ignore - + _delete_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } @distributed_trace def begin_delete( - self, - resource_group_name: str, - resource_name: str, - **kwargs: Any - ) -> LROPoller["_models.DigitalTwinsDescription"]: + self, resource_group_name: str, resource_name: str, **kwargs: Any + ) -> LROPoller[_models.DigitalTwinsDescription]: """Delete a DigitalTwinsInstance. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. @@ -717,86 +948,107 @@ def begin_delete( cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2021_06_30_preview.models.DigitalTwinsDescription] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescription"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + cls: ClsType[_models.DigitalTwinsDescription] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = self._delete_initial( resource_group_name=resource_group_name, resource_name=resource_name, api_version=api_version, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - begin_delete.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}"} # type: ignore + begin_delete.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } @distributed_trace - def list( - self, - **kwargs: Any - ) -> Iterable["_models.DigitalTwinsDescriptionListResult"]: + def list(self, **kwargs: Any) -> Iterable["_models.DigitalTwinsDescription"]: """Get all the DigitalTwinsInstances in a subscription. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either DigitalTwinsDescriptionListResult or the result of + :return: An iterator like instance of either DigitalTwinsDescription or the result of cls(response) :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.digitaltwins.v2021_06_30_preview.models.DigitalTwinsDescriptionListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.paging.ItemPaged[~azure.mgmt.digitaltwins.v2021_06_30_preview.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") + ) + cls: ClsType[_models.DigitalTwinsDescriptionListResult] = kwargs.pop("cls", None) - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescriptionListResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list.metadata['url'], + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: - - request = build_list_request( - subscription_id=self._config.subscription_id, - api_version=api_version, - template_url=next_link, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) @@ -807,16 +1059,14 @@ def extract_data(pipeline_response): deserialized = self._deserialize("DigitalTwinsDescriptionListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -827,56 +1077,68 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.DigitalTwins/digitalTwinsInstances"} # type: ignore + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.DigitalTwins/digitalTwinsInstances"} @distributed_trace def list_by_resource_group( - self, - resource_group_name: str, - **kwargs: Any - ) -> Iterable["_models.DigitalTwinsDescriptionListResult"]: + self, resource_group_name: str, **kwargs: Any + ) -> Iterable["_models.DigitalTwinsDescription"]: """Get all the DigitalTwinsInstances in a resource group. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. 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 DigitalTwinsDescriptionListResult or the result of + :return: An iterator like instance of either DigitalTwinsDescription or the result of cls(response) :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.digitaltwins.v2021_06_30_preview.models.DigitalTwinsDescriptionListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.paging.ItemPaged[~azure.mgmt.digitaltwins.v2021_06_30_preview.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") + ) + cls: ClsType[_models.DigitalTwinsDescriptionListResult] = kwargs.pop("cls", None) - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescriptionListResult"] 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( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata['url'], + template_url=self.list_by_resource_group.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: - - request = build_list_by_resource_group_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - api_version=api_version, - template_url=next_link, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) @@ -887,16 +1149,14 @@ def extract_data(pipeline_response): deserialized = self._deserialize("DigitalTwinsDescriptionListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -907,59 +1167,129 @@ 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.DigitalTwins/digitalTwinsInstances"} # type: ignore + list_by_resource_group.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances" + } - @distributed_trace + @overload def check_name_availability( self, location: str, - digital_twins_instance_check_name: "_models.CheckNameRequest", + digital_twins_instance_check_name: _models.CheckNameRequest, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.CheckNameResult": + ) -> _models.CheckNameResult: """Check if a DigitalTwinsInstance name is available. - :param location: Location of DigitalTwinsInstance. + :param location: Location of DigitalTwinsInstance. Required. :type location: str :param digital_twins_instance_check_name: Set the name parameter in the DigitalTwinsInstanceCheckName structure to the name of the DigitalTwinsInstance to check. + Required. :type digital_twins_instance_check_name: ~azure.mgmt.digitaltwins.v2021_06_30_preview.models.CheckNameRequest + :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: CheckNameResult, or the result of cls(response) + :return: CheckNameResult or the result of cls(response) :rtype: ~azure.mgmt.digitaltwins.v2021_06_30_preview.models.CheckNameResult - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def check_name_availability( + self, + location: str, + digital_twins_instance_check_name: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.CheckNameResult: + """Check if a DigitalTwinsInstance name is available. + + :param location: Location of DigitalTwinsInstance. Required. + :type location: str + :param digital_twins_instance_check_name: Set the name parameter in the + DigitalTwinsInstanceCheckName structure to the name of the DigitalTwinsInstance to check. + Required. + :type digital_twins_instance_check_name: 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: CheckNameResult or the result of cls(response) + :rtype: ~azure.mgmt.digitaltwins.v2021_06_30_preview.models.CheckNameResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def check_name_availability( + self, location: str, digital_twins_instance_check_name: Union[_models.CheckNameRequest, IO], **kwargs: Any + ) -> _models.CheckNameResult: + """Check if a DigitalTwinsInstance name is available. + + :param location: Location of DigitalTwinsInstance. Required. + :type location: str + :param digital_twins_instance_check_name: Set the name parameter in the + DigitalTwinsInstanceCheckName structure to the name of the DigitalTwinsInstance to check. Is + either a model type or a IO type. Required. + :type digital_twins_instance_check_name: + ~azure.mgmt.digitaltwins.v2021_06_30_preview.models.CheckNameRequest 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: CheckNameResult or the result of cls(response) + :rtype: ~azure.mgmt.digitaltwins.v2021_06_30_preview.models.CheckNameResult + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.CheckNameResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") + ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.CheckNameResult] = kwargs.pop("cls", None) - _json = self._serialize.body(digital_twins_instance_check_name, 'CheckNameRequest') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(digital_twins_instance_check_name, (IO, bytes)): + _content = digital_twins_instance_check_name + else: + _json = self._serialize.body(digital_twins_instance_check_name, "CheckNameRequest") request = build_check_name_availability_request( - subscription_id=self._config.subscription_id, location=location, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self.check_name_availability.metadata['url'], + content=_content, + template_url=self.check_name_availability.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -967,12 +1297,13 @@ def check_name_availability( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('CheckNameResult', pipeline_response) + deserialized = self._deserialize("CheckNameResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - check_name_availability.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.DigitalTwins/locations/{location}/checkNameAvailability"} # type: ignore - + check_name_availability.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.DigitalTwins/locations/{location}/checkNameAvailability" + } diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/operations/_operations.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/operations/_operations.py index 57ca4671c5609..96cb5afa967d2 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/operations/_operations.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/operations/_operations.py @@ -6,108 +6,131 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, Callable, Dict, Iterable, Optional, TypeVar - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from ..._serialization import Serializer from .._vendor import _convert_request -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_list_request( - **kwargs: Any -) -> HttpRequest: - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str - accept = "application/json" +def build_list_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") + ) + accept = _headers.pop("Accept", "application/json") + # Construct URL _url = kwargs.pop("template_url", "/providers/Microsoft.DigitalTwins/operations") # Construct parameters - _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - _query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - _header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="GET", - url=_url, - params=_query_parameters, - headers=_header_parameters, - **kwargs - ) + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") -class Operations(object): - """Operations operations. + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.digitaltwins.v2021_06_30_preview.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. +class Operations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.digitaltwins.v2021_06_30_preview.AzureDigitalTwinsManagementClient`'s + :attr:`operations` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace - def list( - self, - **kwargs: Any - ) -> Iterable["_models.OperationListResult"]: + def list(self, **kwargs: Any) -> Iterable["_models.Operation"]: """Lists all of the available DigitalTwins service REST API operations. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either OperationListResult or the result of cls(response) + :return: An iterator like instance of either Operation or the result of cls(response) :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.digitaltwins.v2021_06_30_preview.models.OperationListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.paging.ItemPaged[~azure.mgmt.digitaltwins.v2021_06_30_preview.models.Operation] + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") + ) + cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) - cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationListResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( api_version=api_version, - template_url=self.list.metadata['url'], + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: - - request = build_list_request( - api_version=api_version, - template_url=next_link, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) @@ -118,16 +141,14 @@ def extract_data(pipeline_response): deserialized = self._deserialize("OperationListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -138,8 +159,6 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/providers/Microsoft.DigitalTwins/operations"} # type: ignore + list.metadata = {"url": "/providers/Microsoft.DigitalTwins/operations"} diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/operations/_patch.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/operations/_patch.py new file mode 100644 index 0000000000000..f7dd32510333d --- /dev/null +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/operations/_private_endpoint_connections_operations.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/operations/_private_endpoint_connections_operations.py index e1fabc423fa26..b1e3d332d5752 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/operations/_private_endpoint_connections_operations.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/operations/_private_endpoint_connections_operations.py @@ -6,250 +6,300 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Optional, TypeVar, Union - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import sys +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, cast, 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.polling import LROPoller, NoPolling, PollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models +from ..._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') -JSONType = Any + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False + def build_list_request( - subscription_id: str, - resource_group_name: str, - resource_name: str, - **kwargs: Any + resource_group_name: str, resource_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") + ) + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=63, min_length=3, pattern=r'^(?!-)[A-Za-z0-9-]{3,63}(? HttpRequest: - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") + ) + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=63, min_length=3, pattern=r'^(?!-)[A-Za-z0-9-]{3,63}(? HttpRequest: - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") + ) + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=63, min_length=3, pattern=r'^(?!-)[A-Za-z0-9-]{3,63}(? HttpRequest: - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str - content_type = kwargs.pop('content_type', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") + ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=63, min_length=3, pattern=r'^(?!-)[A-Za-z0-9-]{3,63}(? "_models.PrivateEndpointConnectionsResponse": + self, resource_group_name: str, resource_name: str, **kwargs: Any + ) -> _models.PrivateEndpointConnectionsResponse: """List private endpoint connection properties. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: PrivateEndpointConnectionsResponse, or the result of cls(response) + :return: PrivateEndpointConnectionsResponse or the result of cls(response) :rtype: ~azure.mgmt.digitaltwins.v2021_06_30_preview.models.PrivateEndpointConnectionsResponse - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnectionsResponse"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") + ) + cls: ClsType[_models.PrivateEndpointConnectionsResponse] = kwargs.pop("cls", None) - request = build_list_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list.metadata['url'], + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -257,63 +307,68 @@ def list( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('PrivateEndpointConnectionsResponse', pipeline_response) + deserialized = self._deserialize("PrivateEndpointConnectionsResponse", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - list.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections"} # type: ignore - + list.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections" + } @distributed_trace def get( - self, - resource_group_name: str, - resource_name: str, - private_endpoint_connection_name: str, - **kwargs: Any - ) -> "_models.PrivateEndpointConnection": + self, resource_group_name: str, resource_name: str, private_endpoint_connection_name: str, **kwargs: Any + ) -> _models.PrivateEndpointConnection: """Get private endpoint connection properties for the given private endpoint. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param private_endpoint_connection_name: The name of the private endpoint connection. + :param private_endpoint_connection_name: The name of the private endpoint connection. Required. :type private_endpoint_connection_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: PrivateEndpointConnection, or the result of cls(response) + :return: PrivateEndpointConnection or the result of cls(response) :rtype: ~azure.mgmt.digitaltwins.v2021_06_30_preview.models.PrivateEndpointConnection - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnection"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") + ) + cls: ClsType[_models.PrivateEndpointConnection] = kwargs.pop("cls", None) - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, private_endpoint_connection_name=private_endpoint_connection_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -321,76 +376,79 @@ def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore - + get.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}" + } def _delete_initial( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - resource_name: str, - private_endpoint_connection_name: str, - **kwargs: Any + self, resource_group_name: str, resource_name: str, private_endpoint_connection_name: str, **kwargs: Any ) -> None: - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - request = build_delete_request_initial( - subscription_id=self._config.subscription_id, + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") + ) + cls: ClsType[None] = kwargs.pop("cls", None) + + request = build_delete_request( resource_group_name=resource_group_name, resource_name=resource_name, private_endpoint_connection_name=private_endpoint_connection_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._delete_initial.metadata['url'], + template_url=self._delete_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - _delete_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore - + _delete_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}" + } @distributed_trace - def begin_delete( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - resource_name: str, - private_endpoint_connection_name: str, - **kwargs: Any + def begin_delete( + self, resource_group_name: str, resource_name: str, private_endpoint_connection_name: str, **kwargs: Any ) -> LROPoller[None]: """Delete private endpoint connection with the specified name. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param private_endpoint_connection_name: The name of the private endpoint connection. + :param private_endpoint_connection_name: The name of the private endpoint connection. Required. :type private_endpoint_connection_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. @@ -402,124 +460,156 @@ def begin_delete( # pylint: disable=inconsistent-return-statements Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType[None] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: - raw_result = self._delete_initial( + raw_result = self._delete_initial( # type: ignore resource_group_name=resource_group_name, resource_name=resource_name, private_endpoint_connection_name=private_endpoint_connection_name, api_version=api_version, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - - if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - begin_delete.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore + begin_delete.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}" + } def _create_or_update_initial( self, resource_group_name: str, resource_name: str, private_endpoint_connection_name: str, - private_endpoint_connection: "_models.PrivateEndpointConnection", + private_endpoint_connection: Union[_models.PrivateEndpointConnection, IO], **kwargs: Any - ) -> "_models.PrivateEndpointConnection": - cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnection"] + ) -> _models.PrivateEndpointConnection: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(private_endpoint_connection, 'PrivateEndpointConnection') - - request = build_create_or_update_request_initial( - subscription_id=self._config.subscription_id, + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") + ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PrivateEndpointConnection] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(private_endpoint_connection, (IO, bytes)): + _content = private_endpoint_connection + else: + _json = self._serialize.body(private_endpoint_connection, "PrivateEndpointConnection") + + request = build_create_or_update_request( resource_group_name=resource_group_name, resource_name=resource_name, private_endpoint_connection_name=private_endpoint_connection_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._create_or_update_initial.metadata['url'], + content=_content, + template_url=self._create_or_update_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) if response.status_code == 202: - deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - _create_or_update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore + return deserialized # type: ignore + _create_or_update_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}" + } - @distributed_trace + @overload def begin_create_or_update( self, resource_group_name: str, resource_name: str, private_endpoint_connection_name: str, - private_endpoint_connection: "_models.PrivateEndpointConnection", + private_endpoint_connection: _models.PrivateEndpointConnection, + *, + content_type: str = "application/json", **kwargs: Any - ) -> LROPoller["_models.PrivateEndpointConnection"]: + ) -> LROPoller[_models.PrivateEndpointConnection]: """Update the status of a private endpoint connection with the given name. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param private_endpoint_connection_name: The name of the private endpoint connection. + :param private_endpoint_connection_name: The name of the private endpoint connection. Required. :type private_endpoint_connection_name: str :param private_endpoint_connection: The private endpoint connection with updated properties. + Required. :type private_endpoint_connection: ~azure.mgmt.digitaltwins.v2021_06_30_preview.models.PrivateEndpointConnection + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this @@ -532,17 +622,100 @@ def begin_create_or_update( of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2021_06_30_preview.models.PrivateEndpointConnection] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnection"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + private_endpoint_connection_name: str, + private_endpoint_connection: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.PrivateEndpointConnection]: + """Update the status of a private endpoint connection with the given name. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param private_endpoint_connection_name: The name of the private endpoint connection. Required. + :type private_endpoint_connection_name: str + :param private_endpoint_connection: The private endpoint connection with updated properties. + Required. + :type private_endpoint_connection: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either PrivateEndpointConnection or the result + of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2021_06_30_preview.models.PrivateEndpointConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + private_endpoint_connection_name: str, + private_endpoint_connection: Union[_models.PrivateEndpointConnection, IO], + **kwargs: Any + ) -> LROPoller[_models.PrivateEndpointConnection]: + """Update the status of a private endpoint connection with the given name. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param private_endpoint_connection_name: The name of the private endpoint connection. Required. + :type private_endpoint_connection_name: str + :param private_endpoint_connection: The private endpoint connection with updated properties. Is + either a model type or a IO type. Required. + :type private_endpoint_connection: + ~azure.mgmt.digitaltwins.v2021_06_30_preview.models.PrivateEndpointConnection or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either PrivateEndpointConnection or the result + of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2021_06_30_preview.models.PrivateEndpointConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PrivateEndpointConnection] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = self._create_or_update_initial( resource_group_name=resource_group_name, @@ -551,29 +724,34 @@ def begin_create_or_update( private_endpoint_connection=private_endpoint_connection, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - begin_create_or_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore + begin_create_or_update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}" + } diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/operations/_private_link_resources_operations.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/operations/_private_link_resources_operations.py index 6513ea4bddb61..eb7515db97e0c 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/operations/_private_link_resources_operations.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/operations/_private_link_resources_operations.py @@ -6,163 +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 sys from typing import Any, Callable, Dict, Optional, TypeVar -from msrest import Serializer - -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 HttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from ..._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False + def build_list_request( - subscription_id: str, - resource_group_name: str, - resource_name: str, - **kwargs: Any + resource_group_name: str, resource_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") + ) + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateLinkResources") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateLinkResources", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=63, min_length=3, pattern=r'^(?!-)[A-Za-z0-9-]{3,63}(? HttpRequest: - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") + ) + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateLinkResources/{resourceId}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateLinkResources/{resourceId}", + ) # 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', max_length=90, min_length=1), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=63, min_length=3, pattern=r'^(?!-)[A-Za-z0-9-]{3,63}(? "_models.GroupIdInformationResponse": + def list(self, resource_group_name: str, resource_name: str, **kwargs: Any) -> _models.GroupIdInformationResponse: """List private link resources for given Digital Twin. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: GroupIdInformationResponse, or the result of cls(response) + :return: GroupIdInformationResponse or the result of cls(response) :rtype: ~azure.mgmt.digitaltwins.v2021_06_30_preview.models.GroupIdInformationResponse - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.GroupIdInformationResponse"] 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', "2021-06-30-preview") # type: str + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") + ) + cls: ClsType[_models.GroupIdInformationResponse] = kwargs.pop("cls", None) - request = build_list_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list.metadata['url'], + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -170,63 +196,68 @@ def list( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('GroupIdInformationResponse', pipeline_response) + deserialized = self._deserialize("GroupIdInformationResponse", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - list.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateLinkResources"} # type: ignore - + list.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateLinkResources" + } @distributed_trace def get( - self, - resource_group_name: str, - resource_name: str, - resource_id: str, - **kwargs: Any - ) -> "_models.GroupIdInformation": + self, resource_group_name: str, resource_name: str, resource_id: str, **kwargs: Any + ) -> _models.GroupIdInformation: """Get the specified private link resource for the given Digital Twin. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param resource_id: The name of the private link resource. + :param resource_id: The name of the private link resource. Required. :type resource_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: GroupIdInformation, or the result of cls(response) + :return: GroupIdInformation or the result of cls(response) :rtype: ~azure.mgmt.digitaltwins.v2021_06_30_preview.models.GroupIdInformation - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.GroupIdInformation"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") + ) + cls: ClsType[_models.GroupIdInformation] = kwargs.pop("cls", None) - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, resource_id=resource_id, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -234,12 +265,13 @@ def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('GroupIdInformation', pipeline_response) + deserialized = self._deserialize("GroupIdInformation", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateLinkResources/{resourceId}"} # type: ignore - + get.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateLinkResources/{resourceId}" + } diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/operations/_time_series_database_connections_operations.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/operations/_time_series_database_connections_operations.py index 55c0a906e2fdb..3430af93b0b53 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/operations/_time_series_database_connections_operations.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2021_06_30_preview/operations/_time_series_database_connections_operations.py @@ -6,257 +6,330 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Iterable, Optional, TypeVar, Union - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import sys +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models +from ..._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') -JSONType = Any + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False + def build_list_request( - subscription_id: str, - resource_group_name: str, - resource_name: str, - **kwargs: Any + resource_group_name: str, resource_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") + ) + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections", + ) # 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', max_length=90, min_length=1), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=63, min_length=3, pattern=r'^(?!-)[A-Za-z0-9-]{3,63}(? HttpRequest: - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") + ) + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections/{timeSeriesDatabaseConnectionName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections/{timeSeriesDatabaseConnectionName}", + ) # 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', max_length=90, min_length=1), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=63, min_length=3, pattern=r'^(?!-)[A-Za-z0-9-]{3,63}(? HttpRequest: - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str - content_type = kwargs.pop('content_type', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") + ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections/{timeSeriesDatabaseConnectionName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections/{timeSeriesDatabaseConnectionName}", + ) # 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', max_length=90, min_length=1), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=63, min_length=3, pattern=r'^(?!-)[A-Za-z0-9-]{3,63}(? HttpRequest: - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") + ) + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections/{timeSeriesDatabaseConnectionName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections/{timeSeriesDatabaseConnectionName}", + ) # 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', max_length=90, min_length=1), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=63, min_length=3, pattern=r'^(?!-)[A-Za-z0-9-]{3,63}(? Iterable["_models.TimeSeriesDatabaseConnectionListResult"]: + self, resource_group_name: str, resource_name: str, **kwargs: Any + ) -> Iterable["_models.TimeSeriesDatabaseConnection"]: """Get all existing time series database connections for this DigitalTwins instance. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either TimeSeriesDatabaseConnectionListResult or the - result of cls(response) + :return: An iterator like instance of either TimeSeriesDatabaseConnection or the result of + cls(response) :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.digitaltwins.v2021_06_30_preview.models.TimeSeriesDatabaseConnectionListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.paging.ItemPaged[~azure.mgmt.digitaltwins.v2021_06_30_preview.models.TimeSeriesDatabaseConnection] + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") + ) + cls: ClsType[_models.TimeSeriesDatabaseConnectionListResult] = kwargs.pop("cls", None) - cls = kwargs.pop('cls', None) # type: ClsType["_models.TimeSeriesDatabaseConnectionListResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list.metadata['url'], + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: - - request = build_list_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - resource_name=resource_name, - api_version=api_version, - template_url=next_link, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) @@ -267,16 +340,14 @@ def extract_data(pipeline_response): deserialized = self._deserialize("TimeSeriesDatabaseConnectionListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -287,59 +358,63 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections"} # type: ignore + list.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections" + } @distributed_trace def get( - self, - resource_group_name: str, - resource_name: str, - time_series_database_connection_name: str, - **kwargs: Any - ) -> "_models.TimeSeriesDatabaseConnection": + self, resource_group_name: str, resource_name: str, time_series_database_connection_name: str, **kwargs: Any + ) -> _models.TimeSeriesDatabaseConnection: """Get the description of an existing time series database connection. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param time_series_database_connection_name: Name of time series database connection. + :param time_series_database_connection_name: Name of time series database connection. Required. :type time_series_database_connection_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: TimeSeriesDatabaseConnection, or the result of cls(response) + :return: TimeSeriesDatabaseConnection or the result of cls(response) :rtype: ~azure.mgmt.digitaltwins.v2021_06_30_preview.models.TimeSeriesDatabaseConnection - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.TimeSeriesDatabaseConnection"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") + ) + cls: ClsType[_models.TimeSeriesDatabaseConnection] = kwargs.pop("cls", None) - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, time_series_database_connection_name=time_series_database_connection_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -347,72 +422,174 @@ def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('TimeSeriesDatabaseConnection', pipeline_response) + deserialized = self._deserialize("TimeSeriesDatabaseConnection", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections/{timeSeriesDatabaseConnectionName}"} # type: ignore - + get.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections/{timeSeriesDatabaseConnectionName}" + } def _create_or_update_initial( self, resource_group_name: str, resource_name: str, time_series_database_connection_name: str, - time_series_database_connection_description: "_models.TimeSeriesDatabaseConnection", + time_series_database_connection_description: Union[_models.TimeSeriesDatabaseConnection, IO], **kwargs: Any - ) -> "_models.TimeSeriesDatabaseConnection": - cls = kwargs.pop('cls', None) # type: ClsType["_models.TimeSeriesDatabaseConnection"] + ) -> _models.TimeSeriesDatabaseConnection: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + error_map.update(kwargs.pop("error_map", {}) or {}) - _json = self._serialize.body(time_series_database_connection_description, 'TimeSeriesDatabaseConnection') + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - request = build_create_or_update_request_initial( - subscription_id=self._config.subscription_id, + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") + ) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.TimeSeriesDatabaseConnection] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(time_series_database_connection_description, (IO, bytes)): + _content = time_series_database_connection_description + else: + _json = self._serialize.body(time_series_database_connection_description, "TimeSeriesDatabaseConnection") + + request = build_create_or_update_request( resource_group_name=resource_group_name, resource_name=resource_name, time_series_database_connection_name=time_series_database_connection_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._create_or_update_initial.metadata['url'], + content=_content, + template_url=self._create_or_update_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('TimeSeriesDatabaseConnection', pipeline_response) + deserialized = self._deserialize("TimeSeriesDatabaseConnection", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('TimeSeriesDatabaseConnection', pipeline_response) + deserialized = self._deserialize("TimeSeriesDatabaseConnection", pipeline_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized + return deserialized # type: ignore + + _create_or_update_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections/{timeSeriesDatabaseConnectionName}" + } + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + time_series_database_connection_name: str, + time_series_database_connection_description: _models.TimeSeriesDatabaseConnection, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.TimeSeriesDatabaseConnection]: + """Create or update a time series database connection. - _create_or_update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections/{timeSeriesDatabaseConnectionName}"} # type: ignore + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param time_series_database_connection_name: Name of time series database connection. Required. + :type time_series_database_connection_name: str + :param time_series_database_connection_description: The time series database connection + description. Required. + :type time_series_database_connection_description: + ~azure.mgmt.digitaltwins.v2021_06_30_preview.models.TimeSeriesDatabaseConnection + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either TimeSeriesDatabaseConnection or the + result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2021_06_30_preview.models.TimeSeriesDatabaseConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + @overload + def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + time_series_database_connection_name: str, + time_series_database_connection_description: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.TimeSeriesDatabaseConnection]: + """Create or update a time series database connection. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param time_series_database_connection_name: Name of time series database connection. Required. + :type time_series_database_connection_name: str + :param time_series_database_connection_description: The time series database connection + description. Required. + :type time_series_database_connection_description: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either TimeSeriesDatabaseConnection or the + result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2021_06_30_preview.models.TimeSeriesDatabaseConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace def begin_create_or_update( @@ -420,22 +597,25 @@ def begin_create_or_update( resource_group_name: str, resource_name: str, time_series_database_connection_name: str, - time_series_database_connection_description: "_models.TimeSeriesDatabaseConnection", + time_series_database_connection_description: Union[_models.TimeSeriesDatabaseConnection, IO], **kwargs: Any - ) -> LROPoller["_models.TimeSeriesDatabaseConnection"]: + ) -> LROPoller[_models.TimeSeriesDatabaseConnection]: """Create or update a time series database connection. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param time_series_database_connection_name: Name of time series database connection. + :param time_series_database_connection_name: Name of time series database connection. Required. :type time_series_database_connection_name: str :param time_series_database_connection_description: The time series database connection - description. + description. Is either a model type or a IO type. Required. :type time_series_database_connection_description: - ~azure.mgmt.digitaltwins.v2021_06_30_preview.models.TimeSeriesDatabaseConnection + ~azure.mgmt.digitaltwins.v2021_06_30_preview.models.TimeSeriesDatabaseConnection or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this @@ -448,17 +628,19 @@ def begin_create_or_update( result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2021_06_30_preview.models.TimeSeriesDatabaseConnection] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.TimeSeriesDatabaseConnection"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.TimeSeriesDatabaseConnection] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = self._create_or_update_initial( resource_group_name=resource_group_name, @@ -467,102 +649,109 @@ def begin_create_or_update( time_series_database_connection_description=time_series_database_connection_description, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('TimeSeriesDatabaseConnection', pipeline_response) + deserialized = self._deserialize("TimeSeriesDatabaseConnection", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - begin_create_or_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections/{timeSeriesDatabaseConnectionName}"} # type: ignore + begin_create_or_update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections/{timeSeriesDatabaseConnectionName}" + } def _delete_initial( - self, - resource_group_name: str, - resource_name: str, - time_series_database_connection_name: str, - **kwargs: Any - ) -> Optional["_models.TimeSeriesDatabaseConnection"]: - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.TimeSeriesDatabaseConnection"]] + self, resource_group_name: str, resource_name: str, time_series_database_connection_name: str, **kwargs: Any + ) -> Optional[_models.TimeSeriesDatabaseConnection]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - request = build_delete_request_initial( - subscription_id=self._config.subscription_id, + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") + ) + cls: ClsType[Optional[_models.TimeSeriesDatabaseConnection]] = kwargs.pop("cls", None) + + request = build_delete_request( resource_group_name=resource_group_name, resource_name=resource_name, time_series_database_connection_name=time_series_database_connection_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._delete_initial.metadata['url'], + template_url=self._delete_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('TimeSeriesDatabaseConnection', pipeline_response) + deserialized = self._deserialize("TimeSeriesDatabaseConnection", pipeline_response) if response.status_code == 202: - deserialized = self._deserialize('TimeSeriesDatabaseConnection', pipeline_response) + deserialized = self._deserialize("TimeSeriesDatabaseConnection", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _delete_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections/{timeSeriesDatabaseConnectionName}"} # type: ignore - + _delete_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections/{timeSeriesDatabaseConnectionName}" + } @distributed_trace def begin_delete( - self, - resource_group_name: str, - resource_name: str, - time_series_database_connection_name: str, - **kwargs: Any - ) -> LROPoller["_models.TimeSeriesDatabaseConnection"]: + self, resource_group_name: str, resource_name: str, time_series_database_connection_name: str, **kwargs: Any + ) -> LROPoller[_models.TimeSeriesDatabaseConnection]: """Delete a time series database connection. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param time_series_database_connection_name: Name of time series database connection. + :param time_series_database_connection_name: Name of time series database connection. Required. :type time_series_database_connection_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. @@ -576,45 +765,52 @@ def begin_delete( result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2021_06_30_preview.models.TimeSeriesDatabaseConnection] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2021-06-30-preview") # type: str - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.TimeSeriesDatabaseConnection"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2021-06-30-preview"] = kwargs.pop( + "api_version", _params.pop("api-version", "2021-06-30-preview") ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + cls: ClsType[_models.TimeSeriesDatabaseConnection] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = self._delete_initial( resource_group_name=resource_group_name, resource_name=resource_name, time_series_database_connection_name=time_series_database_connection_name, api_version=api_version, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('TimeSeriesDatabaseConnection', pipeline_response) + deserialized = self._deserialize("TimeSeriesDatabaseConnection", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - begin_delete.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections/{timeSeriesDatabaseConnectionName}"} # type: ignore + begin_delete.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections/{timeSeriesDatabaseConnectionName}" + } diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/__init__.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/__init__.py index 36b558a96cdfd..3d416a868dd25 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/__init__.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/__init__.py @@ -10,9 +10,17 @@ from ._version import VERSION __version__ = VERSION -__all__ = ['AzureDigitalTwinsManagementClient'] -# `._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 * # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "AzureDigitalTwinsManagementClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/_azure_digital_twins_management_client.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/_azure_digital_twins_management_client.py index 5494c582686df..593f55421211b 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/_azure_digital_twins_management_client.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/_azure_digital_twins_management_client.py @@ -9,20 +9,27 @@ from copy import deepcopy from typing import Any, TYPE_CHECKING -from msrest import Deserializer, Serializer - from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient -from . import models +from . import models as _models +from .._serialization import Deserializer, Serializer from ._configuration import AzureDigitalTwinsManagementClientConfiguration -from .operations import DigitalTwinsEndpointOperations, DigitalTwinsOperations, Operations, PrivateEndpointConnectionsOperations, PrivateLinkResourcesOperations, TimeSeriesDatabaseConnectionsOperations +from .operations import ( + DigitalTwinsEndpointOperations, + DigitalTwinsOperations, + Operations, + PrivateEndpointConnectionsOperations, + PrivateLinkResourcesOperations, + TimeSeriesDatabaseConnectionsOperations, +) if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class AzureDigitalTwinsManagementClient: + +class AzureDigitalTwinsManagementClient: # pylint: disable=client-accepts-api-version-keyword """Azure Digital Twins Client for managing DigitalTwinsInstance. :ivar digital_twins: DigitalTwinsOperations operations @@ -41,9 +48,9 @@ class AzureDigitalTwinsManagementClient: :ivar time_series_database_connections: TimeSeriesDatabaseConnectionsOperations operations :vartype time_series_database_connections: azure.mgmt.digitaltwins.v2022_05_31.operations.TimeSeriesDatabaseConnectionsOperations - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: The subscription identifier. + :param subscription_id: The subscription identifier. Required. :type subscription_id: str :param base_url: Service URL. Default value is "https://management.azure.com". :type base_url: str @@ -61,26 +68,31 @@ def __init__( base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: - self._config = AzureDigitalTwinsManagementClientConfiguration(credential=credential, subscription_id=subscription_id, **kwargs) + self._config = AzureDigitalTwinsManagementClientConfiguration( + credential=credential, subscription_id=subscription_id, **kwargs + ) self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) - client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) self._deserialize = Deserializer(client_models) self._serialize.client_side_validation = False self.digital_twins = DigitalTwinsOperations(self._client, self._config, self._serialize, self._deserialize) - self.digital_twins_endpoint = DigitalTwinsEndpointOperations(self._client, self._config, self._serialize, self._deserialize) + self.digital_twins_endpoint = DigitalTwinsEndpointOperations( + self._client, self._config, self._serialize, self._deserialize + ) self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) - self.private_link_resources = PrivateLinkResourcesOperations(self._client, self._config, self._serialize, self._deserialize) - self.private_endpoint_connections = PrivateEndpointConnectionsOperations(self._client, self._config, self._serialize, self._deserialize) - self.time_series_database_connections = TimeSeriesDatabaseConnectionsOperations(self._client, self._config, self._serialize, self._deserialize) - - - def _send_request( - self, - request: HttpRequest, - **kwargs: Any - ) -> HttpResponse: + self.private_link_resources = PrivateLinkResourcesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.private_endpoint_connections = PrivateEndpointConnectionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.time_series_database_connections = TimeSeriesDatabaseConnectionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + + def _send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: """Runs the network request through the client's chained policies. >>> from azure.core.rest import HttpRequest @@ -89,7 +101,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 @@ -102,15 +114,12 @@ def _send_request( request_copy.url = self._client.format_url(request_copy.url) return self._client.send_request(request_copy, **kwargs) - def close(self): - # type: () -> None + def close(self) -> None: self._client.close() - def __enter__(self): - # type: () -> AzureDigitalTwinsManagementClient + def __enter__(self) -> "AzureDigitalTwinsManagementClient": self._client.__enter__() return self - def __exit__(self, *exc_details): - # type: (Any) -> None + def __exit__(self, *exc_details) -> None: self._client.__exit__(*exc_details) diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/_configuration.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/_configuration.py index e3952e0a85de4..7f7b946d46a03 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/_configuration.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/_configuration.py @@ -6,6 +6,7 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, TYPE_CHECKING from azure.core.configuration import Configuration @@ -14,6 +15,11 @@ from ._version import VERSION +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports + if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential @@ -25,23 +31,18 @@ class AzureDigitalTwinsManagementClientConfiguration(Configuration): # pylint: Note that all parameters used to create this instance are saved as instance attributes. - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: The subscription identifier. + :param subscription_id: The subscription identifier. Required. :type subscription_id: str :keyword api_version: Api Version. Default value is "2022-05-31". 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(AzureDigitalTwinsManagementClientConfiguration, self).__init__(**kwargs) - api_version = kwargs.pop('api_version', "2022-05-31") # type: str + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", "2022-05-31") if credential is None: raise ValueError("Parameter 'credential' must not be None.") @@ -51,23 +52,21 @@ def __init__( self.credential = credential self.subscription_id = subscription_id self.api_version = api_version - self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'mgmt-digitaltwins/{}'.format(VERSION)) + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-digitaltwins/{}".format(VERSION)) self._configure(**kwargs) - def _configure( - self, - **kwargs # type: Any - ): - # type: (...) -> None - self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get('retry_policy') or policies.RetryPolicy(**kwargs) - self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get('redirect_policy') or policies.RedirectPolicy(**kwargs) - self.authentication_policy = kwargs.get('authentication_policy') + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: - self.authentication_policy = ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs) + self.authentication_policy = ARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/_metadata.json b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/_metadata.json index ab9b5550b8e65..36d31c3225669 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/_metadata.json +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/_metadata.json @@ -10,20 +10,20 @@ "azure_arm": true, "has_lro_operations": true, "client_side_validation": false, - "sync_imports": "{\"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}, \"regular\": {\"azurecore\": {\"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"], \"azure.mgmt.core\": [\"ARMPipelineClient\"]}, \"local\": {\"._configuration\": [\"AzureDigitalTwinsManagementClientConfiguration\"]}, \"thirdparty\": {\"msrest\": [\"Deserializer\", \"Serializer\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}}", - "async_imports": "{\"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"], \"azure.core.credentials\": [\"TokenCredential\"]}}, \"regular\": {\"azurecore\": {\"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"], \"azure.mgmt.core\": [\"AsyncARMPipelineClient\"]}, \"local\": {\"._configuration\": [\"AzureDigitalTwinsManagementClientConfiguration\"]}, \"thirdparty\": {\"msrest\": [\"Deserializer\", \"Serializer\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}}" + "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"AzureDigitalTwinsManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"AzureDigitalTwinsManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "global_parameters": { "sync": { "credential": { - "signature": "credential, # type: \"TokenCredential\"", - "description": "Credential needed for the client to connect to Azure.", + "signature": "credential: \"TokenCredential\",", + "description": "Credential needed for the client to connect to Azure. Required.", "docstring_type": "~azure.core.credentials.TokenCredential", "required": true }, "subscription_id": { - "signature": "subscription_id, # type: str", - "description": "The subscription identifier.", + "signature": "subscription_id: str,", + "description": "The subscription identifier. Required.", "docstring_type": "str", "required": true } @@ -31,13 +31,13 @@ "async": { "credential": { "signature": "credential: \"AsyncTokenCredential\",", - "description": "Credential needed for the client to connect to Azure.", + "description": "Credential needed for the client to connect to Azure. Required.", "docstring_type": "~azure.core.credentials_async.AsyncTokenCredential", "required": true }, "subscription_id": { "signature": "subscription_id: str,", - "description": "The subscription identifier.", + "description": "The subscription identifier. Required.", "docstring_type": "str", "required": true } @@ -48,19 +48,19 @@ "service_client_specific": { "sync": { "api_version": { - "signature": "api_version=None, # type: Optional[str]", + "signature": "api_version: Optional[str]=None,", "description": "API version to use if no profile is provided, or if missing in profile.", "docstring_type": "str", "required": false }, "base_url": { - "signature": "base_url=\"https://management.azure.com\", # type: str", + "signature": "base_url: str = \"https://management.azure.com\",", "description": "Service URL", "docstring_type": "str", "required": false }, "profile": { - "signature": "profile=KnownProfiles.default, # type: KnownProfiles", + "signature": "profile: KnownProfiles=KnownProfiles.default,", "description": "A profile definition, from KnownProfiles to dict.", "docstring_type": "azure.profiles.KnownProfiles", "required": false @@ -104,4 +104,4 @@ "private_endpoint_connections": "PrivateEndpointConnectionsOperations", "time_series_database_connections": "TimeSeriesDatabaseConnectionsOperations" } -} \ No newline at end of file +} diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/_patch.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/_patch.py index 74e48ecd07cf3..f99e77fef9861 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/_patch.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/_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/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/_vendor.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/_vendor.py index 138f663c53a4e..9aad73fc743e7 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/_vendor.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/_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/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/_version.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/_version.py index a55d01326aa81..e5754a47ce68f 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/_version.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "6.2.0" +VERSION = "1.0.0b1" diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/aio/__init__.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/aio/__init__.py index 20a6435cbbdb2..e4da5a5dc30c1 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/aio/__init__.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/aio/__init__.py @@ -7,9 +7,17 @@ # -------------------------------------------------------------------------- from ._azure_digital_twins_management_client import AzureDigitalTwinsManagementClient -__all__ = ['AzureDigitalTwinsManagementClient'] -# `._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 * # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "AzureDigitalTwinsManagementClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/aio/_azure_digital_twins_management_client.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/aio/_azure_digital_twins_management_client.py index db30b7ac5004c..5e5d606eca107 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/aio/_azure_digital_twins_management_client.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/aio/_azure_digital_twins_management_client.py @@ -9,20 +9,27 @@ from copy import deepcopy from typing import Any, Awaitable, TYPE_CHECKING -from msrest import Deserializer, Serializer - from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient -from .. import models +from .. import models as _models +from ..._serialization import Deserializer, Serializer from ._configuration import AzureDigitalTwinsManagementClientConfiguration -from .operations import DigitalTwinsEndpointOperations, DigitalTwinsOperations, Operations, PrivateEndpointConnectionsOperations, PrivateLinkResourcesOperations, TimeSeriesDatabaseConnectionsOperations +from .operations import ( + DigitalTwinsEndpointOperations, + DigitalTwinsOperations, + Operations, + PrivateEndpointConnectionsOperations, + PrivateLinkResourcesOperations, + TimeSeriesDatabaseConnectionsOperations, +) if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class AzureDigitalTwinsManagementClient: + +class AzureDigitalTwinsManagementClient: # pylint: disable=client-accepts-api-version-keyword """Azure Digital Twins Client for managing DigitalTwinsInstance. :ivar digital_twins: DigitalTwinsOperations operations @@ -42,9 +49,9 @@ class AzureDigitalTwinsManagementClient: :ivar time_series_database_connections: TimeSeriesDatabaseConnectionsOperations operations :vartype time_series_database_connections: azure.mgmt.digitaltwins.v2022_05_31.aio.operations.TimeSeriesDatabaseConnectionsOperations - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: The subscription identifier. + :param subscription_id: The subscription identifier. Required. :type subscription_id: str :param base_url: Service URL. Default value is "https://management.azure.com". :type base_url: str @@ -62,26 +69,31 @@ def __init__( base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: - self._config = AzureDigitalTwinsManagementClientConfiguration(credential=credential, subscription_id=subscription_id, **kwargs) + self._config = AzureDigitalTwinsManagementClientConfiguration( + credential=credential, subscription_id=subscription_id, **kwargs + ) self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) - client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) self._deserialize = Deserializer(client_models) self._serialize.client_side_validation = False self.digital_twins = DigitalTwinsOperations(self._client, self._config, self._serialize, self._deserialize) - self.digital_twins_endpoint = DigitalTwinsEndpointOperations(self._client, self._config, self._serialize, self._deserialize) + self.digital_twins_endpoint = DigitalTwinsEndpointOperations( + self._client, self._config, self._serialize, self._deserialize + ) self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) - self.private_link_resources = PrivateLinkResourcesOperations(self._client, self._config, self._serialize, self._deserialize) - self.private_endpoint_connections = PrivateEndpointConnectionsOperations(self._client, self._config, self._serialize, self._deserialize) - self.time_series_database_connections = TimeSeriesDatabaseConnectionsOperations(self._client, self._config, self._serialize, self._deserialize) - - - def _send_request( - self, - request: HttpRequest, - **kwargs: Any - ) -> Awaitable[AsyncHttpResponse]: + self.private_link_resources = PrivateLinkResourcesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.private_endpoint_connections = PrivateEndpointConnectionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.time_series_database_connections = TimeSeriesDatabaseConnectionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + + def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: """Runs the network request through the client's chained policies. >>> from azure.core.rest import HttpRequest @@ -90,7 +102,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/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/aio/_configuration.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/aio/_configuration.py index e06c6e58a0f36..a6dabb7826fad 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/aio/_configuration.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/aio/_configuration.py @@ -6,6 +6,7 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, TYPE_CHECKING from azure.core.configuration import Configuration @@ -14,6 +15,11 @@ from .._version import VERSION +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports + if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential @@ -25,23 +31,18 @@ class AzureDigitalTwinsManagementClientConfiguration(Configuration): # pylint: Note that all parameters used to create this instance are saved as instance attributes. - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: The subscription identifier. + :param subscription_id: The subscription identifier. Required. :type subscription_id: str :keyword api_version: Api Version. Default value is "2022-05-31". 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(AzureDigitalTwinsManagementClientConfiguration, self).__init__(**kwargs) - api_version = kwargs.pop('api_version', "2022-05-31") # type: str + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", "2022-05-31") if credential is None: raise ValueError("Parameter 'credential' must not be None.") @@ -51,22 +52,21 @@ def __init__( self.credential = credential self.subscription_id = subscription_id self.api_version = api_version - self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'mgmt-digitaltwins/{}'.format(VERSION)) + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-digitaltwins/{}".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/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/aio/_patch.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/aio/_patch.py index 74e48ecd07cf3..f99e77fef9861 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/aio/_patch.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/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/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/aio/operations/__init__.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/aio/operations/__init__.py index b5d50b71ecc92..791d2a1bb74f4 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/aio/operations/__init__.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/aio/operations/__init__.py @@ -13,11 +13,17 @@ from ._private_endpoint_connections_operations import PrivateEndpointConnectionsOperations from ._time_series_database_connections_operations import TimeSeriesDatabaseConnectionsOperations +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + __all__ = [ - 'DigitalTwinsOperations', - 'DigitalTwinsEndpointOperations', - 'Operations', - 'PrivateLinkResourcesOperations', - 'PrivateEndpointConnectionsOperations', - 'TimeSeriesDatabaseConnectionsOperations', + "DigitalTwinsOperations", + "DigitalTwinsEndpointOperations", + "Operations", + "PrivateLinkResourcesOperations", + "PrivateEndpointConnectionsOperations", + "TimeSeriesDatabaseConnectionsOperations", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/aio/operations/_digital_twins_endpoint_operations.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/aio/operations/_digital_twins_endpoint_operations.py index 58a637889ca67..c282a6a1f8958 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/aio/operations/_digital_twins_endpoint_operations.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/aio/operations/_digital_twins_endpoint_operations.py @@ -6,96 +6,124 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar, Union +import sys +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models from ..._vendor import _convert_request -from ...operations._digital_twins_endpoint_operations import build_create_or_update_request_initial, build_delete_request_initial, build_get_request, build_list_request -T = TypeVar('T') +from ...operations._digital_twins_endpoint_operations import ( + build_create_or_update_request, + build_delete_request, + build_get_request, + build_list_request, +) + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class DigitalTwinsEndpointOperations: - """DigitalTwinsEndpointOperations 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 DigitalTwinsEndpointOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.digitaltwins.v2022_05_31.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.digitaltwins.v2022_05_31.aio.AzureDigitalTwinsManagementClient`'s + :attr:`digital_twins_endpoint` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list( - self, - resource_group_name: str, - resource_name: str, - **kwargs: Any - ) -> AsyncIterable["_models.DigitalTwinsEndpointResourceListResult"]: + self, resource_group_name: str, resource_name: str, **kwargs: Any + ) -> AsyncIterable["_models.DigitalTwinsEndpointResource"]: """Get DigitalTwinsInstance Endpoints. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either DigitalTwinsEndpointResourceListResult or the - result of cls(response) + :return: An iterator like instance of either DigitalTwinsEndpointResource or the result of + cls(response) :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.digitaltwins.v2022_05_31.models.DigitalTwinsEndpointResourceListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.digitaltwins.v2022_05_31.models.DigitalTwinsEndpointResource] + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2022-05-31") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + cls: ClsType[_models.DigitalTwinsEndpointResourceListResult] = kwargs.pop("cls", None) - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsEndpointResourceListResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list.metadata['url'], + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: - - request = build_list_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - resource_name=resource_name, - api_version=api_version, - template_url=next_link, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) @@ -106,16 +134,14 @@ async def extract_data(pipeline_response): deserialized = self._deserialize("DigitalTwinsEndpointResourceListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -126,59 +152,61 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints"} # type: ignore + list.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints" + } @distributed_trace_async async def get( - self, - resource_group_name: str, - resource_name: str, - endpoint_name: str, - **kwargs: Any - ) -> "_models.DigitalTwinsEndpointResource": + self, resource_group_name: str, resource_name: str, endpoint_name: str, **kwargs: Any + ) -> _models.DigitalTwinsEndpointResource: """Get DigitalTwinsInstances Endpoint. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param endpoint_name: Name of Endpoint Resource. + :param endpoint_name: Name of Endpoint Resource. Required. :type endpoint_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: DigitalTwinsEndpointResource, or the result of cls(response) + :return: DigitalTwinsEndpointResource or the result of cls(response) :rtype: ~azure.mgmt.digitaltwins.v2022_05_31.models.DigitalTwinsEndpointResource - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsEndpointResource"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', "2022-05-31") # type: str + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + cls: ClsType[_models.DigitalTwinsEndpointResource] = kwargs.pop("cls", None) - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, endpoint_name=endpoint_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -186,72 +214,172 @@ async def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('DigitalTwinsEndpointResource', pipeline_response) + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}"} # type: ignore - + get.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}" + } async def _create_or_update_initial( self, resource_group_name: str, resource_name: str, endpoint_name: str, - endpoint_description: "_models.DigitalTwinsEndpointResource", + endpoint_description: Union[_models.DigitalTwinsEndpointResource, IO], **kwargs: Any - ) -> "_models.DigitalTwinsEndpointResource": - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsEndpointResource"] + ) -> _models.DigitalTwinsEndpointResource: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2022-05-31") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(endpoint_description, 'DigitalTwinsEndpointResource') + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DigitalTwinsEndpointResource] = kwargs.pop("cls", None) - request = build_create_or_update_request_initial( - subscription_id=self._config.subscription_id, + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(endpoint_description, (IO, bytes)): + _content = endpoint_description + else: + _json = self._serialize.body(endpoint_description, "DigitalTwinsEndpointResource") + + request = build_create_or_update_request( resource_group_name=resource_group_name, resource_name=resource_name, 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_initial.metadata['url'], + content=_content, + template_url=self._create_or_update_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('DigitalTwinsEndpointResource', pipeline_response) + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('DigitalTwinsEndpointResource', pipeline_response) + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized + return deserialized # type: ignore + + _create_or_update_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}" + } + + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + endpoint_name: str, + endpoint_description: _models.DigitalTwinsEndpointResource, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.DigitalTwinsEndpointResource]: + """Create or update DigitalTwinsInstance endpoint. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param endpoint_name: Name of Endpoint Resource. Required. + :type endpoint_name: str + :param endpoint_description: The DigitalTwinsInstance endpoint metadata and security metadata. + Required. + :type endpoint_description: + ~azure.mgmt.digitaltwins.v2022_05_31.models.DigitalTwinsEndpointResource + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either DigitalTwinsEndpointResource or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2022_05_31.models.DigitalTwinsEndpointResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ - _create_or_update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}"} # type: ignore + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + endpoint_name: str, + endpoint_description: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.DigitalTwinsEndpointResource]: + """Create or update DigitalTwinsInstance endpoint. + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param endpoint_name: Name of Endpoint Resource. Required. + :type endpoint_name: str + :param endpoint_description: The DigitalTwinsInstance endpoint metadata and security metadata. + Required. + :type endpoint_description: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either DigitalTwinsEndpointResource or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2022_05_31.models.DigitalTwinsEndpointResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace_async async def begin_create_or_update( @@ -259,21 +387,25 @@ async def begin_create_or_update( resource_group_name: str, resource_name: str, endpoint_name: str, - endpoint_description: "_models.DigitalTwinsEndpointResource", + endpoint_description: Union[_models.DigitalTwinsEndpointResource, IO], **kwargs: Any - ) -> AsyncLROPoller["_models.DigitalTwinsEndpointResource"]: + ) -> AsyncLROPoller[_models.DigitalTwinsEndpointResource]: """Create or update DigitalTwinsInstance endpoint. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param endpoint_name: Name of Endpoint Resource. + :param endpoint_name: Name of Endpoint Resource. Required. :type endpoint_name: str :param endpoint_description: The DigitalTwinsInstance endpoint metadata and security metadata. + Is either a model type or a IO type. Required. :type endpoint_description: - ~azure.mgmt.digitaltwins.v2022_05_31.models.DigitalTwinsEndpointResource + ~azure.mgmt.digitaltwins.v2022_05_31.models.DigitalTwinsEndpointResource or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for @@ -286,17 +418,17 @@ async def begin_create_or_update( result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2022_05_31.models.DigitalTwinsEndpointResource] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2022-05-31") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsEndpointResource"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DigitalTwinsEndpointResource] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = await self._create_or_update_initial( resource_group_name=resource_group_name, @@ -305,102 +437,107 @@ async def begin_create_or_update( endpoint_description=endpoint_description, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('DigitalTwinsEndpointResource', pipeline_response) + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - begin_create_or_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}"} # type: ignore + begin_create_or_update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}" + } async def _delete_initial( - self, - resource_group_name: str, - resource_name: str, - endpoint_name: str, - **kwargs: Any - ) -> Optional["_models.DigitalTwinsEndpointResource"]: - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.DigitalTwinsEndpointResource"]] + self, resource_group_name: str, resource_name: str, endpoint_name: str, **kwargs: Any + ) -> Optional[_models.DigitalTwinsEndpointResource]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2022-05-31") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - request = build_delete_request_initial( - subscription_id=self._config.subscription_id, + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + cls: ClsType[Optional[_models.DigitalTwinsEndpointResource]] = kwargs.pop("cls", None) + + request = build_delete_request( resource_group_name=resource_group_name, resource_name=resource_name, endpoint_name=endpoint_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._delete_initial.metadata['url'], + template_url=self._delete_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('DigitalTwinsEndpointResource', pipeline_response) + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) if response.status_code == 202: - deserialized = self._deserialize('DigitalTwinsEndpointResource', pipeline_response) + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _delete_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}"} # type: ignore - + _delete_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}" + } @distributed_trace_async async def begin_delete( - self, - resource_group_name: str, - resource_name: str, - endpoint_name: str, - **kwargs: Any - ) -> AsyncLROPoller["_models.DigitalTwinsEndpointResource"]: + self, resource_group_name: str, resource_name: str, endpoint_name: str, **kwargs: Any + ) -> AsyncLROPoller[_models.DigitalTwinsEndpointResource]: """Delete a DigitalTwinsInstance endpoint. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param endpoint_name: Name of Endpoint Resource. + :param endpoint_name: Name of Endpoint Resource. Required. :type endpoint_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. @@ -414,45 +551,50 @@ async def begin_delete( result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2022_05_31.models.DigitalTwinsEndpointResource] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2022-05-31") # type: str - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsEndpointResource"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + cls: ClsType[_models.DigitalTwinsEndpointResource] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = await self._delete_initial( resource_group_name=resource_group_name, resource_name=resource_name, endpoint_name=endpoint_name, api_version=api_version, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('DigitalTwinsEndpointResource', pipeline_response) + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - begin_delete.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}"} # type: ignore + begin_delete.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}" + } diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/aio/operations/_digital_twins_operations.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/aio/operations/_digital_twins_operations.py index e24d2bce941da..30cddfcbb9e64 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/aio/operations/_digital_twins_operations.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/aio/operations/_digital_twins_operations.py @@ -6,90 +6,112 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar, Union +import sys +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models from ..._vendor import _convert_request -from ...operations._digital_twins_operations import build_check_name_availability_request, build_create_or_update_request_initial, build_delete_request_initial, build_get_request, build_list_by_resource_group_request, build_list_request, build_update_request_initial -T = TypeVar('T') +from ...operations._digital_twins_operations import ( + build_check_name_availability_request, + build_create_or_update_request, + build_delete_request, + build_get_request, + build_list_by_resource_group_request, + build_list_request, + build_update_request, +) + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class DigitalTwinsOperations: - """DigitalTwinsOperations 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 DigitalTwinsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.digitaltwins.v2022_05_31.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.digitaltwins.v2022_05_31.aio.AzureDigitalTwinsManagementClient`'s + :attr:`digital_twins` 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, - resource_group_name: str, - resource_name: str, - **kwargs: Any - ) -> "_models.DigitalTwinsDescription": + async def get(self, resource_group_name: str, resource_name: str, **kwargs: Any) -> _models.DigitalTwinsDescription: """Get DigitalTwinsInstances resource. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: DigitalTwinsDescription, or the result of cls(response) + :return: DigitalTwinsDescription or the result of cls(response) :rtype: ~azure.mgmt.digitaltwins.v2022_05_31.models.DigitalTwinsDescription - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescription"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2022-05-31") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + cls: ClsType[_models.DigitalTwinsDescription] = kwargs.pop("cls", None) - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -97,90 +119,190 @@ async def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}"} # type: ignore - + get.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } async def _create_or_update_initial( self, resource_group_name: str, resource_name: str, - digital_twins_create: "_models.DigitalTwinsDescription", + digital_twins_create: Union[_models.DigitalTwinsDescription, IO], **kwargs: Any - ) -> "_models.DigitalTwinsDescription": - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescription"] + ) -> _models.DigitalTwinsDescription: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2022-05-31") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(digital_twins_create, 'DigitalTwinsDescription') + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DigitalTwinsDescription] = kwargs.pop("cls", None) - request = build_create_or_update_request_initial( - subscription_id=self._config.subscription_id, + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(digital_twins_create, (IO, bytes)): + _content = digital_twins_create + else: + _json = self._serialize.body(digital_twins_create, "DigitalTwinsDescription") + + request = build_create_or_update_request( resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._create_or_update_initial.metadata['url'], + content=_content, + template_url=self._create_or_update_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized + return deserialized # type: ignore + + _create_or_update_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } - _create_or_update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}"} # type: ignore + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + digital_twins_create: _models.DigitalTwinsDescription, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.DigitalTwinsDescription]: + """Create or update the metadata of a DigitalTwinsInstance. The usual pattern to modify a property + is to retrieve the DigitalTwinsInstance and security metadata, and then combine them with the + modified values in a new body to update the DigitalTwinsInstance. + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param digital_twins_create: The DigitalTwinsInstance and security metadata. Required. + :type digital_twins_create: ~azure.mgmt.digitaltwins.v2022_05_31.models.DigitalTwinsDescription + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either DigitalTwinsDescription or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2022_05_31.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + digital_twins_create: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.DigitalTwinsDescription]: + """Create or update the metadata of a DigitalTwinsInstance. The usual pattern to modify a property + is to retrieve the DigitalTwinsInstance and security metadata, and then combine them with the + modified values in a new body to update the DigitalTwinsInstance. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param digital_twins_create: The DigitalTwinsInstance and security metadata. Required. + :type digital_twins_create: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either DigitalTwinsDescription or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2022_05_31.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace_async async def begin_create_or_update( self, resource_group_name: str, resource_name: str, - digital_twins_create: "_models.DigitalTwinsDescription", + digital_twins_create: Union[_models.DigitalTwinsDescription, IO], **kwargs: Any - ) -> AsyncLROPoller["_models.DigitalTwinsDescription"]: + ) -> AsyncLROPoller[_models.DigitalTwinsDescription]: """Create or update the metadata of a DigitalTwinsInstance. The usual pattern to modify a property is to retrieve the DigitalTwinsInstance and security metadata, and then combine them with the modified values in a new body to update the DigitalTwinsInstance. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param digital_twins_create: The DigitalTwinsInstance and security metadata. + :param digital_twins_create: The DigitalTwinsInstance and security metadata. Is either a model + type or a IO type. Required. :type digital_twins_create: ~azure.mgmt.digitaltwins.v2022_05_31.models.DigitalTwinsDescription + or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for @@ -193,17 +315,17 @@ async def begin_create_or_update( result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2022_05_31.models.DigitalTwinsDescription] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2022-05-31") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescription"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DigitalTwinsDescription] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = await self._create_or_update_initial( resource_group_name=resource_group_name, @@ -211,106 +333,133 @@ async def begin_create_or_update( digital_twins_create=digital_twins_create, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - begin_create_or_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}"} # type: ignore + begin_create_or_update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } async def _update_initial( self, resource_group_name: str, resource_name: str, - digital_twins_patch_description: "_models.DigitalTwinsPatchDescription", + digital_twins_patch_description: Union[_models.DigitalTwinsPatchDescription, IO], **kwargs: Any - ) -> "_models.DigitalTwinsDescription": - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescription"] + ) -> _models.DigitalTwinsDescription: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2022-05-31") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(digital_twins_patch_description, 'DigitalTwinsPatchDescription') + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DigitalTwinsDescription] = kwargs.pop("cls", None) - request = build_update_request_initial( - subscription_id=self._config.subscription_id, + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(digital_twins_patch_description, (IO, bytes)): + _content = digital_twins_patch_description + else: + _json = self._serialize.body(digital_twins_patch_description, "DigitalTwinsPatchDescription") + + request = build_update_request( resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._update_initial.metadata['url'], + content=_content, + template_url=self._update_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if response.status_code == 202: - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - _update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}"} # type: ignore + return deserialized # type: ignore + _update_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } - @distributed_trace_async + @overload async def begin_update( self, resource_group_name: str, resource_name: str, - digital_twins_patch_description: "_models.DigitalTwinsPatchDescription", + digital_twins_patch_description: _models.DigitalTwinsPatchDescription, + *, + content_type: str = "application/json", **kwargs: Any - ) -> AsyncLROPoller["_models.DigitalTwinsDescription"]: + ) -> AsyncLROPoller[_models.DigitalTwinsDescription]: """Update metadata of DigitalTwinsInstance. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str :param digital_twins_patch_description: The DigitalTwinsInstance and security metadata. + Required. :type digital_twins_patch_description: ~azure.mgmt.digitaltwins.v2022_05_31.models.DigitalTwinsPatchDescription + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for @@ -323,17 +472,92 @@ async def begin_update( result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2022_05_31.models.DigitalTwinsDescription] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2022-05-31") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescription"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + + @overload + async def begin_update( + self, + resource_group_name: str, + resource_name: str, + digital_twins_patch_description: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.DigitalTwinsDescription]: + """Update metadata of DigitalTwinsInstance. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param digital_twins_patch_description: The DigitalTwinsInstance and security metadata. + Required. + :type digital_twins_patch_description: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either DigitalTwinsDescription or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2022_05_31.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_update( + self, + resource_group_name: str, + resource_name: str, + digital_twins_patch_description: Union[_models.DigitalTwinsPatchDescription, IO], + **kwargs: Any + ) -> AsyncLROPoller[_models.DigitalTwinsDescription]: + """Update metadata of DigitalTwinsInstance. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param digital_twins_patch_description: The DigitalTwinsInstance and security metadata. Is + either a model type or a IO type. Required. + :type digital_twins_patch_description: + ~azure.mgmt.digitaltwins.v2022_05_31.models.DigitalTwinsPatchDescription or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either DigitalTwinsDescription or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2022_05_31.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DigitalTwinsDescription] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = await self._update_initial( resource_group_name=resource_group_name, @@ -341,97 +565,104 @@ async def begin_update( digital_twins_patch_description=digital_twins_patch_description, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - begin_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}"} # type: ignore + begin_update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } async def _delete_initial( - self, - resource_group_name: str, - resource_name: str, - **kwargs: Any - ) -> Optional["_models.DigitalTwinsDescription"]: - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.DigitalTwinsDescription"]] + self, resource_group_name: str, resource_name: str, **kwargs: Any + ) -> Optional[_models.DigitalTwinsDescription]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2022-05-31") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - request = build_delete_request_initial( - subscription_id=self._config.subscription_id, + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + cls: ClsType[Optional[_models.DigitalTwinsDescription]] = kwargs.pop("cls", None) + + request = build_delete_request( resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._delete_initial.metadata['url'], + template_url=self._delete_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if response.status_code == 202: - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _delete_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}"} # type: ignore - + _delete_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } @distributed_trace_async async def begin_delete( - self, - resource_group_name: str, - resource_name: str, - **kwargs: Any - ) -> AsyncLROPoller["_models.DigitalTwinsDescription"]: + self, resource_group_name: str, resource_name: str, **kwargs: Any + ) -> AsyncLROPoller[_models.DigitalTwinsDescription]: """Delete a DigitalTwinsInstance. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. @@ -445,86 +676,103 @@ async def begin_delete( result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2022_05_31.models.DigitalTwinsDescription] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2022-05-31") # type: str - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescription"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + cls: ClsType[_models.DigitalTwinsDescription] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = await self._delete_initial( resource_group_name=resource_group_name, resource_name=resource_name, api_version=api_version, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - begin_delete.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}"} # type: ignore + begin_delete.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } @distributed_trace - def list( - self, - **kwargs: Any - ) -> AsyncIterable["_models.DigitalTwinsDescriptionListResult"]: + def list(self, **kwargs: Any) -> AsyncIterable["_models.DigitalTwinsDescription"]: """Get all the DigitalTwinsInstances in a subscription. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either DigitalTwinsDescriptionListResult or the result of + :return: An iterator like instance of either DigitalTwinsDescription or the result of cls(response) :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.digitaltwins.v2022_05_31.models.DigitalTwinsDescriptionListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.digitaltwins.v2022_05_31.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2022-05-31") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + cls: ClsType[_models.DigitalTwinsDescriptionListResult] = kwargs.pop("cls", None) - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescriptionListResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list.metadata['url'], + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: - - request = build_list_request( - subscription_id=self._config.subscription_id, - api_version=api_version, - template_url=next_link, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) @@ -535,16 +783,14 @@ async def extract_data(pipeline_response): deserialized = self._deserialize("DigitalTwinsDescriptionListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -555,56 +801,66 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.DigitalTwins/digitalTwinsInstances"} # type: ignore + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.DigitalTwins/digitalTwinsInstances"} @distributed_trace def list_by_resource_group( - self, - resource_group_name: str, - **kwargs: Any - ) -> AsyncIterable["_models.DigitalTwinsDescriptionListResult"]: + self, resource_group_name: str, **kwargs: Any + ) -> AsyncIterable["_models.DigitalTwinsDescription"]: """Get all the DigitalTwinsInstances in a resource group. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. 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 DigitalTwinsDescriptionListResult or the result of + :return: An iterator like instance of either DigitalTwinsDescription or the result of cls(response) :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.digitaltwins.v2022_05_31.models.DigitalTwinsDescriptionListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.digitaltwins.v2022_05_31.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2022-05-31") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + cls: ClsType[_models.DigitalTwinsDescriptionListResult] = kwargs.pop("cls", None) - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescriptionListResult"] 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( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata['url'], + template_url=self.list_by_resource_group.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: - - request = build_list_by_resource_group_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - api_version=api_version, - template_url=next_link, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) @@ -615,16 +871,14 @@ async def extract_data(pipeline_response): deserialized = self._deserialize("DigitalTwinsDescriptionListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -635,59 +889,127 @@ 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.DigitalTwins/digitalTwinsInstances"} # type: ignore + list_by_resource_group.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances" + } - @distributed_trace_async + @overload async def check_name_availability( self, location: str, - digital_twins_instance_check_name: "_models.CheckNameRequest", + digital_twins_instance_check_name: _models.CheckNameRequest, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.CheckNameResult": + ) -> _models.CheckNameResult: """Check if a DigitalTwinsInstance name is available. - :param location: Location of DigitalTwinsInstance. + :param location: Location of DigitalTwinsInstance. Required. :type location: str :param digital_twins_instance_check_name: Set the name parameter in the DigitalTwinsInstanceCheckName structure to the name of the DigitalTwinsInstance to check. + Required. :type digital_twins_instance_check_name: ~azure.mgmt.digitaltwins.v2022_05_31.models.CheckNameRequest + :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: CheckNameResult, or the result of cls(response) + :return: CheckNameResult or the result of cls(response) :rtype: ~azure.mgmt.digitaltwins.v2022_05_31.models.CheckNameResult - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def check_name_availability( + self, + location: str, + digital_twins_instance_check_name: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.CheckNameResult: + """Check if a DigitalTwinsInstance name is available. + + :param location: Location of DigitalTwinsInstance. Required. + :type location: str + :param digital_twins_instance_check_name: Set the name parameter in the + DigitalTwinsInstanceCheckName structure to the name of the DigitalTwinsInstance to check. + Required. + :type digital_twins_instance_check_name: 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: CheckNameResult or the result of cls(response) + :rtype: ~azure.mgmt.digitaltwins.v2022_05_31.models.CheckNameResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def check_name_availability( + self, location: str, digital_twins_instance_check_name: Union[_models.CheckNameRequest, IO], **kwargs: Any + ) -> _models.CheckNameResult: + """Check if a DigitalTwinsInstance name is available. + + :param location: Location of DigitalTwinsInstance. Required. + :type location: str + :param digital_twins_instance_check_name: Set the name parameter in the + DigitalTwinsInstanceCheckName structure to the name of the DigitalTwinsInstance to check. Is + either a model type or a IO type. Required. + :type digital_twins_instance_check_name: + ~azure.mgmt.digitaltwins.v2022_05_31.models.CheckNameRequest 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: CheckNameResult or the result of cls(response) + :rtype: ~azure.mgmt.digitaltwins.v2022_05_31.models.CheckNameResult + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.CheckNameResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', "2022-05-31") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.CheckNameResult] = kwargs.pop("cls", None) - _json = self._serialize.body(digital_twins_instance_check_name, 'CheckNameRequest') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(digital_twins_instance_check_name, (IO, bytes)): + _content = digital_twins_instance_check_name + else: + _json = self._serialize.body(digital_twins_instance_check_name, "CheckNameRequest") request = build_check_name_availability_request( - subscription_id=self._config.subscription_id, location=location, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self.check_name_availability.metadata['url'], + content=_content, + template_url=self.check_name_availability.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -695,12 +1017,13 @@ async def check_name_availability( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('CheckNameResult', pipeline_response) + deserialized = self._deserialize("CheckNameResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - check_name_availability.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.DigitalTwins/locations/{location}/checkNameAvailability"} # type: ignore - + check_name_availability.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.DigitalTwins/locations/{location}/checkNameAvailability" + } diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/aio/operations/_operations.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/aio/operations/_operations.py index a59d62729f047..b32f950ea4254 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/aio/operations/_operations.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/aio/operations/_operations.py @@ -6,79 +6,105 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models from ..._vendor import _convert_request from ...operations._operations import build_list_request -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class Operations: - """Operations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class Operations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.digitaltwins.v2022_05_31.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.digitaltwins.v2022_05_31.aio.AzureDigitalTwinsManagementClient`'s + :attr:`operations` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace - def list( - self, - **kwargs: Any - ) -> AsyncIterable["_models.OperationListResult"]: + def list(self, **kwargs: Any) -> AsyncIterable["_models.Operation"]: """Lists all of the available DigitalTwins service REST API operations. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either OperationListResult or the result of cls(response) + :return: An iterator like instance of either Operation or the result of cls(response) :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.digitaltwins.v2022_05_31.models.OperationListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.digitaltwins.v2022_05_31.models.Operation] + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2022-05-31") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) - cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationListResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( api_version=api_version, - template_url=self.list.metadata['url'], + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: - - request = build_list_request( - api_version=api_version, - template_url=next_link, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) @@ -89,16 +115,14 @@ async def extract_data(pipeline_response): deserialized = self._deserialize("OperationListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -109,8 +133,6 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/providers/Microsoft.DigitalTwins/operations"} # type: ignore + list.metadata = {"url": "/providers/Microsoft.DigitalTwins/operations"} diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/aio/operations/_patch.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/aio/operations/_patch.py new file mode 100644 index 0000000000000..f7dd32510333d --- /dev/null +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/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/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/aio/operations/_private_endpoint_connections_operations.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/aio/operations/_private_endpoint_connections_operations.py index 1da1a42cf8403..016e498f2e517 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/aio/operations/_private_endpoint_connections_operations.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/aio/operations/_private_endpoint_connections_operations.py @@ -6,88 +6,108 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Optional, TypeVar, Union - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import sys +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, cast, 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.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod 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 azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models from ..._vendor import _convert_request -from ...operations._private_endpoint_connections_operations import build_create_or_update_request_initial, build_delete_request_initial, build_get_request, build_list_request -T = TypeVar('T') +from ...operations._private_endpoint_connections_operations import ( + build_create_or_update_request, + build_delete_request, + build_get_request, + build_list_request, +) + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class PrivateEndpointConnectionsOperations: - """PrivateEndpointConnectionsOperations 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 PrivateEndpointConnectionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.digitaltwins.v2022_05_31.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.digitaltwins.v2022_05_31.aio.AzureDigitalTwinsManagementClient`'s + :attr:`private_endpoint_connections` 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 list( - self, - resource_group_name: str, - resource_name: str, - **kwargs: Any - ) -> "_models.PrivateEndpointConnectionsResponse": + self, resource_group_name: str, resource_name: str, **kwargs: Any + ) -> _models.PrivateEndpointConnectionsResponse: """List private endpoint connection properties. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: PrivateEndpointConnectionsResponse, or the result of cls(response) + :return: PrivateEndpointConnectionsResponse or the result of cls(response) :rtype: ~azure.mgmt.digitaltwins.v2022_05_31.models.PrivateEndpointConnectionsResponse - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnectionsResponse"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', "2022-05-31") # type: str + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + cls: ClsType[_models.PrivateEndpointConnectionsResponse] = kwargs.pop("cls", None) - request = build_list_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list.metadata['url'], + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -95,63 +115,66 @@ async def list( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('PrivateEndpointConnectionsResponse', pipeline_response) + deserialized = self._deserialize("PrivateEndpointConnectionsResponse", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - list.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections"} # type: ignore - + list.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections" + } @distributed_trace_async async def get( - self, - resource_group_name: str, - resource_name: str, - private_endpoint_connection_name: str, - **kwargs: Any - ) -> "_models.PrivateEndpointConnection": + self, resource_group_name: str, resource_name: str, private_endpoint_connection_name: str, **kwargs: Any + ) -> _models.PrivateEndpointConnection: """Get private endpoint connection properties for the given private endpoint. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param private_endpoint_connection_name: The name of the private endpoint connection. + :param private_endpoint_connection_name: The name of the private endpoint connection. Required. :type private_endpoint_connection_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: PrivateEndpointConnection, or the result of cls(response) + :return: PrivateEndpointConnection or the result of cls(response) :rtype: ~azure.mgmt.digitaltwins.v2022_05_31.models.PrivateEndpointConnection - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnection"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2022-05-31") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + cls: ClsType[_models.PrivateEndpointConnection] = kwargs.pop("cls", None) - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, private_endpoint_connection_name=private_endpoint_connection_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -159,76 +182,77 @@ async def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore - + get.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}" + } async def _delete_initial( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - resource_name: str, - private_endpoint_connection_name: str, - **kwargs: Any + self, resource_group_name: str, resource_name: str, private_endpoint_connection_name: str, **kwargs: Any ) -> None: - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2022-05-31") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - request = build_delete_request_initial( - subscription_id=self._config.subscription_id, + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + cls: ClsType[None] = kwargs.pop("cls", None) + + request = build_delete_request( resource_group_name=resource_group_name, resource_name=resource_name, private_endpoint_connection_name=private_endpoint_connection_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._delete_initial.metadata['url'], + template_url=self._delete_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - _delete_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore - + _delete_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}" + } @distributed_trace_async - async def begin_delete( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - resource_name: str, - private_endpoint_connection_name: str, - **kwargs: Any + async def begin_delete( + self, resource_group_name: str, resource_name: str, private_endpoint_connection_name: str, **kwargs: Any ) -> AsyncLROPoller[None]: """Delete private endpoint connection with the specified name. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param private_endpoint_connection_name: The name of the private endpoint connection. + :param private_endpoint_connection_name: The name of the private endpoint connection. Required. :type private_endpoint_connection_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. @@ -240,124 +264,152 @@ async def begin_delete( # pylint: disable=inconsistent-return-statements Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2022-05-31") # type: str - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType[None] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: - raw_result = await self._delete_initial( + raw_result = await self._delete_initial( # type: ignore resource_group_name=resource_group_name, resource_name=resource_name, private_endpoint_connection_name=private_endpoint_connection_name, api_version=api_version, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - - if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - begin_delete.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore + begin_delete.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}" + } async def _create_or_update_initial( self, resource_group_name: str, resource_name: str, private_endpoint_connection_name: str, - private_endpoint_connection: "_models.PrivateEndpointConnection", + private_endpoint_connection: Union[_models.PrivateEndpointConnection, IO], **kwargs: Any - ) -> "_models.PrivateEndpointConnection": - cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnection"] + ) -> _models.PrivateEndpointConnection: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2022-05-31") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(private_endpoint_connection, 'PrivateEndpointConnection') + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PrivateEndpointConnection] = kwargs.pop("cls", None) - request = build_create_or_update_request_initial( - subscription_id=self._config.subscription_id, + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(private_endpoint_connection, (IO, bytes)): + _content = private_endpoint_connection + else: + _json = self._serialize.body(private_endpoint_connection, "PrivateEndpointConnection") + + request = build_create_or_update_request( resource_group_name=resource_group_name, resource_name=resource_name, private_endpoint_connection_name=private_endpoint_connection_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._create_or_update_initial.metadata['url'], + content=_content, + template_url=self._create_or_update_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) if response.status_code == 202: - deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - _create_or_update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore + return deserialized # type: ignore + _create_or_update_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}" + } - @distributed_trace_async + @overload async def begin_create_or_update( self, resource_group_name: str, resource_name: str, private_endpoint_connection_name: str, - private_endpoint_connection: "_models.PrivateEndpointConnection", + private_endpoint_connection: _models.PrivateEndpointConnection, + *, + content_type: str = "application/json", **kwargs: Any - ) -> AsyncLROPoller["_models.PrivateEndpointConnection"]: + ) -> AsyncLROPoller[_models.PrivateEndpointConnection]: """Update the status of a private endpoint connection with the given name. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param private_endpoint_connection_name: The name of the private endpoint connection. + :param private_endpoint_connection_name: The name of the private endpoint connection. Required. :type private_endpoint_connection_name: str :param private_endpoint_connection: The private endpoint connection with updated properties. + Required. :type private_endpoint_connection: ~azure.mgmt.digitaltwins.v2022_05_31.models.PrivateEndpointConnection + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for @@ -370,17 +422,98 @@ async def begin_create_or_update( result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2022_05_31.models.PrivateEndpointConnection] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2022-05-31") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnection"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + private_endpoint_connection_name: str, + private_endpoint_connection: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.PrivateEndpointConnection]: + """Update the status of a private endpoint connection with the given name. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param private_endpoint_connection_name: The name of the private endpoint connection. Required. + :type private_endpoint_connection_name: str + :param private_endpoint_connection: The private endpoint connection with updated properties. + Required. + :type private_endpoint_connection: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either PrivateEndpointConnection or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2022_05_31.models.PrivateEndpointConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + private_endpoint_connection_name: str, + private_endpoint_connection: Union[_models.PrivateEndpointConnection, IO], + **kwargs: Any + ) -> AsyncLROPoller[_models.PrivateEndpointConnection]: + """Update the status of a private endpoint connection with the given name. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param private_endpoint_connection_name: The name of the private endpoint connection. Required. + :type private_endpoint_connection_name: str + :param private_endpoint_connection: The private endpoint connection with updated properties. Is + either a model type or a IO type. Required. + :type private_endpoint_connection: + ~azure.mgmt.digitaltwins.v2022_05_31.models.PrivateEndpointConnection or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either PrivateEndpointConnection or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2022_05_31.models.PrivateEndpointConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PrivateEndpointConnection] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = await self._create_or_update_initial( resource_group_name=resource_group_name, @@ -389,29 +522,34 @@ async def begin_create_or_update( private_endpoint_connection=private_endpoint_connection, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - begin_create_or_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore + begin_create_or_update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}" + } diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/aio/operations/_private_link_resources_operations.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/aio/operations/_private_link_resources_operations.py index 98edbf3ce607a..531de78e8238f 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/aio/operations/_private_link_resources_operations.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/aio/operations/_private_link_resources_operations.py @@ -6,86 +6,101 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, Callable, Dict, Optional, TypeVar -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_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models from ..._vendor import _convert_request from ...operations._private_link_resources_operations import build_get_request, build_list_request -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class PrivateLinkResourcesOperations: - """PrivateLinkResourcesOperations 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 PrivateLinkResourcesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.digitaltwins.v2022_05_31.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.digitaltwins.v2022_05_31.aio.AzureDigitalTwinsManagementClient`'s + :attr:`private_link_resources` 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 list( - self, - resource_group_name: str, - resource_name: str, - **kwargs: Any - ) -> "_models.GroupIdInformationResponse": + self, resource_group_name: str, resource_name: str, **kwargs: Any + ) -> _models.GroupIdInformationResponse: """List private link resources for given Digital Twin. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: GroupIdInformationResponse, or the result of cls(response) + :return: GroupIdInformationResponse or the result of cls(response) :rtype: ~azure.mgmt.digitaltwins.v2022_05_31.models.GroupIdInformationResponse - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.GroupIdInformationResponse"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2022-05-31") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + cls: ClsType[_models.GroupIdInformationResponse] = kwargs.pop("cls", None) - request = build_list_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list.metadata['url'], + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -93,63 +108,66 @@ async def list( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('GroupIdInformationResponse', pipeline_response) + deserialized = self._deserialize("GroupIdInformationResponse", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - list.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateLinkResources"} # type: ignore - + list.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateLinkResources" + } @distributed_trace_async async def get( - self, - resource_group_name: str, - resource_name: str, - resource_id: str, - **kwargs: Any - ) -> "_models.GroupIdInformation": + self, resource_group_name: str, resource_name: str, resource_id: str, **kwargs: Any + ) -> _models.GroupIdInformation: """Get the specified private link resource for the given Digital Twin. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param resource_id: The name of the private link resource. + :param resource_id: The name of the private link resource. Required. :type resource_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: GroupIdInformation, or the result of cls(response) + :return: GroupIdInformation or the result of cls(response) :rtype: ~azure.mgmt.digitaltwins.v2022_05_31.models.GroupIdInformation - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.GroupIdInformation"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2022-05-31") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + cls: ClsType[_models.GroupIdInformation] = kwargs.pop("cls", None) - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, resource_id=resource_id, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -157,12 +175,13 @@ async def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('GroupIdInformation', pipeline_response) + deserialized = self._deserialize("GroupIdInformation", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateLinkResources/{resourceId}"} # type: ignore - + get.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateLinkResources/{resourceId}" + } diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/aio/operations/_time_series_database_connections_operations.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/aio/operations/_time_series_database_connections_operations.py index c28a2a181ebe2..7b4795ed70c1f 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/aio/operations/_time_series_database_connections_operations.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/aio/operations/_time_series_database_connections_operations.py @@ -6,96 +6,124 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar, Union +import sys +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models from ..._vendor import _convert_request -from ...operations._time_series_database_connections_operations import build_create_or_update_request_initial, build_delete_request_initial, build_get_request, build_list_request -T = TypeVar('T') +from ...operations._time_series_database_connections_operations import ( + build_create_or_update_request, + build_delete_request, + build_get_request, + build_list_request, +) + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class TimeSeriesDatabaseConnectionsOperations: - """TimeSeriesDatabaseConnectionsOperations 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 TimeSeriesDatabaseConnectionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.digitaltwins.v2022_05_31.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.digitaltwins.v2022_05_31.aio.AzureDigitalTwinsManagementClient`'s + :attr:`time_series_database_connections` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list( - self, - resource_group_name: str, - resource_name: str, - **kwargs: Any - ) -> AsyncIterable["_models.TimeSeriesDatabaseConnectionListResult"]: + self, resource_group_name: str, resource_name: str, **kwargs: Any + ) -> AsyncIterable["_models.TimeSeriesDatabaseConnection"]: """Get all existing time series database connections for this DigitalTwins instance. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either TimeSeriesDatabaseConnectionListResult or the - result of cls(response) + :return: An iterator like instance of either TimeSeriesDatabaseConnection or the result of + cls(response) :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.digitaltwins.v2022_05_31.models.TimeSeriesDatabaseConnectionListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.digitaltwins.v2022_05_31.models.TimeSeriesDatabaseConnection] + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2022-05-31") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + cls: ClsType[_models.TimeSeriesDatabaseConnectionListResult] = kwargs.pop("cls", None) - cls = kwargs.pop('cls', None) # type: ClsType["_models.TimeSeriesDatabaseConnectionListResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list.metadata['url'], + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: - - request = build_list_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - resource_name=resource_name, - api_version=api_version, - template_url=next_link, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) @@ -106,16 +134,14 @@ async def extract_data(pipeline_response): deserialized = self._deserialize("TimeSeriesDatabaseConnectionListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -126,59 +152,61 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections"} # type: ignore + list.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections" + } @distributed_trace_async async def get( - self, - resource_group_name: str, - resource_name: str, - time_series_database_connection_name: str, - **kwargs: Any - ) -> "_models.TimeSeriesDatabaseConnection": + self, resource_group_name: str, resource_name: str, time_series_database_connection_name: str, **kwargs: Any + ) -> _models.TimeSeriesDatabaseConnection: """Get the description of an existing time series database connection. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param time_series_database_connection_name: Name of time series database connection. + :param time_series_database_connection_name: Name of time series database connection. Required. :type time_series_database_connection_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: TimeSeriesDatabaseConnection, or the result of cls(response) + :return: TimeSeriesDatabaseConnection or the result of cls(response) :rtype: ~azure.mgmt.digitaltwins.v2022_05_31.models.TimeSeriesDatabaseConnection - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.TimeSeriesDatabaseConnection"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', "2022-05-31") # type: str + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + cls: ClsType[_models.TimeSeriesDatabaseConnection] = kwargs.pop("cls", None) - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, time_series_database_connection_name=time_series_database_connection_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -186,72 +214,172 @@ async def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('TimeSeriesDatabaseConnection', pipeline_response) + deserialized = self._deserialize("TimeSeriesDatabaseConnection", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections/{timeSeriesDatabaseConnectionName}"} # type: ignore - + get.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections/{timeSeriesDatabaseConnectionName}" + } async def _create_or_update_initial( self, resource_group_name: str, resource_name: str, time_series_database_connection_name: str, - time_series_database_connection_description: "_models.TimeSeriesDatabaseConnection", + time_series_database_connection_description: Union[_models.TimeSeriesDatabaseConnection, IO], **kwargs: Any - ) -> "_models.TimeSeriesDatabaseConnection": - cls = kwargs.pop('cls', None) # type: ClsType["_models.TimeSeriesDatabaseConnection"] + ) -> _models.TimeSeriesDatabaseConnection: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2022-05-31") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(time_series_database_connection_description, 'TimeSeriesDatabaseConnection') + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.TimeSeriesDatabaseConnection] = kwargs.pop("cls", None) - request = build_create_or_update_request_initial( - subscription_id=self._config.subscription_id, + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(time_series_database_connection_description, (IO, bytes)): + _content = time_series_database_connection_description + else: + _json = self._serialize.body(time_series_database_connection_description, "TimeSeriesDatabaseConnection") + + request = build_create_or_update_request( resource_group_name=resource_group_name, resource_name=resource_name, time_series_database_connection_name=time_series_database_connection_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._create_or_update_initial.metadata['url'], + content=_content, + template_url=self._create_or_update_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('TimeSeriesDatabaseConnection', pipeline_response) + deserialized = self._deserialize("TimeSeriesDatabaseConnection", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('TimeSeriesDatabaseConnection', pipeline_response) + deserialized = self._deserialize("TimeSeriesDatabaseConnection", pipeline_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized + return deserialized # type: ignore + + _create_or_update_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections/{timeSeriesDatabaseConnectionName}" + } + + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + time_series_database_connection_name: str, + time_series_database_connection_description: _models.TimeSeriesDatabaseConnection, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.TimeSeriesDatabaseConnection]: + """Create or update a time series database connection. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param time_series_database_connection_name: Name of time series database connection. Required. + :type time_series_database_connection_name: str + :param time_series_database_connection_description: The time series database connection + description. Required. + :type time_series_database_connection_description: + ~azure.mgmt.digitaltwins.v2022_05_31.models.TimeSeriesDatabaseConnection + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either TimeSeriesDatabaseConnection or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2022_05_31.models.TimeSeriesDatabaseConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ - _create_or_update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections/{timeSeriesDatabaseConnectionName}"} # type: ignore + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + time_series_database_connection_name: str, + time_series_database_connection_description: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.TimeSeriesDatabaseConnection]: + """Create or update a time series database connection. + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param time_series_database_connection_name: Name of time series database connection. Required. + :type time_series_database_connection_name: str + :param time_series_database_connection_description: The time series database connection + description. Required. + :type time_series_database_connection_description: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either TimeSeriesDatabaseConnection or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2022_05_31.models.TimeSeriesDatabaseConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace_async async def begin_create_or_update( @@ -259,22 +387,25 @@ async def begin_create_or_update( resource_group_name: str, resource_name: str, time_series_database_connection_name: str, - time_series_database_connection_description: "_models.TimeSeriesDatabaseConnection", + time_series_database_connection_description: Union[_models.TimeSeriesDatabaseConnection, IO], **kwargs: Any - ) -> AsyncLROPoller["_models.TimeSeriesDatabaseConnection"]: + ) -> AsyncLROPoller[_models.TimeSeriesDatabaseConnection]: """Create or update a time series database connection. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param time_series_database_connection_name: Name of time series database connection. + :param time_series_database_connection_name: Name of time series database connection. Required. :type time_series_database_connection_name: str :param time_series_database_connection_description: The time series database connection - description. + description. Is either a model type or a IO type. Required. :type time_series_database_connection_description: - ~azure.mgmt.digitaltwins.v2022_05_31.models.TimeSeriesDatabaseConnection + ~azure.mgmt.digitaltwins.v2022_05_31.models.TimeSeriesDatabaseConnection or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for @@ -287,17 +418,17 @@ async def begin_create_or_update( result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2022_05_31.models.TimeSeriesDatabaseConnection] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2022-05-31") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.TimeSeriesDatabaseConnection"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.TimeSeriesDatabaseConnection] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = await self._create_or_update_initial( resource_group_name=resource_group_name, @@ -306,102 +437,107 @@ async def begin_create_or_update( time_series_database_connection_description=time_series_database_connection_description, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('TimeSeriesDatabaseConnection', pipeline_response) + deserialized = self._deserialize("TimeSeriesDatabaseConnection", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - begin_create_or_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections/{timeSeriesDatabaseConnectionName}"} # type: ignore + begin_create_or_update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections/{timeSeriesDatabaseConnectionName}" + } async def _delete_initial( - self, - resource_group_name: str, - resource_name: str, - time_series_database_connection_name: str, - **kwargs: Any - ) -> Optional["_models.TimeSeriesDatabaseConnection"]: - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.TimeSeriesDatabaseConnection"]] + self, resource_group_name: str, resource_name: str, time_series_database_connection_name: str, **kwargs: Any + ) -> Optional[_models.TimeSeriesDatabaseConnection]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2022-05-31") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - request = build_delete_request_initial( - subscription_id=self._config.subscription_id, + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + cls: ClsType[Optional[_models.TimeSeriesDatabaseConnection]] = kwargs.pop("cls", None) + + request = build_delete_request( resource_group_name=resource_group_name, resource_name=resource_name, time_series_database_connection_name=time_series_database_connection_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._delete_initial.metadata['url'], + template_url=self._delete_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('TimeSeriesDatabaseConnection', pipeline_response) + deserialized = self._deserialize("TimeSeriesDatabaseConnection", pipeline_response) if response.status_code == 202: - deserialized = self._deserialize('TimeSeriesDatabaseConnection', pipeline_response) + deserialized = self._deserialize("TimeSeriesDatabaseConnection", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _delete_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections/{timeSeriesDatabaseConnectionName}"} # type: ignore - + _delete_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections/{timeSeriesDatabaseConnectionName}" + } @distributed_trace_async async def begin_delete( - self, - resource_group_name: str, - resource_name: str, - time_series_database_connection_name: str, - **kwargs: Any - ) -> AsyncLROPoller["_models.TimeSeriesDatabaseConnection"]: + self, resource_group_name: str, resource_name: str, time_series_database_connection_name: str, **kwargs: Any + ) -> AsyncLROPoller[_models.TimeSeriesDatabaseConnection]: """Delete a time series database connection. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param time_series_database_connection_name: Name of time series database connection. + :param time_series_database_connection_name: Name of time series database connection. Required. :type time_series_database_connection_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. @@ -415,45 +551,50 @@ async def begin_delete( result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2022_05_31.models.TimeSeriesDatabaseConnection] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2022-05-31") # type: str - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.TimeSeriesDatabaseConnection"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + cls: ClsType[_models.TimeSeriesDatabaseConnection] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = await self._delete_initial( resource_group_name=resource_group_name, resource_name=resource_name, time_series_database_connection_name=time_series_database_connection_name, api_version=api_version, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('TimeSeriesDatabaseConnection', pipeline_response) + deserialized = self._deserialize("TimeSeriesDatabaseConnection", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = AsyncARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - begin_delete.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections/{timeSeriesDatabaseConnectionName}"} # type: ignore + begin_delete.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections/{timeSeriesDatabaseConnectionName}" + } diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/models/__init__.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/models/__init__.py index 3893252166778..1816c624f2c49 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/models/__init__.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/models/__init__.py @@ -41,67 +41,69 @@ from ._models_py3 import TimeSeriesDatabaseConnectionListResult from ._models_py3 import TimeSeriesDatabaseConnectionProperties - -from ._azure_digital_twins_management_client_enums import ( - AuthenticationType, - ConnectionPropertiesProvisioningState, - ConnectionType, - CreatedByType, - DigitalTwinsIdentityType, - EndpointProvisioningState, - EndpointType, - PrivateLinkServiceConnectionStatus, - ProvisioningState, - PublicNetworkAccess, - Reason, - TimeSeriesDatabaseConnectionState, -) +from ._azure_digital_twins_management_client_enums import AuthenticationType +from ._azure_digital_twins_management_client_enums import ConnectionPropertiesProvisioningState +from ._azure_digital_twins_management_client_enums import ConnectionType +from ._azure_digital_twins_management_client_enums import CreatedByType +from ._azure_digital_twins_management_client_enums import DigitalTwinsIdentityType +from ._azure_digital_twins_management_client_enums import EndpointProvisioningState +from ._azure_digital_twins_management_client_enums import EndpointType +from ._azure_digital_twins_management_client_enums import PrivateLinkServiceConnectionStatus +from ._azure_digital_twins_management_client_enums import ProvisioningState +from ._azure_digital_twins_management_client_enums import PublicNetworkAccess +from ._azure_digital_twins_management_client_enums import Reason +from ._azure_digital_twins_management_client_enums import TimeSeriesDatabaseConnectionState +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk __all__ = [ - 'AzureDataExplorerConnectionProperties', - 'CheckNameRequest', - 'CheckNameResult', - 'ConnectionProperties', - 'ConnectionPropertiesPrivateLinkServiceConnectionState', - 'ConnectionState', - 'DigitalTwinsDescription', - 'DigitalTwinsDescriptionListResult', - 'DigitalTwinsEndpointResource', - 'DigitalTwinsEndpointResourceListResult', - 'DigitalTwinsEndpointResourceProperties', - 'DigitalTwinsIdentity', - 'DigitalTwinsPatchDescription', - 'DigitalTwinsPatchProperties', - 'DigitalTwinsResource', - 'ErrorDefinition', - 'ErrorResponse', - 'EventGrid', - 'EventHub', - 'ExternalResource', - 'GroupIdInformation', - 'GroupIdInformationProperties', - 'GroupIdInformationResponse', - 'Operation', - 'OperationDisplay', - 'OperationListResult', - 'PrivateEndpoint', - 'PrivateEndpointConnection', - 'PrivateEndpointConnectionsResponse', - 'ServiceBus', - 'SystemData', - 'TimeSeriesDatabaseConnection', - 'TimeSeriesDatabaseConnectionListResult', - 'TimeSeriesDatabaseConnectionProperties', - 'AuthenticationType', - 'ConnectionPropertiesProvisioningState', - 'ConnectionType', - 'CreatedByType', - 'DigitalTwinsIdentityType', - 'EndpointProvisioningState', - 'EndpointType', - 'PrivateLinkServiceConnectionStatus', - 'ProvisioningState', - 'PublicNetworkAccess', - 'Reason', - 'TimeSeriesDatabaseConnectionState', + "AzureDataExplorerConnectionProperties", + "CheckNameRequest", + "CheckNameResult", + "ConnectionProperties", + "ConnectionPropertiesPrivateLinkServiceConnectionState", + "ConnectionState", + "DigitalTwinsDescription", + "DigitalTwinsDescriptionListResult", + "DigitalTwinsEndpointResource", + "DigitalTwinsEndpointResourceListResult", + "DigitalTwinsEndpointResourceProperties", + "DigitalTwinsIdentity", + "DigitalTwinsPatchDescription", + "DigitalTwinsPatchProperties", + "DigitalTwinsResource", + "ErrorDefinition", + "ErrorResponse", + "EventGrid", + "EventHub", + "ExternalResource", + "GroupIdInformation", + "GroupIdInformationProperties", + "GroupIdInformationResponse", + "Operation", + "OperationDisplay", + "OperationListResult", + "PrivateEndpoint", + "PrivateEndpointConnection", + "PrivateEndpointConnectionsResponse", + "ServiceBus", + "SystemData", + "TimeSeriesDatabaseConnection", + "TimeSeriesDatabaseConnectionListResult", + "TimeSeriesDatabaseConnectionProperties", + "AuthenticationType", + "ConnectionPropertiesProvisioningState", + "ConnectionType", + "CreatedByType", + "DigitalTwinsIdentityType", + "EndpointProvisioningState", + "EndpointType", + "PrivateLinkServiceConnectionStatus", + "ProvisioningState", + "PublicNetworkAccess", + "Reason", + "TimeSeriesDatabaseConnectionState", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/models/_azure_digital_twins_management_client_enums.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/models/_azure_digital_twins_management_client_enums.py index ad0b25b898492..696b5690cf628 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/models/_azure_digital_twins_management_client_enums.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/models/_azure_digital_twins_management_client_enums.py @@ -7,11 +7,10 @@ # -------------------------------------------------------------------------- from enum import Enum -from six import with_metaclass from azure.core import CaseInsensitiveEnumMeta -class AuthenticationType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): +class AuthenticationType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Specifies the authentication type being used for connecting to the endpoint. Defaults to 'KeyBased'. If 'KeyBased' is selected, a connection string must be specified (at least the primary connection string). If 'IdentityBased' is select, the endpointUri and entityPath @@ -21,31 +20,32 @@ class AuthenticationType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): KEY_BASED = "KeyBased" IDENTITY_BASED = "IdentityBased" -class ConnectionPropertiesProvisioningState(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The provisioning state. - """ + +class ConnectionPropertiesProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The provisioning state.""" PENDING = "Pending" APPROVED = "Approved" REJECTED = "Rejected" DISCONNECTED = "Disconnected" -class ConnectionType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The type of time series connection resource. - """ + +class ConnectionType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of time series connection resource.""" AZURE_DATA_EXPLORER = "AzureDataExplorer" -class CreatedByType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The type of identity that created the resource. - """ + +class CreatedByType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of identity that created the resource.""" USER = "User" APPLICATION = "Application" MANAGED_IDENTITY = "ManagedIdentity" KEY = "Key" -class DigitalTwinsIdentityType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): + +class DigitalTwinsIdentityType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The type of Managed Identity used by the DigitalTwinsInstance. Only SystemAssigned is supported. """ @@ -53,9 +53,9 @@ class DigitalTwinsIdentityType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum NONE = "None" SYSTEM_ASSIGNED = "SystemAssigned" -class EndpointProvisioningState(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The provisioning state. - """ + +class EndpointProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The provisioning state.""" PROVISIONING = "Provisioning" DELETING = "Deleting" @@ -70,26 +70,26 @@ class EndpointProvisioningState(with_metaclass(CaseInsensitiveEnumMeta, str, Enu MOVING = "Moving" DISABLED = "Disabled" -class EndpointType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The type of Digital Twins endpoint - """ + +class EndpointType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of Digital Twins endpoint.""" EVENT_HUB = "EventHub" EVENT_GRID = "EventGrid" SERVICE_BUS = "ServiceBus" -class PrivateLinkServiceConnectionStatus(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The status of a private endpoint connection. - """ + +class PrivateLinkServiceConnectionStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The status of a private endpoint connection.""" PENDING = "Pending" APPROVED = "Approved" REJECTED = "Rejected" DISCONNECTED = "Disconnected" -class ProvisioningState(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The provisioning state. - """ + +class ProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The provisioning state.""" PROVISIONING = "Provisioning" DELETING = "Deleting" @@ -103,23 +103,23 @@ class ProvisioningState(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): RESTORING = "Restoring" MOVING = "Moving" -class PublicNetworkAccess(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """Public network access for the DigitalTwinsInstance. - """ + +class PublicNetworkAccess(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Public network access for the DigitalTwinsInstance.""" ENABLED = "Enabled" DISABLED = "Disabled" -class Reason(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """Message providing the reason why the given name is invalid. - """ + +class Reason(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Message providing the reason why the given name is invalid.""" INVALID = "Invalid" ALREADY_EXISTS = "AlreadyExists" -class TimeSeriesDatabaseConnectionState(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): - """The provisioning state. - """ + +class TimeSeriesDatabaseConnectionState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The provisioning state.""" PROVISIONING = "Provisioning" DELETING = "Deleting" diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/models/_models_py3.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/models/_models_py3.py index 86a68f593c253..efbd8749b7d0e 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/models/_models_py3.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/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,56 +8,51 @@ # -------------------------------------------------------------------------- import datetime -from typing import Dict, List, Optional, Union +from typing import Dict, List, Optional, TYPE_CHECKING, Union -from azure.core.exceptions import HttpResponseError -import msrest.serialization +from ... import _serialization -from ._azure_digital_twins_management_client_enums import * +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from .. import models as _models -class TimeSeriesDatabaseConnectionProperties(msrest.serialization.Model): +class TimeSeriesDatabaseConnectionProperties(_serialization.Model): """Properties of a time series database connection resource. - You probably want to use the sub-classes and not this class directly. Known - sub-classes are: AzureDataExplorerConnectionProperties. + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + AzureDataExplorerConnectionProperties Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. - :ivar connection_type: Required. The type of time series connection resource.Constant filled by - server. Possible values include: "AzureDataExplorer". + :ivar connection_type: The type of time series connection resource. Required. + "AzureDataExplorer" :vartype connection_type: str or ~azure.mgmt.digitaltwins.v2022_05_31.models.ConnectionType - :ivar provisioning_state: The provisioning state. Possible values include: "Provisioning", - "Deleting", "Updating", "Succeeded", "Failed", "Canceled", "Deleted", "Warning", "Suspending", - "Restoring", "Moving", "Disabled". + :ivar provisioning_state: The provisioning state. Known values are: "Provisioning", "Deleting", + "Updating", "Succeeded", "Failed", "Canceled", "Deleted", "Warning", "Suspending", "Restoring", + "Moving", and "Disabled". :vartype provisioning_state: str or ~azure.mgmt.digitaltwins.v2022_05_31.models.TimeSeriesDatabaseConnectionState """ _validation = { - 'connection_type': {'required': True}, - 'provisioning_state': {'readonly': True}, + "connection_type": {"required": True}, + "provisioning_state": {"readonly": True}, } _attribute_map = { - 'connection_type': {'key': 'connectionType', 'type': 'str'}, - 'provisioning_state': {'key': 'provisioningState', 'type': 'str'}, + "connection_type": {"key": "connectionType", "type": "str"}, + "provisioning_state": {"key": "provisioningState", "type": "str"}, } - _subtype_map = { - 'connection_type': {'AzureDataExplorer': 'AzureDataExplorerConnectionProperties'} - } + _subtype_map = {"connection_type": {"AzureDataExplorer": "AzureDataExplorerConnectionProperties"}} - def __init__( - self, - **kwargs - ): - """ - """ - super(TimeSeriesDatabaseConnectionProperties, self).__init__(**kwargs) - self.connection_type = None # type: Optional[str] + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.connection_type: Optional[str] = None self.provisioning_state = None @@ -67,29 +63,29 @@ class AzureDataExplorerConnectionProperties(TimeSeriesDatabaseConnectionProperti All required parameters must be populated in order to send to Azure. - :ivar connection_type: Required. The type of time series connection resource.Constant filled by - server. Possible values include: "AzureDataExplorer". + :ivar connection_type: The type of time series connection resource. Required. + "AzureDataExplorer" :vartype connection_type: str or ~azure.mgmt.digitaltwins.v2022_05_31.models.ConnectionType - :ivar provisioning_state: The provisioning state. Possible values include: "Provisioning", - "Deleting", "Updating", "Succeeded", "Failed", "Canceled", "Deleted", "Warning", "Suspending", - "Restoring", "Moving", "Disabled". + :ivar provisioning_state: The provisioning state. Known values are: "Provisioning", "Deleting", + "Updating", "Succeeded", "Failed", "Canceled", "Deleted", "Warning", "Suspending", "Restoring", + "Moving", and "Disabled". :vartype provisioning_state: str or ~azure.mgmt.digitaltwins.v2022_05_31.models.TimeSeriesDatabaseConnectionState - :ivar adx_resource_id: Required. The resource ID of the Azure Data Explorer cluster. + :ivar adx_resource_id: The resource ID of the Azure Data Explorer cluster. Required. :vartype adx_resource_id: str - :ivar adx_endpoint_uri: Required. The URI of the Azure Data Explorer endpoint. + :ivar adx_endpoint_uri: The URI of the Azure Data Explorer endpoint. Required. :vartype adx_endpoint_uri: str - :ivar adx_database_name: Required. The name of the Azure Data Explorer database. + :ivar adx_database_name: The name of the Azure Data Explorer database. Required. :vartype adx_database_name: str - :ivar adx_table_name: The name of the Azure Data Explorer table. + :ivar adx_table_name: The name of the Azure Data Explorer table. Defaults to AdtPropertyEvents. :vartype adx_table_name: str - :ivar event_hub_endpoint_uri: Required. The URL of the EventHub namespace for identity-based - authentication. It must include the protocol sb://. + :ivar event_hub_endpoint_uri: The URL of the EventHub namespace for identity-based + authentication. It must include the protocol sb://. Required. :vartype event_hub_endpoint_uri: str - :ivar event_hub_entity_path: Required. The EventHub name in the EventHub namespace for - identity-based authentication. + :ivar event_hub_entity_path: The EventHub name in the EventHub namespace for identity-based + authentication. Required. :vartype event_hub_entity_path: str - :ivar event_hub_namespace_resource_id: Required. The resource ID of the EventHub namespace. + :ivar event_hub_namespace_resource_id: The resource ID of the EventHub namespace. Required. :vartype event_hub_namespace_resource_id: str :ivar event_hub_consumer_group: The EventHub consumer group to use when ADX reads from EventHub. Defaults to $Default. @@ -97,27 +93,27 @@ class AzureDataExplorerConnectionProperties(TimeSeriesDatabaseConnectionProperti """ _validation = { - 'connection_type': {'required': True}, - 'provisioning_state': {'readonly': True}, - 'adx_resource_id': {'required': True}, - 'adx_endpoint_uri': {'required': True}, - 'adx_database_name': {'required': True}, - 'event_hub_endpoint_uri': {'required': True}, - 'event_hub_entity_path': {'required': True}, - 'event_hub_namespace_resource_id': {'required': True}, + "connection_type": {"required": True}, + "provisioning_state": {"readonly": True}, + "adx_resource_id": {"required": True}, + "adx_endpoint_uri": {"required": True}, + "adx_database_name": {"required": True}, + "event_hub_endpoint_uri": {"required": True}, + "event_hub_entity_path": {"required": True}, + "event_hub_namespace_resource_id": {"required": True}, } _attribute_map = { - 'connection_type': {'key': 'connectionType', 'type': 'str'}, - 'provisioning_state': {'key': 'provisioningState', 'type': 'str'}, - 'adx_resource_id': {'key': 'adxResourceId', 'type': 'str'}, - 'adx_endpoint_uri': {'key': 'adxEndpointUri', 'type': 'str'}, - 'adx_database_name': {'key': 'adxDatabaseName', 'type': 'str'}, - 'adx_table_name': {'key': 'adxTableName', 'type': 'str'}, - 'event_hub_endpoint_uri': {'key': 'eventHubEndpointUri', 'type': 'str'}, - 'event_hub_entity_path': {'key': 'eventHubEntityPath', 'type': 'str'}, - 'event_hub_namespace_resource_id': {'key': 'eventHubNamespaceResourceId', 'type': 'str'}, - 'event_hub_consumer_group': {'key': 'eventHubConsumerGroup', 'type': 'str'}, + "connection_type": {"key": "connectionType", "type": "str"}, + "provisioning_state": {"key": "provisioningState", "type": "str"}, + "adx_resource_id": {"key": "adxResourceId", "type": "str"}, + "adx_endpoint_uri": {"key": "adxEndpointUri", "type": "str"}, + "adx_database_name": {"key": "adxDatabaseName", "type": "str"}, + "adx_table_name": {"key": "adxTableName", "type": "str"}, + "event_hub_endpoint_uri": {"key": "eventHubEndpointUri", "type": "str"}, + "event_hub_entity_path": {"key": "eventHubEntityPath", "type": "str"}, + "event_hub_namespace_resource_id": {"key": "eventHubNamespaceResourceId", "type": "str"}, + "event_hub_consumer_group": {"key": "eventHubConsumerGroup", "type": "str"}, } def __init__( @@ -129,33 +125,34 @@ def __init__( event_hub_endpoint_uri: str, event_hub_entity_path: str, event_hub_namespace_resource_id: str, - adx_table_name: Optional[str] = None, - event_hub_consumer_group: Optional[str] = None, + adx_table_name: str = "AdtPropertyEvents", + event_hub_consumer_group: str = "$Default", **kwargs ): """ - :keyword adx_resource_id: Required. The resource ID of the Azure Data Explorer cluster. + :keyword adx_resource_id: The resource ID of the Azure Data Explorer cluster. Required. :paramtype adx_resource_id: str - :keyword adx_endpoint_uri: Required. The URI of the Azure Data Explorer endpoint. + :keyword adx_endpoint_uri: The URI of the Azure Data Explorer endpoint. Required. :paramtype adx_endpoint_uri: str - :keyword adx_database_name: Required. The name of the Azure Data Explorer database. + :keyword adx_database_name: The name of the Azure Data Explorer database. Required. :paramtype adx_database_name: str - :keyword adx_table_name: The name of the Azure Data Explorer table. + :keyword adx_table_name: The name of the Azure Data Explorer table. Defaults to + AdtPropertyEvents. :paramtype adx_table_name: str - :keyword event_hub_endpoint_uri: Required. The URL of the EventHub namespace for identity-based - authentication. It must include the protocol sb://. + :keyword event_hub_endpoint_uri: The URL of the EventHub namespace for identity-based + authentication. It must include the protocol sb://. Required. :paramtype event_hub_endpoint_uri: str - :keyword event_hub_entity_path: Required. The EventHub name in the EventHub namespace for - identity-based authentication. + :keyword event_hub_entity_path: The EventHub name in the EventHub namespace for identity-based + authentication. Required. :paramtype event_hub_entity_path: str - :keyword event_hub_namespace_resource_id: Required. The resource ID of the EventHub namespace. + :keyword event_hub_namespace_resource_id: The resource ID of the EventHub namespace. Required. :paramtype event_hub_namespace_resource_id: str :keyword event_hub_consumer_group: The EventHub consumer group to use when ADX reads from EventHub. Defaults to $Default. :paramtype event_hub_consumer_group: str """ - super(AzureDataExplorerConnectionProperties, self).__init__(**kwargs) - self.connection_type = 'AzureDataExplorer' # type: str + super().__init__(**kwargs) + self.connection_type: str = "AzureDataExplorer" self.adx_resource_id = adx_resource_id self.adx_endpoint_uri = adx_endpoint_uri self.adx_database_name = adx_database_name @@ -166,47 +163,42 @@ def __init__( self.event_hub_consumer_group = event_hub_consumer_group -class CheckNameRequest(msrest.serialization.Model): +class CheckNameRequest(_serialization.Model): """The result returned from a database check name availability request. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. - :ivar name: Required. Resource name. + :ivar name: Resource name. Required. :vartype name: str :ivar type: The type of resource, for instance Microsoft.DigitalTwins/digitalTwinsInstances. - Has constant value: "Microsoft.DigitalTwins/digitalTwinsInstances". + Required. Default value is "Microsoft.DigitalTwins/digitalTwinsInstances". :vartype type: str """ _validation = { - 'name': {'required': True}, - 'type': {'required': True, 'constant': True}, + "name": {"required": True}, + "type": {"required": True, "constant": True}, } _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, } type = "Microsoft.DigitalTwins/digitalTwinsInstances" - def __init__( - self, - *, - name: str, - **kwargs - ): + def __init__(self, *, name: str, **kwargs): """ - :keyword name: Required. Resource name. + :keyword name: Resource name. Required. :paramtype name: str """ - super(CheckNameRequest, self).__init__(**kwargs) + super().__init__(**kwargs) self.name = name -class CheckNameResult(msrest.serialization.Model): +class CheckNameResult(_serialization.Model): """The result returned from a check name availability request. :ivar name_available: Specifies a Boolean value that indicates if the name is available. @@ -214,15 +206,15 @@ class CheckNameResult(msrest.serialization.Model): :ivar message: Message indicating an unavailable name due to a conflict, or a description of the naming rules that are violated. :vartype message: str - :ivar reason: Message providing the reason why the given name is invalid. Possible values - include: "Invalid", "AlreadyExists". + :ivar reason: Message providing the reason why the given name is invalid. Known values are: + "Invalid" and "AlreadyExists". :vartype reason: str or ~azure.mgmt.digitaltwins.v2022_05_31.models.Reason """ _attribute_map = { - 'name_available': {'key': 'nameAvailable', 'type': 'bool'}, - 'message': {'key': 'message', 'type': 'str'}, - 'reason': {'key': 'reason', 'type': 'str'}, + "name_available": {"key": "nameAvailable", "type": "bool"}, + "message": {"key": "message", "type": "str"}, + "reason": {"key": "reason", "type": "str"}, } def __init__( @@ -230,7 +222,7 @@ def __init__( *, name_available: Optional[bool] = None, message: Optional[str] = None, - reason: Optional[Union[str, "Reason"]] = None, + reason: Optional[Union[str, "_models.Reason"]] = None, **kwargs ): """ @@ -239,23 +231,23 @@ def __init__( :keyword message: Message indicating an unavailable name due to a conflict, or a description of the naming rules that are violated. :paramtype message: str - :keyword reason: Message providing the reason why the given name is invalid. Possible values - include: "Invalid", "AlreadyExists". + :keyword reason: Message providing the reason why the given name is invalid. Known values are: + "Invalid" and "AlreadyExists". :paramtype reason: str or ~azure.mgmt.digitaltwins.v2022_05_31.models.Reason """ - super(CheckNameResult, self).__init__(**kwargs) + super().__init__(**kwargs) self.name_available = name_available self.message = message self.reason = reason -class ConnectionProperties(msrest.serialization.Model): +class ConnectionProperties(_serialization.Model): """The properties of a private endpoint connection. Variables are only populated by the server, and will be ignored when sending a request. - :ivar provisioning_state: The provisioning state. Possible values include: "Pending", - "Approved", "Rejected", "Disconnected". + :ivar provisioning_state: The provisioning state. Known values are: "Pending", "Approved", + "Rejected", and "Disconnected". :vartype provisioning_state: str or ~azure.mgmt.digitaltwins.v2022_05_31.models.ConnectionPropertiesProvisioningState :ivar private_endpoint: The private endpoint. @@ -268,22 +260,27 @@ class ConnectionProperties(msrest.serialization.Model): """ _validation = { - 'provisioning_state': {'readonly': True}, + "provisioning_state": {"readonly": True}, } _attribute_map = { - 'provisioning_state': {'key': 'provisioningState', 'type': 'str'}, - 'private_endpoint': {'key': 'privateEndpoint', 'type': 'PrivateEndpoint'}, - 'group_ids': {'key': 'groupIds', 'type': '[str]'}, - 'private_link_service_connection_state': {'key': 'privateLinkServiceConnectionState', 'type': 'ConnectionPropertiesPrivateLinkServiceConnectionState'}, + "provisioning_state": {"key": "provisioningState", "type": "str"}, + "private_endpoint": {"key": "privateEndpoint", "type": "PrivateEndpoint"}, + "group_ids": {"key": "groupIds", "type": "[str]"}, + "private_link_service_connection_state": { + "key": "privateLinkServiceConnectionState", + "type": "ConnectionPropertiesPrivateLinkServiceConnectionState", + }, } def __init__( self, *, - private_endpoint: Optional["PrivateEndpoint"] = None, + private_endpoint: Optional["_models.PrivateEndpoint"] = None, group_ids: Optional[List[str]] = None, - private_link_service_connection_state: Optional["ConnectionPropertiesPrivateLinkServiceConnectionState"] = None, + private_link_service_connection_state: Optional[ + "_models.ConnectionPropertiesPrivateLinkServiceConnectionState" + ] = None, **kwargs ): """ @@ -295,60 +292,60 @@ def __init__( :paramtype private_link_service_connection_state: ~azure.mgmt.digitaltwins.v2022_05_31.models.ConnectionPropertiesPrivateLinkServiceConnectionState """ - super(ConnectionProperties, self).__init__(**kwargs) + super().__init__(**kwargs) self.provisioning_state = None self.private_endpoint = private_endpoint self.group_ids = group_ids self.private_link_service_connection_state = private_link_service_connection_state -class ConnectionState(msrest.serialization.Model): +class ConnectionState(_serialization.Model): """The current state of a private endpoint connection. All required parameters must be populated in order to send to Azure. - :ivar status: Required. The status of a private endpoint connection. Possible values include: - "Pending", "Approved", "Rejected", "Disconnected". + :ivar status: The status of a private endpoint connection. Required. Known values are: + "Pending", "Approved", "Rejected", and "Disconnected". :vartype status: str or ~azure.mgmt.digitaltwins.v2022_05_31.models.PrivateLinkServiceConnectionStatus - :ivar description: Required. The description for the current state of a private endpoint - connection. + :ivar description: The description for the current state of a private endpoint connection. + Required. :vartype description: str :ivar actions_required: Actions required for a private endpoint connection. :vartype actions_required: str """ _validation = { - 'status': {'required': True}, - 'description': {'required': True}, + "status": {"required": True}, + "description": {"required": True}, } _attribute_map = { - 'status': {'key': 'status', 'type': 'str'}, - 'description': {'key': 'description', 'type': 'str'}, - 'actions_required': {'key': 'actionsRequired', 'type': 'str'}, + "status": {"key": "status", "type": "str"}, + "description": {"key": "description", "type": "str"}, + "actions_required": {"key": "actionsRequired", "type": "str"}, } def __init__( self, *, - status: Union[str, "PrivateLinkServiceConnectionStatus"], + status: Union[str, "_models.PrivateLinkServiceConnectionStatus"], description: str, actions_required: Optional[str] = None, **kwargs ): """ - :keyword status: Required. The status of a private endpoint connection. Possible values - include: "Pending", "Approved", "Rejected", "Disconnected". + :keyword status: The status of a private endpoint connection. Required. Known values are: + "Pending", "Approved", "Rejected", and "Disconnected". :paramtype status: str or ~azure.mgmt.digitaltwins.v2022_05_31.models.PrivateLinkServiceConnectionStatus - :keyword description: Required. The description for the current state of a private endpoint - connection. + :keyword description: The description for the current state of a private endpoint connection. + Required. :paramtype description: str :keyword actions_required: Actions required for a private endpoint connection. :paramtype actions_required: str """ - super(ConnectionState, self).__init__(**kwargs) + super().__init__(**kwargs) self.status = status self.description = description self.actions_required = actions_required @@ -359,51 +356,51 @@ class ConnectionPropertiesPrivateLinkServiceConnectionState(ConnectionState): All required parameters must be populated in order to send to Azure. - :ivar status: Required. The status of a private endpoint connection. Possible values include: - "Pending", "Approved", "Rejected", "Disconnected". + :ivar status: The status of a private endpoint connection. Required. Known values are: + "Pending", "Approved", "Rejected", and "Disconnected". :vartype status: str or ~azure.mgmt.digitaltwins.v2022_05_31.models.PrivateLinkServiceConnectionStatus - :ivar description: Required. The description for the current state of a private endpoint - connection. + :ivar description: The description for the current state of a private endpoint connection. + Required. :vartype description: str :ivar actions_required: Actions required for a private endpoint connection. :vartype actions_required: str """ _validation = { - 'status': {'required': True}, - 'description': {'required': True}, + "status": {"required": True}, + "description": {"required": True}, } _attribute_map = { - 'status': {'key': 'status', 'type': 'str'}, - 'description': {'key': 'description', 'type': 'str'}, - 'actions_required': {'key': 'actionsRequired', 'type': 'str'}, + "status": {"key": "status", "type": "str"}, + "description": {"key": "description", "type": "str"}, + "actions_required": {"key": "actionsRequired", "type": "str"}, } def __init__( self, *, - status: Union[str, "PrivateLinkServiceConnectionStatus"], + status: Union[str, "_models.PrivateLinkServiceConnectionStatus"], description: str, actions_required: Optional[str] = None, **kwargs ): """ - :keyword status: Required. The status of a private endpoint connection. Possible values - include: "Pending", "Approved", "Rejected", "Disconnected". + :keyword status: The status of a private endpoint connection. Required. Known values are: + "Pending", "Approved", "Rejected", and "Disconnected". :paramtype status: str or ~azure.mgmt.digitaltwins.v2022_05_31.models.PrivateLinkServiceConnectionStatus - :keyword description: Required. The description for the current state of a private endpoint - connection. + :keyword description: The description for the current state of a private endpoint connection. + Required. :paramtype description: str :keyword actions_required: Actions required for a private endpoint connection. :paramtype actions_required: str """ - super(ConnectionPropertiesPrivateLinkServiceConnectionState, self).__init__(status=status, description=description, actions_required=actions_required, **kwargs) + super().__init__(status=status, description=description, actions_required=actions_required, **kwargs) -class DigitalTwinsResource(msrest.serialization.Model): +class DigitalTwinsResource(_serialization.Model): """The common properties of a DigitalTwinsInstance. Variables are only populated by the server, and will be ignored when sending a request. @@ -416,9 +413,9 @@ class DigitalTwinsResource(msrest.serialization.Model): :vartype name: str :ivar type: The resource type. :vartype type: str - :ivar location: Required. The resource location. + :ivar location: The resource location. Required. :vartype location: str - :ivar tags: A set of tags. The resource tags. + :ivar tags: The resource tags. :vartype tags: dict[str, str] :ivar identity: The managed identity for the DigitalTwinsInstance. :vartype identity: ~azure.mgmt.digitaltwins.v2022_05_31.models.DigitalTwinsIdentity @@ -428,21 +425,21 @@ class DigitalTwinsResource(msrest.serialization.Model): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True, 'pattern': r'^(?!-)[A-Za-z0-9-]{3,63}(?= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False + def build_list_request( - subscription_id: str, - resource_group_name: str, - resource_name: str, - **kwargs: Any + resource_group_name: str, resource_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = kwargs.pop('api_version', "2022-05-31") # type: str + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints", + ) # 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', max_length=90, min_length=1), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=63, min_length=3, pattern=r'^(?!-)[A-Za-z0-9-]{3,63}(? HttpRequest: - api_version = kwargs.pop('api_version', "2022-05-31") # type: str + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}", + ) # 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', max_length=90, min_length=1), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=63, min_length=3, pattern=r'^(?!-)[A-Za-z0-9-]{3,63}(? HttpRequest: - api_version = kwargs.pop('api_version', "2022-05-31") # type: str - content_type = kwargs.pop('content_type', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}", + ) # 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', max_length=90, min_length=1), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=63, min_length=3, pattern=r'^(?!-)[A-Za-z0-9-]{3,63}(? HttpRequest: - api_version = kwargs.pop('api_version', "2022-05-31") # type: str + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}", + ) # 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', max_length=90, min_length=1), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=63, min_length=3, pattern=r'^(?!-)[A-Za-z0-9-]{3,63}(? Iterable["_models.DigitalTwinsEndpointResourceListResult"]: + self, resource_group_name: str, resource_name: str, **kwargs: Any + ) -> Iterable["_models.DigitalTwinsEndpointResource"]: """Get DigitalTwinsInstance Endpoints. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either DigitalTwinsEndpointResourceListResult or the - result of cls(response) + :return: An iterator like instance of either DigitalTwinsEndpointResource or the result of + cls(response) :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.digitaltwins.v2022_05_31.models.DigitalTwinsEndpointResourceListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.paging.ItemPaged[~azure.mgmt.digitaltwins.v2022_05_31.models.DigitalTwinsEndpointResource] + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2022-05-31") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + cls: ClsType[_models.DigitalTwinsEndpointResourceListResult] = kwargs.pop("cls", None) - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsEndpointResourceListResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list.metadata['url'], + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: - - request = build_list_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - resource_name=resource_name, - api_version=api_version, - template_url=next_link, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) @@ -267,16 +318,14 @@ def extract_data(pipeline_response): deserialized = self._deserialize("DigitalTwinsEndpointResourceListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -287,59 +336,61 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints"} # type: ignore + list.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints" + } @distributed_trace def get( - self, - resource_group_name: str, - resource_name: str, - endpoint_name: str, - **kwargs: Any - ) -> "_models.DigitalTwinsEndpointResource": + self, resource_group_name: str, resource_name: str, endpoint_name: str, **kwargs: Any + ) -> _models.DigitalTwinsEndpointResource: """Get DigitalTwinsInstances Endpoint. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param endpoint_name: Name of Endpoint Resource. + :param endpoint_name: Name of Endpoint Resource. Required. :type endpoint_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: DigitalTwinsEndpointResource, or the result of cls(response) + :return: DigitalTwinsEndpointResource or the result of cls(response) :rtype: ~azure.mgmt.digitaltwins.v2022_05_31.models.DigitalTwinsEndpointResource - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsEndpointResource"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', "2022-05-31") # type: str + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + cls: ClsType[_models.DigitalTwinsEndpointResource] = kwargs.pop("cls", None) - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, endpoint_name=endpoint_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -347,72 +398,172 @@ def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('DigitalTwinsEndpointResource', pipeline_response) + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}"} # type: ignore - + get.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}" + } def _create_or_update_initial( self, resource_group_name: str, resource_name: str, endpoint_name: str, - endpoint_description: "_models.DigitalTwinsEndpointResource", + endpoint_description: Union[_models.DigitalTwinsEndpointResource, IO], **kwargs: Any - ) -> "_models.DigitalTwinsEndpointResource": - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsEndpointResource"] + ) -> _models.DigitalTwinsEndpointResource: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2022-05-31") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(endpoint_description, 'DigitalTwinsEndpointResource') + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DigitalTwinsEndpointResource] = kwargs.pop("cls", None) - request = build_create_or_update_request_initial( - subscription_id=self._config.subscription_id, + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(endpoint_description, (IO, bytes)): + _content = endpoint_description + else: + _json = self._serialize.body(endpoint_description, "DigitalTwinsEndpointResource") + + request = build_create_or_update_request( resource_group_name=resource_group_name, resource_name=resource_name, 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_initial.metadata['url'], + content=_content, + template_url=self._create_or_update_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('DigitalTwinsEndpointResource', pipeline_response) + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('DigitalTwinsEndpointResource', pipeline_response) + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized + return deserialized # type: ignore + + _create_or_update_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}" + } + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + endpoint_name: str, + endpoint_description: _models.DigitalTwinsEndpointResource, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.DigitalTwinsEndpointResource]: + """Create or update DigitalTwinsInstance endpoint. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param endpoint_name: Name of Endpoint Resource. Required. + :type endpoint_name: str + :param endpoint_description: The DigitalTwinsInstance endpoint metadata and security metadata. + Required. + :type endpoint_description: + ~azure.mgmt.digitaltwins.v2022_05_31.models.DigitalTwinsEndpointResource + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either DigitalTwinsEndpointResource or the + result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2022_05_31.models.DigitalTwinsEndpointResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ - _create_or_update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}"} # type: ignore + @overload + def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + endpoint_name: str, + endpoint_description: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.DigitalTwinsEndpointResource]: + """Create or update DigitalTwinsInstance endpoint. + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param endpoint_name: Name of Endpoint Resource. Required. + :type endpoint_name: str + :param endpoint_description: The DigitalTwinsInstance endpoint metadata and security metadata. + Required. + :type endpoint_description: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either DigitalTwinsEndpointResource or the + result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2022_05_31.models.DigitalTwinsEndpointResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace def begin_create_or_update( @@ -420,21 +571,25 @@ def begin_create_or_update( resource_group_name: str, resource_name: str, endpoint_name: str, - endpoint_description: "_models.DigitalTwinsEndpointResource", + endpoint_description: Union[_models.DigitalTwinsEndpointResource, IO], **kwargs: Any - ) -> LROPoller["_models.DigitalTwinsEndpointResource"]: + ) -> LROPoller[_models.DigitalTwinsEndpointResource]: """Create or update DigitalTwinsInstance endpoint. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param endpoint_name: Name of Endpoint Resource. + :param endpoint_name: Name of Endpoint Resource. Required. :type endpoint_name: str :param endpoint_description: The DigitalTwinsInstance endpoint metadata and security metadata. + Is either a model type or a IO type. Required. :type endpoint_description: - ~azure.mgmt.digitaltwins.v2022_05_31.models.DigitalTwinsEndpointResource + ~azure.mgmt.digitaltwins.v2022_05_31.models.DigitalTwinsEndpointResource or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this @@ -447,17 +602,17 @@ def begin_create_or_update( result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2022_05_31.models.DigitalTwinsEndpointResource] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2022-05-31") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsEndpointResource"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DigitalTwinsEndpointResource] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = self._create_or_update_initial( resource_group_name=resource_group_name, @@ -466,102 +621,107 @@ def begin_create_or_update( endpoint_description=endpoint_description, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('DigitalTwinsEndpointResource', pipeline_response) + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - begin_create_or_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}"} # type: ignore + begin_create_or_update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}" + } def _delete_initial( - self, - resource_group_name: str, - resource_name: str, - endpoint_name: str, - **kwargs: Any - ) -> Optional["_models.DigitalTwinsEndpointResource"]: - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.DigitalTwinsEndpointResource"]] + self, resource_group_name: str, resource_name: str, endpoint_name: str, **kwargs: Any + ) -> Optional[_models.DigitalTwinsEndpointResource]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2022-05-31") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - request = build_delete_request_initial( - subscription_id=self._config.subscription_id, + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + cls: ClsType[Optional[_models.DigitalTwinsEndpointResource]] = kwargs.pop("cls", None) + + request = build_delete_request( resource_group_name=resource_group_name, resource_name=resource_name, endpoint_name=endpoint_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._delete_initial.metadata['url'], + template_url=self._delete_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('DigitalTwinsEndpointResource', pipeline_response) + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) if response.status_code == 202: - deserialized = self._deserialize('DigitalTwinsEndpointResource', pipeline_response) + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _delete_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}"} # type: ignore - + _delete_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}" + } @distributed_trace def begin_delete( - self, - resource_group_name: str, - resource_name: str, - endpoint_name: str, - **kwargs: Any - ) -> LROPoller["_models.DigitalTwinsEndpointResource"]: + self, resource_group_name: str, resource_name: str, endpoint_name: str, **kwargs: Any + ) -> LROPoller[_models.DigitalTwinsEndpointResource]: """Delete a DigitalTwinsInstance endpoint. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param endpoint_name: Name of Endpoint Resource. + :param endpoint_name: Name of Endpoint Resource. Required. :type endpoint_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. @@ -575,45 +735,50 @@ def begin_delete( result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2022_05_31.models.DigitalTwinsEndpointResource] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2022-05-31") # type: str - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsEndpointResource"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + cls: ClsType[_models.DigitalTwinsEndpointResource] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = self._delete_initial( resource_group_name=resource_group_name, resource_name=resource_name, endpoint_name=endpoint_name, api_version=api_version, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('DigitalTwinsEndpointResource', pipeline_response) + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - begin_delete.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}"} # type: ignore + begin_delete.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}" + } diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/operations/_digital_twins_operations.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/operations/_digital_twins_operations.py index 7523b73d6bc3e..13c7f4744898c 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/operations/_digital_twins_operations.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/operations/_digital_twins_operations.py @@ -6,361 +6,357 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Iterable, Optional, TypeVar, Union - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import sys +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models +from ..._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') -JSONType = Any + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_get_request( - subscription_id: str, - resource_group_name: str, - resource_name: str, - **kwargs: Any -) -> HttpRequest: - api_version = kwargs.pop('api_version', "2022-05-31") # type: str - accept = "application/json" +def build_get_request(resource_group_name: str, resource_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + accept = _headers.pop("Accept", "application/json") + # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}", + ) # 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', max_length=90, min_length=1), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=63, min_length=3, pattern=r'^(?!-)[A-Za-z0-9-]{3,63}(? HttpRequest: - api_version = kwargs.pop('api_version', "2022-05-31") # type: str - content_type = kwargs.pop('content_type', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}", + ) # 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', max_length=90, min_length=1), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=63, min_length=3, pattern=r'^(?!-)[A-Za-z0-9-]{3,63}(? HttpRequest: - api_version = kwargs.pop('api_version', "2022-05-31") # type: str - content_type = kwargs.pop('content_type', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}", + ) # 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', max_length=90, min_length=1), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=63, min_length=3, pattern=r'^(?!-)[A-Za-z0-9-]{3,63}(? HttpRequest: - api_version = kwargs.pop('api_version', "2022-05-31") # type: str + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}", + ) # 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', max_length=90, min_length=1), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=63, min_length=3, pattern=r'^(?!-)[A-Za-z0-9-]{3,63}(? HttpRequest: - api_version = kwargs.pop('api_version', "2022-05-31") # type: str +def build_list_request(subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.DigitalTwins/digitalTwinsInstances") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.DigitalTwins/digitalTwinsInstances" + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters - _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - _query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - _header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="GET", - url=_url, - params=_query_parameters, - headers=_header_parameters, - **kwargs - ) - - -def build_list_by_resource_group_request( - subscription_id: str, - resource_group_name: str, - **kwargs: Any -) -> HttpRequest: - api_version = kwargs.pop('api_version', "2022-05-31") # type: str + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_by_resource_group_request(resource_group_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances", + ) # 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', max_length=90, min_length=1), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # 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_check_name_availability_request( - subscription_id: str, - location: str, - *, - json: JSONType = None, - content: Any = None, - **kwargs: Any -) -> HttpRequest: - api_version = kwargs.pop('api_version', "2022-05-31") # type: str - content_type = kwargs.pop('content_type', None) # type: Optional[str] + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_check_name_availability_request(location: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.DigitalTwins/locations/{location}/checkNameAvailability") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.DigitalTwins/locations/{location}/checkNameAvailability", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), - "location": _SERIALIZER.url("location", location, 'str', min_length=3), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "location": _SERIALIZER.url("location", location, "str", min_length=3), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore # Construct parameters - _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - _query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] if content_type is not None: - _header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') - _header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="POST", - url=_url, - params=_query_parameters, - headers=_header_parameters, - json=json, - content=content, - **kwargs - ) - -class DigitalTwinsOperations(object): - """DigitalTwinsOperations 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.digitaltwins.v2022_05_31.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class DigitalTwinsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.digitaltwins.v2022_05_31.AzureDigitalTwinsManagementClient`'s + :attr:`digital_twins` 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, - resource_group_name: str, - resource_name: str, - **kwargs: Any - ) -> "_models.DigitalTwinsDescription": + def get(self, resource_group_name: str, resource_name: str, **kwargs: Any) -> _models.DigitalTwinsDescription: """Get DigitalTwinsInstances resource. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: DigitalTwinsDescription, or the result of cls(response) + :return: DigitalTwinsDescription or the result of cls(response) :rtype: ~azure.mgmt.digitaltwins.v2022_05_31.models.DigitalTwinsDescription - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescription"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', "2022-05-31") # type: str + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + cls: ClsType[_models.DigitalTwinsDescription] = kwargs.pop("cls", None) - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -368,90 +364,190 @@ def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}"} # type: ignore - + get.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } def _create_or_update_initial( self, resource_group_name: str, resource_name: str, - digital_twins_create: "_models.DigitalTwinsDescription", + digital_twins_create: Union[_models.DigitalTwinsDescription, IO], **kwargs: Any - ) -> "_models.DigitalTwinsDescription": - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescription"] + ) -> _models.DigitalTwinsDescription: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2022-05-31") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(digital_twins_create, 'DigitalTwinsDescription') + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DigitalTwinsDescription] = kwargs.pop("cls", None) - request = build_create_or_update_request_initial( - subscription_id=self._config.subscription_id, + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(digital_twins_create, (IO, bytes)): + _content = digital_twins_create + else: + _json = self._serialize.body(digital_twins_create, "DigitalTwinsDescription") + + request = build_create_or_update_request( resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._create_or_update_initial.metadata['url'], + content=_content, + template_url=self._create_or_update_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized + return deserialized # type: ignore - _create_or_update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}"} # type: ignore + _create_or_update_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } + @overload + def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + digital_twins_create: _models.DigitalTwinsDescription, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.DigitalTwinsDescription]: + """Create or update the metadata of a DigitalTwinsInstance. The usual pattern to modify a property + is to retrieve the DigitalTwinsInstance and security metadata, and then combine them with the + modified values in a new body to update the DigitalTwinsInstance. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param digital_twins_create: The DigitalTwinsInstance and security metadata. Required. + :type digital_twins_create: ~azure.mgmt.digitaltwins.v2022_05_31.models.DigitalTwinsDescription + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either DigitalTwinsDescription or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2022_05_31.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + digital_twins_create: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.DigitalTwinsDescription]: + """Create or update the metadata of a DigitalTwinsInstance. The usual pattern to modify a property + is to retrieve the DigitalTwinsInstance and security metadata, and then combine them with the + modified values in a new body to update the DigitalTwinsInstance. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param digital_twins_create: The DigitalTwinsInstance and security metadata. Required. + :type digital_twins_create: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either DigitalTwinsDescription or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2022_05_31.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace def begin_create_or_update( self, resource_group_name: str, resource_name: str, - digital_twins_create: "_models.DigitalTwinsDescription", + digital_twins_create: Union[_models.DigitalTwinsDescription, IO], **kwargs: Any - ) -> LROPoller["_models.DigitalTwinsDescription"]: + ) -> LROPoller[_models.DigitalTwinsDescription]: """Create or update the metadata of a DigitalTwinsInstance. The usual pattern to modify a property is to retrieve the DigitalTwinsInstance and security metadata, and then combine them with the modified values in a new body to update the DigitalTwinsInstance. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param digital_twins_create: The DigitalTwinsInstance and security metadata. + :param digital_twins_create: The DigitalTwinsInstance and security metadata. Is either a model + type or a IO type. Required. :type digital_twins_create: ~azure.mgmt.digitaltwins.v2022_05_31.models.DigitalTwinsDescription + or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this @@ -464,17 +560,17 @@ def begin_create_or_update( cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2022_05_31.models.DigitalTwinsDescription] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2022-05-31") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescription"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DigitalTwinsDescription] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = self._create_or_update_initial( resource_group_name=resource_group_name, @@ -482,106 +578,133 @@ def begin_create_or_update( digital_twins_create=digital_twins_create, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - begin_create_or_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}"} # type: ignore + begin_create_or_update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } def _update_initial( self, resource_group_name: str, resource_name: str, - digital_twins_patch_description: "_models.DigitalTwinsPatchDescription", + digital_twins_patch_description: Union[_models.DigitalTwinsPatchDescription, IO], **kwargs: Any - ) -> "_models.DigitalTwinsDescription": - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescription"] + ) -> _models.DigitalTwinsDescription: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2022-05-31") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(digital_twins_patch_description, 'DigitalTwinsPatchDescription') + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DigitalTwinsDescription] = kwargs.pop("cls", None) - request = build_update_request_initial( - subscription_id=self._config.subscription_id, + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(digital_twins_patch_description, (IO, bytes)): + _content = digital_twins_patch_description + else: + _json = self._serialize.body(digital_twins_patch_description, "DigitalTwinsPatchDescription") + + request = build_update_request( resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._update_initial.metadata['url'], + content=_content, + template_url=self._update_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if response.status_code == 202: - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - _update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}"} # type: ignore + return deserialized # type: ignore + _update_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } - @distributed_trace + @overload def begin_update( self, resource_group_name: str, resource_name: str, - digital_twins_patch_description: "_models.DigitalTwinsPatchDescription", + digital_twins_patch_description: _models.DigitalTwinsPatchDescription, + *, + content_type: str = "application/json", **kwargs: Any - ) -> LROPoller["_models.DigitalTwinsDescription"]: + ) -> LROPoller[_models.DigitalTwinsDescription]: """Update metadata of DigitalTwinsInstance. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str :param digital_twins_patch_description: The DigitalTwinsInstance and security metadata. + Required. :type digital_twins_patch_description: ~azure.mgmt.digitaltwins.v2022_05_31.models.DigitalTwinsPatchDescription + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this @@ -594,17 +717,92 @@ def begin_update( cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2022_05_31.models.DigitalTwinsDescription] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2022-05-31") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescription"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + + @overload + def begin_update( + self, + resource_group_name: str, + resource_name: str, + digital_twins_patch_description: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.DigitalTwinsDescription]: + """Update metadata of DigitalTwinsInstance. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param digital_twins_patch_description: The DigitalTwinsInstance and security metadata. + Required. + :type digital_twins_patch_description: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either DigitalTwinsDescription or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2022_05_31.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_update( + self, + resource_group_name: str, + resource_name: str, + digital_twins_patch_description: Union[_models.DigitalTwinsPatchDescription, IO], + **kwargs: Any + ) -> LROPoller[_models.DigitalTwinsDescription]: + """Update metadata of DigitalTwinsInstance. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param digital_twins_patch_description: The DigitalTwinsInstance and security metadata. Is + either a model type or a IO type. Required. + :type digital_twins_patch_description: + ~azure.mgmt.digitaltwins.v2022_05_31.models.DigitalTwinsPatchDescription or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either DigitalTwinsDescription or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2022_05_31.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DigitalTwinsDescription] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = self._update_initial( resource_group_name=resource_group_name, @@ -612,97 +810,104 @@ def begin_update( digital_twins_patch_description=digital_twins_patch_description, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - begin_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}"} # type: ignore + begin_update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } def _delete_initial( - self, - resource_group_name: str, - resource_name: str, - **kwargs: Any - ) -> Optional["_models.DigitalTwinsDescription"]: - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.DigitalTwinsDescription"]] + self, resource_group_name: str, resource_name: str, **kwargs: Any + ) -> Optional[_models.DigitalTwinsDescription]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2022-05-31") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - request = build_delete_request_initial( - subscription_id=self._config.subscription_id, + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + cls: ClsType[Optional[_models.DigitalTwinsDescription]] = kwargs.pop("cls", None) + + request = build_delete_request( resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._delete_initial.metadata['url'], + template_url=self._delete_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if response.status_code == 202: - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _delete_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}"} # type: ignore - + _delete_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } @distributed_trace def begin_delete( - self, - resource_group_name: str, - resource_name: str, - **kwargs: Any - ) -> LROPoller["_models.DigitalTwinsDescription"]: + self, resource_group_name: str, resource_name: str, **kwargs: Any + ) -> LROPoller[_models.DigitalTwinsDescription]: """Delete a DigitalTwinsInstance. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. @@ -716,86 +921,103 @@ def begin_delete( cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2022_05_31.models.DigitalTwinsDescription] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2022-05-31") # type: str - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescription"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + cls: ClsType[_models.DigitalTwinsDescription] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = self._delete_initial( resource_group_name=resource_group_name, resource_name=resource_name, api_version=api_version, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('DigitalTwinsDescription', pipeline_response) + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - begin_delete.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}"} # type: ignore + begin_delete.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } @distributed_trace - def list( - self, - **kwargs: Any - ) -> Iterable["_models.DigitalTwinsDescriptionListResult"]: + def list(self, **kwargs: Any) -> Iterable["_models.DigitalTwinsDescription"]: """Get all the DigitalTwinsInstances in a subscription. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either DigitalTwinsDescriptionListResult or the result of + :return: An iterator like instance of either DigitalTwinsDescription or the result of cls(response) :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.digitaltwins.v2022_05_31.models.DigitalTwinsDescriptionListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.paging.ItemPaged[~azure.mgmt.digitaltwins.v2022_05_31.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2022-05-31") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + cls: ClsType[_models.DigitalTwinsDescriptionListResult] = kwargs.pop("cls", None) - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescriptionListResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list.metadata['url'], + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: - - request = build_list_request( - subscription_id=self._config.subscription_id, - api_version=api_version, - template_url=next_link, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) @@ -806,16 +1028,14 @@ def extract_data(pipeline_response): deserialized = self._deserialize("DigitalTwinsDescriptionListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -826,56 +1046,66 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.DigitalTwins/digitalTwinsInstances"} # type: ignore + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.DigitalTwins/digitalTwinsInstances"} @distributed_trace def list_by_resource_group( - self, - resource_group_name: str, - **kwargs: Any - ) -> Iterable["_models.DigitalTwinsDescriptionListResult"]: + self, resource_group_name: str, **kwargs: Any + ) -> Iterable["_models.DigitalTwinsDescription"]: """Get all the DigitalTwinsInstances in a resource group. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. 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 DigitalTwinsDescriptionListResult or the result of + :return: An iterator like instance of either DigitalTwinsDescription or the result of cls(response) :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.digitaltwins.v2022_05_31.models.DigitalTwinsDescriptionListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.paging.ItemPaged[~azure.mgmt.digitaltwins.v2022_05_31.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2022-05-31") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + cls: ClsType[_models.DigitalTwinsDescriptionListResult] = kwargs.pop("cls", None) - cls = kwargs.pop('cls', None) # type: ClsType["_models.DigitalTwinsDescriptionListResult"] 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( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata['url'], + template_url=self.list_by_resource_group.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: - - request = build_list_by_resource_group_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - api_version=api_version, - template_url=next_link, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) @@ -886,16 +1116,14 @@ def extract_data(pipeline_response): deserialized = self._deserialize("DigitalTwinsDescriptionListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -906,59 +1134,127 @@ 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.DigitalTwins/digitalTwinsInstances"} # type: ignore + list_by_resource_group.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances" + } - @distributed_trace + @overload def check_name_availability( self, location: str, - digital_twins_instance_check_name: "_models.CheckNameRequest", + digital_twins_instance_check_name: _models.CheckNameRequest, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.CheckNameResult": + ) -> _models.CheckNameResult: """Check if a DigitalTwinsInstance name is available. - :param location: Location of DigitalTwinsInstance. + :param location: Location of DigitalTwinsInstance. Required. :type location: str :param digital_twins_instance_check_name: Set the name parameter in the DigitalTwinsInstanceCheckName structure to the name of the DigitalTwinsInstance to check. + Required. :type digital_twins_instance_check_name: ~azure.mgmt.digitaltwins.v2022_05_31.models.CheckNameRequest + :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: CheckNameResult or the result of cls(response) + :rtype: ~azure.mgmt.digitaltwins.v2022_05_31.models.CheckNameResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def check_name_availability( + self, + location: str, + digital_twins_instance_check_name: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.CheckNameResult: + """Check if a DigitalTwinsInstance name is available. + + :param location: Location of DigitalTwinsInstance. Required. + :type location: str + :param digital_twins_instance_check_name: Set the name parameter in the + DigitalTwinsInstanceCheckName structure to the name of the DigitalTwinsInstance to check. + Required. + :type digital_twins_instance_check_name: 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: CheckNameResult, or the result of cls(response) + :return: CheckNameResult or the result of cls(response) :rtype: ~azure.mgmt.digitaltwins.v2022_05_31.models.CheckNameResult - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def check_name_availability( + self, location: str, digital_twins_instance_check_name: Union[_models.CheckNameRequest, IO], **kwargs: Any + ) -> _models.CheckNameResult: + """Check if a DigitalTwinsInstance name is available. + + :param location: Location of DigitalTwinsInstance. Required. + :type location: str + :param digital_twins_instance_check_name: Set the name parameter in the + DigitalTwinsInstanceCheckName structure to the name of the DigitalTwinsInstance to check. Is + either a model type or a IO type. Required. + :type digital_twins_instance_check_name: + ~azure.mgmt.digitaltwins.v2022_05_31.models.CheckNameRequest 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: CheckNameResult or the result of cls(response) + :rtype: ~azure.mgmt.digitaltwins.v2022_05_31.models.CheckNameResult + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.CheckNameResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', "2022-05-31") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.CheckNameResult] = kwargs.pop("cls", None) - _json = self._serialize.body(digital_twins_instance_check_name, 'CheckNameRequest') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(digital_twins_instance_check_name, (IO, bytes)): + _content = digital_twins_instance_check_name + else: + _json = self._serialize.body(digital_twins_instance_check_name, "CheckNameRequest") request = build_check_name_availability_request( - subscription_id=self._config.subscription_id, location=location, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self.check_name_availability.metadata['url'], + content=_content, + template_url=self.check_name_availability.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -966,12 +1262,13 @@ def check_name_availability( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('CheckNameResult', pipeline_response) + deserialized = self._deserialize("CheckNameResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - check_name_availability.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.DigitalTwins/locations/{location}/checkNameAvailability"} # type: ignore - + check_name_availability.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.DigitalTwins/locations/{location}/checkNameAvailability" + } diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/operations/_operations.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/operations/_operations.py index fe41fdc588695..b37c7c526e0e9 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/operations/_operations.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/operations/_operations.py @@ -6,108 +6,126 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, Callable, Dict, Iterable, Optional, TypeVar - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from ..._serialization import Serializer from .._vendor import _convert_request -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_list_request( - **kwargs: Any -) -> HttpRequest: - api_version = kwargs.pop('api_version', "2022-05-31") # type: str - accept = "application/json" +def build_list_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + accept = _headers.pop("Accept", "application/json") + # Construct URL _url = kwargs.pop("template_url", "/providers/Microsoft.DigitalTwins/operations") # Construct parameters - _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - _query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - _header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="GET", - url=_url, - params=_query_parameters, - headers=_header_parameters, - **kwargs - ) - -class Operations(object): - """Operations operations. - - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. - - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.digitaltwins.v2022_05_31.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class Operations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.digitaltwins.v2022_05_31.AzureDigitalTwinsManagementClient`'s + :attr:`operations` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace - def list( - self, - **kwargs: Any - ) -> Iterable["_models.OperationListResult"]: + def list(self, **kwargs: Any) -> Iterable["_models.Operation"]: """Lists all of the available DigitalTwins service REST API operations. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either OperationListResult or the result of cls(response) - :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.digitaltwins.v2022_05_31.models.OperationListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Operation or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.digitaltwins.v2022_05_31.models.Operation] + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2022-05-31") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) - cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationListResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( api_version=api_version, - template_url=self.list.metadata['url'], + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: - - request = build_list_request( - api_version=api_version, - template_url=next_link, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) @@ -118,16 +136,14 @@ def extract_data(pipeline_response): deserialized = self._deserialize("OperationListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -138,8 +154,6 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/providers/Microsoft.DigitalTwins/operations"} # type: ignore + list.metadata = {"url": "/providers/Microsoft.DigitalTwins/operations"} diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/operations/_patch.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/operations/_patch.py new file mode 100644 index 0000000000000..f7dd32510333d --- /dev/null +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/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/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/operations/_private_endpoint_connections_operations.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/operations/_private_endpoint_connections_operations.py index c153b3b337738..0bdacad5f375f 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/operations/_private_endpoint_connections_operations.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/operations/_private_endpoint_connections_operations.py @@ -6,250 +6,290 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Optional, TypeVar, Union - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import sys +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, cast, 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.polling import LROPoller, NoPolling, PollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models +from ..._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') -JSONType = Any + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False + def build_list_request( - subscription_id: str, - resource_group_name: str, - resource_name: str, - **kwargs: Any + resource_group_name: str, resource_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = kwargs.pop('api_version', "2022-05-31") # type: str + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=63, min_length=3, pattern=r'^(?!-)[A-Za-z0-9-]{3,63}(? HttpRequest: - api_version = kwargs.pop('api_version', "2022-05-31") # type: str + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=63, min_length=3, pattern=r'^(?!-)[A-Za-z0-9-]{3,63}(? HttpRequest: - api_version = kwargs.pop('api_version', "2022-05-31") # type: str + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=63, min_length=3, pattern=r'^(?!-)[A-Za-z0-9-]{3,63}(? HttpRequest: - api_version = kwargs.pop('api_version', "2022-05-31") # type: str - content_type = kwargs.pop('content_type', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=63, min_length=3, pattern=r'^(?!-)[A-Za-z0-9-]{3,63}(? "_models.PrivateEndpointConnectionsResponse": + self, resource_group_name: str, resource_name: str, **kwargs: Any + ) -> _models.PrivateEndpointConnectionsResponse: """List private endpoint connection properties. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: PrivateEndpointConnectionsResponse, or the result of cls(response) + :return: PrivateEndpointConnectionsResponse or the result of cls(response) :rtype: ~azure.mgmt.digitaltwins.v2022_05_31.models.PrivateEndpointConnectionsResponse - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnectionsResponse"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', "2022-05-31") # type: str + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + cls: ClsType[_models.PrivateEndpointConnectionsResponse] = kwargs.pop("cls", None) - request = build_list_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list.metadata['url'], + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -257,63 +297,66 @@ def list( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('PrivateEndpointConnectionsResponse', pipeline_response) + deserialized = self._deserialize("PrivateEndpointConnectionsResponse", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - list.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections"} # type: ignore - + list.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections" + } @distributed_trace def get( - self, - resource_group_name: str, - resource_name: str, - private_endpoint_connection_name: str, - **kwargs: Any - ) -> "_models.PrivateEndpointConnection": + self, resource_group_name: str, resource_name: str, private_endpoint_connection_name: str, **kwargs: Any + ) -> _models.PrivateEndpointConnection: """Get private endpoint connection properties for the given private endpoint. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param private_endpoint_connection_name: The name of the private endpoint connection. + :param private_endpoint_connection_name: The name of the private endpoint connection. Required. :type private_endpoint_connection_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: PrivateEndpointConnection, or the result of cls(response) + :return: PrivateEndpointConnection or the result of cls(response) :rtype: ~azure.mgmt.digitaltwins.v2022_05_31.models.PrivateEndpointConnection - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnection"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', "2022-05-31") # type: str + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + cls: ClsType[_models.PrivateEndpointConnection] = kwargs.pop("cls", None) - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, private_endpoint_connection_name=private_endpoint_connection_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -321,76 +364,77 @@ def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore - + get.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}" + } def _delete_initial( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - resource_name: str, - private_endpoint_connection_name: str, - **kwargs: Any + self, resource_group_name: str, resource_name: str, private_endpoint_connection_name: str, **kwargs: Any ) -> None: - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2022-05-31") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - request = build_delete_request_initial( - subscription_id=self._config.subscription_id, + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + cls: ClsType[None] = kwargs.pop("cls", None) + + request = build_delete_request( resource_group_name=resource_group_name, resource_name=resource_name, private_endpoint_connection_name=private_endpoint_connection_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._delete_initial.metadata['url'], + template_url=self._delete_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - _delete_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore - + _delete_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}" + } @distributed_trace - def begin_delete( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - resource_name: str, - private_endpoint_connection_name: str, - **kwargs: Any + def begin_delete( + self, resource_group_name: str, resource_name: str, private_endpoint_connection_name: str, **kwargs: Any ) -> LROPoller[None]: """Delete private endpoint connection with the specified name. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param private_endpoint_connection_name: The name of the private endpoint connection. + :param private_endpoint_connection_name: The name of the private endpoint connection. Required. :type private_endpoint_connection_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. @@ -402,124 +446,152 @@ def begin_delete( # pylint: disable=inconsistent-return-statements Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2022-05-31") # type: str - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType[None] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: - raw_result = self._delete_initial( + raw_result = self._delete_initial( # type: ignore resource_group_name=resource_group_name, resource_name=resource_name, private_endpoint_connection_name=private_endpoint_connection_name, api_version=api_version, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - - if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - begin_delete.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore + begin_delete.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}" + } def _create_or_update_initial( self, resource_group_name: str, resource_name: str, private_endpoint_connection_name: str, - private_endpoint_connection: "_models.PrivateEndpointConnection", + private_endpoint_connection: Union[_models.PrivateEndpointConnection, IO], **kwargs: Any - ) -> "_models.PrivateEndpointConnection": - cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnection"] + ) -> _models.PrivateEndpointConnection: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2022-05-31") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(private_endpoint_connection, 'PrivateEndpointConnection') + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PrivateEndpointConnection] = kwargs.pop("cls", None) - request = build_create_or_update_request_initial( - subscription_id=self._config.subscription_id, + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(private_endpoint_connection, (IO, bytes)): + _content = private_endpoint_connection + else: + _json = self._serialize.body(private_endpoint_connection, "PrivateEndpointConnection") + + request = build_create_or_update_request( resource_group_name=resource_group_name, resource_name=resource_name, private_endpoint_connection_name=private_endpoint_connection_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._create_or_update_initial.metadata['url'], + content=_content, + template_url=self._create_or_update_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) if response.status_code == 202: - deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - _create_or_update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore + return deserialized # type: ignore + _create_or_update_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}" + } - @distributed_trace + @overload def begin_create_or_update( self, resource_group_name: str, resource_name: str, private_endpoint_connection_name: str, - private_endpoint_connection: "_models.PrivateEndpointConnection", + private_endpoint_connection: _models.PrivateEndpointConnection, + *, + content_type: str = "application/json", **kwargs: Any - ) -> LROPoller["_models.PrivateEndpointConnection"]: + ) -> LROPoller[_models.PrivateEndpointConnection]: """Update the status of a private endpoint connection with the given name. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param private_endpoint_connection_name: The name of the private endpoint connection. + :param private_endpoint_connection_name: The name of the private endpoint connection. Required. :type private_endpoint_connection_name: str :param private_endpoint_connection: The private endpoint connection with updated properties. + Required. :type private_endpoint_connection: ~azure.mgmt.digitaltwins.v2022_05_31.models.PrivateEndpointConnection + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this @@ -532,17 +604,98 @@ def begin_create_or_update( of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2022_05_31.models.PrivateEndpointConnection] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2022-05-31") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateEndpointConnection"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + private_endpoint_connection_name: str, + private_endpoint_connection: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.PrivateEndpointConnection]: + """Update the status of a private endpoint connection with the given name. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param private_endpoint_connection_name: The name of the private endpoint connection. Required. + :type private_endpoint_connection_name: str + :param private_endpoint_connection: The private endpoint connection with updated properties. + Required. + :type private_endpoint_connection: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either PrivateEndpointConnection or the result + of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2022_05_31.models.PrivateEndpointConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + private_endpoint_connection_name: str, + private_endpoint_connection: Union[_models.PrivateEndpointConnection, IO], + **kwargs: Any + ) -> LROPoller[_models.PrivateEndpointConnection]: + """Update the status of a private endpoint connection with the given name. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param private_endpoint_connection_name: The name of the private endpoint connection. Required. + :type private_endpoint_connection_name: str + :param private_endpoint_connection: The private endpoint connection with updated properties. Is + either a model type or a IO type. Required. + :type private_endpoint_connection: + ~azure.mgmt.digitaltwins.v2022_05_31.models.PrivateEndpointConnection or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either PrivateEndpointConnection or the result + of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2022_05_31.models.PrivateEndpointConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PrivateEndpointConnection] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = self._create_or_update_initial( resource_group_name=resource_group_name, @@ -551,29 +704,34 @@ def begin_create_or_update( private_endpoint_connection=private_endpoint_connection, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - begin_create_or_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore + begin_create_or_update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}" + } diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/operations/_private_link_resources_operations.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/operations/_private_link_resources_operations.py index 32cf4bcfaee87..122c146169ba7 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/operations/_private_link_resources_operations.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/operations/_private_link_resources_operations.py @@ -6,163 +6,183 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, Callable, Dict, Optional, TypeVar -from msrest import Serializer - -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 HttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from ..._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False + def build_list_request( - subscription_id: str, - resource_group_name: str, - resource_name: str, - **kwargs: Any + resource_group_name: str, resource_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = kwargs.pop('api_version', "2022-05-31") # type: str + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateLinkResources") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateLinkResources", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=63, min_length=3, pattern=r'^(?!-)[A-Za-z0-9-]{3,63}(? HttpRequest: - api_version = kwargs.pop('api_version', "2022-05-31") # type: str + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateLinkResources/{resourceId}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateLinkResources/{resourceId}", + ) # 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', max_length=90, min_length=1), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=63, min_length=3, pattern=r'^(?!-)[A-Za-z0-9-]{3,63}(? "_models.GroupIdInformationResponse": + def list(self, resource_group_name: str, resource_name: str, **kwargs: Any) -> _models.GroupIdInformationResponse: """List private link resources for given Digital Twin. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: GroupIdInformationResponse, or the result of cls(response) + :return: GroupIdInformationResponse or the result of cls(response) :rtype: ~azure.mgmt.digitaltwins.v2022_05_31.models.GroupIdInformationResponse - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.GroupIdInformationResponse"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', "2022-05-31") # type: str + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + cls: ClsType[_models.GroupIdInformationResponse] = kwargs.pop("cls", None) - request = build_list_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list.metadata['url'], + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -170,63 +190,66 @@ def list( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('GroupIdInformationResponse', pipeline_response) + deserialized = self._deserialize("GroupIdInformationResponse", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - list.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateLinkResources"} # type: ignore - + list.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateLinkResources" + } @distributed_trace def get( - self, - resource_group_name: str, - resource_name: str, - resource_id: str, - **kwargs: Any - ) -> "_models.GroupIdInformation": + self, resource_group_name: str, resource_name: str, resource_id: str, **kwargs: Any + ) -> _models.GroupIdInformation: """Get the specified private link resource for the given Digital Twin. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param resource_id: The name of the private link resource. + :param resource_id: The name of the private link resource. Required. :type resource_id: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: GroupIdInformation, or the result of cls(response) + :return: GroupIdInformation or the result of cls(response) :rtype: ~azure.mgmt.digitaltwins.v2022_05_31.models.GroupIdInformation - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.GroupIdInformation"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', "2022-05-31") # type: str + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + cls: ClsType[_models.GroupIdInformation] = kwargs.pop("cls", None) - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, resource_id=resource_id, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -234,12 +257,13 @@ def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('GroupIdInformation', pipeline_response) + deserialized = self._deserialize("GroupIdInformation", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateLinkResources/{resourceId}"} # type: ignore - + get.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateLinkResources/{resourceId}" + } diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/operations/_time_series_database_connections_operations.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/operations/_time_series_database_connections_operations.py index f5b466a3c6101..0417705ebd4c8 100644 --- a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/operations/_time_series_database_connections_operations.py +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_05_31/operations/_time_series_database_connections_operations.py @@ -6,257 +6,320 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Iterable, Optional, TypeVar, Union - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import sys +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models +from ..._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') -JSONType = Any + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False + def build_list_request( - subscription_id: str, - resource_group_name: str, - resource_name: str, - **kwargs: Any + resource_group_name: str, resource_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: - api_version = kwargs.pop('api_version', "2022-05-31") # type: str + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections", + ) # 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', max_length=90, min_length=1), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=63, min_length=3, pattern=r'^(?!-)[A-Za-z0-9-]{3,63}(? HttpRequest: - api_version = kwargs.pop('api_version', "2022-05-31") # type: str + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections/{timeSeriesDatabaseConnectionName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections/{timeSeriesDatabaseConnectionName}", + ) # 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', max_length=90, min_length=1), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=63, min_length=3, pattern=r'^(?!-)[A-Za-z0-9-]{3,63}(? HttpRequest: - api_version = kwargs.pop('api_version', "2022-05-31") # type: str - content_type = kwargs.pop('content_type', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections/{timeSeriesDatabaseConnectionName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections/{timeSeriesDatabaseConnectionName}", + ) # 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', max_length=90, min_length=1), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=63, min_length=3, pattern=r'^(?!-)[A-Za-z0-9-]{3,63}(? HttpRequest: - api_version = kwargs.pop('api_version', "2022-05-31") # type: str + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + accept = _headers.pop("Accept", "application/json") - accept = "application/json" # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections/{timeSeriesDatabaseConnectionName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections/{timeSeriesDatabaseConnectionName}", + ) # 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', max_length=90, min_length=1), - "resourceName": _SERIALIZER.url("resource_name", resource_name, 'str', max_length=63, min_length=3, pattern=r'^(?!-)[A-Za-z0-9-]{3,63}(? Iterable["_models.TimeSeriesDatabaseConnectionListResult"]: + self, resource_group_name: str, resource_name: str, **kwargs: Any + ) -> Iterable["_models.TimeSeriesDatabaseConnection"]: """Get all existing time series database connections for this DigitalTwins instance. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either TimeSeriesDatabaseConnectionListResult or the - result of cls(response) + :return: An iterator like instance of either TimeSeriesDatabaseConnection or the result of + cls(response) :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.digitaltwins.v2022_05_31.models.TimeSeriesDatabaseConnectionListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.paging.ItemPaged[~azure.mgmt.digitaltwins.v2022_05_31.models.TimeSeriesDatabaseConnection] + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2022-05-31") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + cls: ClsType[_models.TimeSeriesDatabaseConnectionListResult] = kwargs.pop("cls", None) - cls = kwargs.pop('cls', None) # type: ClsType["_models.TimeSeriesDatabaseConnectionListResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list.metadata['url'], + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: - - request = build_list_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - resource_name=resource_name, - api_version=api_version, - template_url=next_link, + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) @@ -267,16 +330,14 @@ def extract_data(pipeline_response): deserialized = self._deserialize("TimeSeriesDatabaseConnectionListResult", pipeline_response) list_of_elem = deserialized.value if cls: - list_of_elem = cls(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -287,59 +348,61 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections"} # type: ignore + list.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections" + } @distributed_trace def get( - self, - resource_group_name: str, - resource_name: str, - time_series_database_connection_name: str, - **kwargs: Any - ) -> "_models.TimeSeriesDatabaseConnection": + self, resource_group_name: str, resource_name: str, time_series_database_connection_name: str, **kwargs: Any + ) -> _models.TimeSeriesDatabaseConnection: """Get the description of an existing time series database connection. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param time_series_database_connection_name: Name of time series database connection. + :param time_series_database_connection_name: Name of time series database connection. Required. :type time_series_database_connection_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: TimeSeriesDatabaseConnection, or the result of cls(response) + :return: TimeSeriesDatabaseConnection or the result of cls(response) :rtype: ~azure.mgmt.digitaltwins.v2022_05_31.models.TimeSeriesDatabaseConnection - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.TimeSeriesDatabaseConnection"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', "2022-05-31") # type: str + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + cls: ClsType[_models.TimeSeriesDatabaseConnection] = kwargs.pop("cls", None) - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, resource_name=resource_name, time_series_database_connection_name=time_series_database_connection_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: @@ -347,72 +410,172 @@ def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('TimeSeriesDatabaseConnection', pipeline_response) + deserialized = self._deserialize("TimeSeriesDatabaseConnection", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections/{timeSeriesDatabaseConnectionName}"} # type: ignore - + get.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections/{timeSeriesDatabaseConnectionName}" + } def _create_or_update_initial( self, resource_group_name: str, resource_name: str, time_series_database_connection_name: str, - time_series_database_connection_description: "_models.TimeSeriesDatabaseConnection", + time_series_database_connection_description: Union[_models.TimeSeriesDatabaseConnection, IO], **kwargs: Any - ) -> "_models.TimeSeriesDatabaseConnection": - cls = kwargs.pop('cls', None) # type: ClsType["_models.TimeSeriesDatabaseConnection"] + ) -> _models.TimeSeriesDatabaseConnection: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2022-05-31") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _json = self._serialize.body(time_series_database_connection_description, 'TimeSeriesDatabaseConnection') + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.TimeSeriesDatabaseConnection] = kwargs.pop("cls", None) - request = build_create_or_update_request_initial( - subscription_id=self._config.subscription_id, + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(time_series_database_connection_description, (IO, bytes)): + _content = time_series_database_connection_description + else: + _json = self._serialize.body(time_series_database_connection_description, "TimeSeriesDatabaseConnection") + + request = build_create_or_update_request( resource_group_name=resource_group_name, resource_name=resource_name, time_series_database_connection_name=time_series_database_connection_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._create_or_update_initial.metadata['url'], + content=_content, + template_url=self._create_or_update_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('TimeSeriesDatabaseConnection', pipeline_response) + deserialized = self._deserialize("TimeSeriesDatabaseConnection", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('TimeSeriesDatabaseConnection', pipeline_response) + deserialized = self._deserialize("TimeSeriesDatabaseConnection", pipeline_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized + return deserialized # type: ignore + + _create_or_update_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections/{timeSeriesDatabaseConnectionName}" + } + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + time_series_database_connection_name: str, + time_series_database_connection_description: _models.TimeSeriesDatabaseConnection, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.TimeSeriesDatabaseConnection]: + """Create or update a time series database connection. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param time_series_database_connection_name: Name of time series database connection. Required. + :type time_series_database_connection_name: str + :param time_series_database_connection_description: The time series database connection + description. Required. + :type time_series_database_connection_description: + ~azure.mgmt.digitaltwins.v2022_05_31.models.TimeSeriesDatabaseConnection + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either TimeSeriesDatabaseConnection or the + result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2022_05_31.models.TimeSeriesDatabaseConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ - _create_or_update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections/{timeSeriesDatabaseConnectionName}"} # type: ignore + @overload + def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + time_series_database_connection_name: str, + time_series_database_connection_description: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.TimeSeriesDatabaseConnection]: + """Create or update a time series database connection. + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param time_series_database_connection_name: Name of time series database connection. Required. + :type time_series_database_connection_name: str + :param time_series_database_connection_description: The time series database connection + description. Required. + :type time_series_database_connection_description: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either TimeSeriesDatabaseConnection or the + result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2022_05_31.models.TimeSeriesDatabaseConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace def begin_create_or_update( @@ -420,22 +583,25 @@ def begin_create_or_update( resource_group_name: str, resource_name: str, time_series_database_connection_name: str, - time_series_database_connection_description: "_models.TimeSeriesDatabaseConnection", + time_series_database_connection_description: Union[_models.TimeSeriesDatabaseConnection, IO], **kwargs: Any - ) -> LROPoller["_models.TimeSeriesDatabaseConnection"]: + ) -> LROPoller[_models.TimeSeriesDatabaseConnection]: """Create or update a time series database connection. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param time_series_database_connection_name: Name of time series database connection. + :param time_series_database_connection_name: Name of time series database connection. Required. :type time_series_database_connection_name: str :param time_series_database_connection_description: The time series database connection - description. + description. Is either a model type or a IO type. Required. :type time_series_database_connection_description: - ~azure.mgmt.digitaltwins.v2022_05_31.models.TimeSeriesDatabaseConnection + ~azure.mgmt.digitaltwins.v2022_05_31.models.TimeSeriesDatabaseConnection or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this @@ -448,17 +614,17 @@ def begin_create_or_update( result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2022_05_31.models.TimeSeriesDatabaseConnection] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2022-05-31") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.TimeSeriesDatabaseConnection"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.TimeSeriesDatabaseConnection] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = self._create_or_update_initial( resource_group_name=resource_group_name, @@ -467,102 +633,107 @@ def begin_create_or_update( time_series_database_connection_description=time_series_database_connection_description, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('TimeSeriesDatabaseConnection', pipeline_response) + deserialized = self._deserialize("TimeSeriesDatabaseConnection", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - begin_create_or_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections/{timeSeriesDatabaseConnectionName}"} # type: ignore + begin_create_or_update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections/{timeSeriesDatabaseConnectionName}" + } def _delete_initial( - self, - resource_group_name: str, - resource_name: str, - time_series_database_connection_name: str, - **kwargs: Any - ) -> Optional["_models.TimeSeriesDatabaseConnection"]: - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.TimeSeriesDatabaseConnection"]] + self, resource_group_name: str, resource_name: str, time_series_database_connection_name: str, **kwargs: Any + ) -> Optional[_models.TimeSeriesDatabaseConnection]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {}) or {}) - api_version = kwargs.pop('api_version', "2022-05-31") # type: str + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - request = build_delete_request_initial( - subscription_id=self._config.subscription_id, + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + cls: ClsType[Optional[_models.TimeSeriesDatabaseConnection]] = kwargs.pop("cls", None) + + request = build_delete_request( resource_group_name=resource_group_name, resource_name=resource_name, time_series_database_connection_name=time_series_database_connection_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._delete_initial.metadata['url'], + template_url=self._delete_initial.metadata["url"], + headers=_headers, + params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('TimeSeriesDatabaseConnection', pipeline_response) + deserialized = self._deserialize("TimeSeriesDatabaseConnection", pipeline_response) if response.status_code == 202: - deserialized = self._deserialize('TimeSeriesDatabaseConnection', pipeline_response) + deserialized = self._deserialize("TimeSeriesDatabaseConnection", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _delete_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections/{timeSeriesDatabaseConnectionName}"} # type: ignore - + _delete_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections/{timeSeriesDatabaseConnectionName}" + } @distributed_trace def begin_delete( - self, - resource_group_name: str, - resource_name: str, - time_series_database_connection_name: str, - **kwargs: Any - ) -> LROPoller["_models.TimeSeriesDatabaseConnection"]: + self, resource_group_name: str, resource_name: str, time_series_database_connection_name: str, **kwargs: Any + ) -> LROPoller[_models.TimeSeriesDatabaseConnection]: """Delete a time series database connection. :param resource_group_name: The name of the resource group that contains the - DigitalTwinsInstance. + DigitalTwinsInstance. Required. :type resource_group_name: str - :param resource_name: The name of the DigitalTwinsInstance. + :param resource_name: The name of the DigitalTwinsInstance. Required. :type resource_name: str - :param time_series_database_connection_name: Name of time series database connection. + :param time_series_database_connection_name: Name of time series database connection. Required. :type time_series_database_connection_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. @@ -576,45 +747,50 @@ def begin_delete( result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2022_05_31.models.TimeSeriesDatabaseConnection] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = kwargs.pop('api_version', "2022-05-31") # type: str - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.TimeSeriesDatabaseConnection"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-05-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-05-31")) + cls: ClsType[_models.TimeSeriesDatabaseConnection] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: raw_result = self._delete_initial( resource_group_name=resource_group_name, resource_name=resource_name, time_series_database_connection_name=time_series_database_connection_name, api_version=api_version, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - response = pipeline_response.http_response - deserialized = self._deserialize('TimeSeriesDatabaseConnection', pipeline_response) + deserialized = self._deserialize("TimeSeriesDatabaseConnection", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - - if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - begin_delete.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections/{timeSeriesDatabaseConnectionName}"} # type: ignore + begin_delete.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections/{timeSeriesDatabaseConnectionName}" + } diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/__init__.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/__init__.py new file mode 100644 index 0000000000000..3d416a868dd25 --- /dev/null +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/__init__.py @@ -0,0 +1,26 @@ +# 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_digital_twins_management_client import AzureDigitalTwinsManagementClient +from ._version import VERSION + +__version__ = VERSION + +try: + from ._patch import __all__ as _patch_all + from ._patch import * # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "AzureDigitalTwinsManagementClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/_azure_digital_twins_management_client.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/_azure_digital_twins_management_client.py new file mode 100644 index 0000000000000..8c81dab19b2d1 --- /dev/null +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/_azure_digital_twins_management_client.py @@ -0,0 +1,125 @@ +# 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 copy import deepcopy +from typing import Any, TYPE_CHECKING + +from azure.core.rest import HttpRequest, HttpResponse +from azure.mgmt.core import ARMPipelineClient + +from . import models as _models +from .._serialization import Deserializer, Serializer +from ._configuration import AzureDigitalTwinsManagementClientConfiguration +from .operations import ( + DigitalTwinsEndpointOperations, + DigitalTwinsOperations, + Operations, + PrivateEndpointConnectionsOperations, + PrivateLinkResourcesOperations, + TimeSeriesDatabaseConnectionsOperations, +) + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials import TokenCredential + + +class AzureDigitalTwinsManagementClient: # pylint: disable=client-accepts-api-version-keyword + """Azure Digital Twins Client for managing DigitalTwinsInstance. + + :ivar digital_twins: DigitalTwinsOperations operations + :vartype digital_twins: azure.mgmt.digitaltwins.v2022_10_31.operations.DigitalTwinsOperations + :ivar digital_twins_endpoint: DigitalTwinsEndpointOperations operations + :vartype digital_twins_endpoint: + azure.mgmt.digitaltwins.v2022_10_31.operations.DigitalTwinsEndpointOperations + :ivar operations: Operations operations + :vartype operations: azure.mgmt.digitaltwins.v2022_10_31.operations.Operations + :ivar private_link_resources: PrivateLinkResourcesOperations operations + :vartype private_link_resources: + azure.mgmt.digitaltwins.v2022_10_31.operations.PrivateLinkResourcesOperations + :ivar private_endpoint_connections: PrivateEndpointConnectionsOperations operations + :vartype private_endpoint_connections: + azure.mgmt.digitaltwins.v2022_10_31.operations.PrivateEndpointConnectionsOperations + :ivar time_series_database_connections: TimeSeriesDatabaseConnectionsOperations operations + :vartype time_series_database_connections: + azure.mgmt.digitaltwins.v2022_10_31.operations.TimeSeriesDatabaseConnectionsOperations + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The subscription identifier. Required. + :type subscription_id: str + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword api_version: Api Version. Default value is "2022-10-31". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + """ + + def __init__( + self, + credential: "TokenCredential", + subscription_id: str, + base_url: str = "https://management.azure.com", + **kwargs: Any + ) -> None: + self._config = AzureDigitalTwinsManagementClientConfiguration( + credential=credential, subscription_id=subscription_id, **kwargs + ) + self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.digital_twins = DigitalTwinsOperations(self._client, self._config, self._serialize, self._deserialize) + self.digital_twins_endpoint = DigitalTwinsEndpointOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) + self.private_link_resources = PrivateLinkResourcesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.private_endpoint_connections = PrivateEndpointConnectionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.time_series_database_connections = TimeSeriesDatabaseConnectionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + + def _send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.HttpResponse + """ + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) + + def close(self) -> None: + self._client.close() + + def __enter__(self) -> "AzureDigitalTwinsManagementClient": + self._client.__enter__() + return self + + def __exit__(self, *exc_details) -> None: + self._client.__exit__(*exc_details) diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/_configuration.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/_configuration.py new file mode 100644 index 0000000000000..726d8f8d6f285 --- /dev/null +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/_configuration.py @@ -0,0 +1,72 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +import sys +from typing import Any, TYPE_CHECKING + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy + +from ._version import VERSION + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials import TokenCredential + + +class AzureDigitalTwinsManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes + """Configuration for AzureDigitalTwinsManagementClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The subscription identifier. Required. + :type subscription_id: str + :keyword api_version: Api Version. Default value is "2022-10-31". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: + super(AzureDigitalTwinsManagementClientConfiguration, self).__init__(**kwargs) + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", "2022-10-31") + + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + + self.credential = credential + self.subscription_id = subscription_id + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-digitaltwins/{}".format(VERSION)) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = ARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/_metadata.json b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/_metadata.json new file mode 100644 index 0000000000000..be37a4586de01 --- /dev/null +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/_metadata.json @@ -0,0 +1,107 @@ +{ + "chosen_version": "2022-10-31", + "total_api_version_list": ["2022-10-31"], + "client": { + "name": "AzureDigitalTwinsManagementClient", + "filename": "_azure_digital_twins_management_client", + "description": "Azure Digital Twins Client for managing DigitalTwinsInstance.", + "host_value": "\"https://management.azure.com\"", + "parameterized_host_template": null, + "azure_arm": true, + "has_lro_operations": true, + "client_side_validation": false, + "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"AzureDigitalTwinsManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"AzureDigitalTwinsManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + }, + "global_parameters": { + "sync": { + "credential": { + "signature": "credential: \"TokenCredential\",", + "description": "Credential needed for the client to connect to Azure. Required.", + "docstring_type": "~azure.core.credentials.TokenCredential", + "required": true + }, + "subscription_id": { + "signature": "subscription_id: str,", + "description": "The subscription identifier. Required.", + "docstring_type": "str", + "required": true + } + }, + "async": { + "credential": { + "signature": "credential: \"AsyncTokenCredential\",", + "description": "Credential needed for the client to connect to Azure. Required.", + "docstring_type": "~azure.core.credentials_async.AsyncTokenCredential", + "required": true + }, + "subscription_id": { + "signature": "subscription_id: str,", + "description": "The subscription identifier. Required.", + "docstring_type": "str", + "required": true + } + }, + "constant": { + }, + "call": "credential, subscription_id", + "service_client_specific": { + "sync": { + "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 + } + }, + "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": { + "digital_twins": "DigitalTwinsOperations", + "digital_twins_endpoint": "DigitalTwinsEndpointOperations", + "operations": "Operations", + "private_link_resources": "PrivateLinkResourcesOperations", + "private_endpoint_connections": "PrivateEndpointConnectionsOperations", + "time_series_database_connections": "TimeSeriesDatabaseConnectionsOperations" + } +} diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/_patch.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/_patch.py new file mode 100644 index 0000000000000..f7dd32510333d --- /dev/null +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/_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/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/_vendor.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/_vendor.py new file mode 100644 index 0000000000000..9aad73fc743e7 --- /dev/null +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/_vendor.py @@ -0,0 +1,27 @@ +# -------------------------------------------------------------------------- +# 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.core.pipeline.transport import HttpRequest + + +def _convert_request(request, files=None): + data = request.content if not files else None + request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) + if files: + request.set_formdata_body(files) + return request + + +def _format_url_section(template, **kwargs): + components = template.split("/") + while components: + try: + return template.format(**kwargs) + except KeyError as key: + formatted_components = template.split("/") + components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] + template = "/".join(components) diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/_version.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/_version.py new file mode 100644 index 0000000000000..e5754a47ce68f --- /dev/null +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/_version.py @@ -0,0 +1,9 @@ +# 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. +# -------------------------------------------------------------------------- + +VERSION = "1.0.0b1" diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/aio/__init__.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/aio/__init__.py new file mode 100644 index 0000000000000..e4da5a5dc30c1 --- /dev/null +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/aio/__init__.py @@ -0,0 +1,23 @@ +# 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_digital_twins_management_client import AzureDigitalTwinsManagementClient + +try: + from ._patch import __all__ as _patch_all + from ._patch import * # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "AzureDigitalTwinsManagementClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/aio/_azure_digital_twins_management_client.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/aio/_azure_digital_twins_management_client.py new file mode 100644 index 0000000000000..2f3be7b2803b7 --- /dev/null +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/aio/_azure_digital_twins_management_client.py @@ -0,0 +1,126 @@ +# 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 copy import deepcopy +from typing import Any, Awaitable, TYPE_CHECKING + +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.mgmt.core import AsyncARMPipelineClient + +from .. import models as _models +from ..._serialization import Deserializer, Serializer +from ._configuration import AzureDigitalTwinsManagementClientConfiguration +from .operations import ( + DigitalTwinsEndpointOperations, + DigitalTwinsOperations, + Operations, + PrivateEndpointConnectionsOperations, + PrivateLinkResourcesOperations, + TimeSeriesDatabaseConnectionsOperations, +) + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + + +class AzureDigitalTwinsManagementClient: # pylint: disable=client-accepts-api-version-keyword + """Azure Digital Twins Client for managing DigitalTwinsInstance. + + :ivar digital_twins: DigitalTwinsOperations operations + :vartype digital_twins: + azure.mgmt.digitaltwins.v2022_10_31.aio.operations.DigitalTwinsOperations + :ivar digital_twins_endpoint: DigitalTwinsEndpointOperations operations + :vartype digital_twins_endpoint: + azure.mgmt.digitaltwins.v2022_10_31.aio.operations.DigitalTwinsEndpointOperations + :ivar operations: Operations operations + :vartype operations: azure.mgmt.digitaltwins.v2022_10_31.aio.operations.Operations + :ivar private_link_resources: PrivateLinkResourcesOperations operations + :vartype private_link_resources: + azure.mgmt.digitaltwins.v2022_10_31.aio.operations.PrivateLinkResourcesOperations + :ivar private_endpoint_connections: PrivateEndpointConnectionsOperations operations + :vartype private_endpoint_connections: + azure.mgmt.digitaltwins.v2022_10_31.aio.operations.PrivateEndpointConnectionsOperations + :ivar time_series_database_connections: TimeSeriesDatabaseConnectionsOperations operations + :vartype time_series_database_connections: + azure.mgmt.digitaltwins.v2022_10_31.aio.operations.TimeSeriesDatabaseConnectionsOperations + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The subscription identifier. Required. + :type subscription_id: str + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword api_version: Api Version. Default value is "2022-10-31". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + """ + + def __init__( + self, + credential: "AsyncTokenCredential", + subscription_id: str, + base_url: str = "https://management.azure.com", + **kwargs: Any + ) -> None: + self._config = AzureDigitalTwinsManagementClientConfiguration( + credential=credential, subscription_id=subscription_id, **kwargs + ) + self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + + client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.digital_twins = DigitalTwinsOperations(self._client, self._config, self._serialize, self._deserialize) + self.digital_twins_endpoint = DigitalTwinsEndpointOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) + self.private_link_resources = PrivateLinkResourcesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.private_endpoint_connections = PrivateEndpointConnectionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.time_series_database_connections = TimeSeriesDatabaseConnectionsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + + def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = await client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.AsyncHttpResponse + """ + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) + + async def close(self) -> None: + await self._client.close() + + async def __aenter__(self) -> "AzureDigitalTwinsManagementClient": + await self._client.__aenter__() + return self + + async def __aexit__(self, *exc_details) -> None: + await self._client.__aexit__(*exc_details) diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/aio/_configuration.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/aio/_configuration.py new file mode 100644 index 0000000000000..9a00820f754ff --- /dev/null +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/aio/_configuration.py @@ -0,0 +1,72 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +import sys +from typing import Any, TYPE_CHECKING + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy + +from .._version import VERSION + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + + +class AzureDigitalTwinsManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes + """Configuration for AzureDigitalTwinsManagementClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The subscription identifier. Required. + :type subscription_id: str + :keyword api_version: Api Version. Default value is "2022-10-31". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: + super(AzureDigitalTwinsManagementClientConfiguration, self).__init__(**kwargs) + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", "2022-10-31") + + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + + self.credential = credential + self.subscription_id = subscription_id + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-digitaltwins/{}".format(VERSION)) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/aio/_patch.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/aio/_patch.py new file mode 100644 index 0000000000000..f7dd32510333d --- /dev/null +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/aio/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/aio/operations/__init__.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/aio/operations/__init__.py new file mode 100644 index 0000000000000..791d2a1bb74f4 --- /dev/null +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/aio/operations/__init__.py @@ -0,0 +1,29 @@ +# 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 ._digital_twins_operations import DigitalTwinsOperations +from ._digital_twins_endpoint_operations import DigitalTwinsEndpointOperations +from ._operations import Operations +from ._private_link_resources_operations import PrivateLinkResourcesOperations +from ._private_endpoint_connections_operations import PrivateEndpointConnectionsOperations +from ._time_series_database_connections_operations import TimeSeriesDatabaseConnectionsOperations + +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "DigitalTwinsOperations", + "DigitalTwinsEndpointOperations", + "Operations", + "PrivateLinkResourcesOperations", + "PrivateEndpointConnectionsOperations", + "TimeSeriesDatabaseConnectionsOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/aio/operations/_digital_twins_endpoint_operations.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/aio/operations/_digital_twins_endpoint_operations.py new file mode 100644 index 0000000000000..1f7b250be9c24 --- /dev/null +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/aio/operations/_digital_twins_endpoint_operations.py @@ -0,0 +1,600 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._digital_twins_endpoint_operations import ( + build_create_or_update_request, + build_delete_request, + build_get_request, + build_list_request, +) + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class DigitalTwinsEndpointOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.digitaltwins.v2022_10_31.aio.AzureDigitalTwinsManagementClient`'s + :attr:`digital_twins_endpoint` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, resource_group_name: str, resource_name: str, **kwargs: Any + ) -> AsyncIterable["_models.DigitalTwinsEndpointResource"]: + """Get DigitalTwinsInstance Endpoints. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either DigitalTwinsEndpointResource or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.digitaltwins.v2022_10_31.models.DigitalTwinsEndpointResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + cls: ClsType[_models.DigitalTwinsEndpointResourceListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + resource_group_name=resource_group_name, + resource_name=resource_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("DigitalTwinsEndpointResourceListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints" + } + + @distributed_trace_async + async def get( + self, resource_group_name: str, resource_name: str, endpoint_name: str, **kwargs: Any + ) -> _models.DigitalTwinsEndpointResource: + """Get DigitalTwinsInstances Endpoint. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param endpoint_name: Name of Endpoint Resource. Required. + :type endpoint_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: DigitalTwinsEndpointResource or the result of cls(response) + :rtype: ~azure.mgmt.digitaltwins.v2022_10_31.models.DigitalTwinsEndpointResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + cls: ClsType[_models.DigitalTwinsEndpointResource] = kwargs.pop("cls", None) + + request = build_get_request( + resource_group_name=resource_group_name, + resource_name=resource_name, + endpoint_name=endpoint_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}" + } + + async def _create_or_update_initial( + self, + resource_group_name: str, + resource_name: str, + endpoint_name: str, + endpoint_description: Union[_models.DigitalTwinsEndpointResource, IO], + **kwargs: Any + ) -> _models.DigitalTwinsEndpointResource: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DigitalTwinsEndpointResource] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(endpoint_description, (IO, bytes)): + _content = endpoint_description + else: + _json = self._serialize.body(endpoint_description, "DigitalTwinsEndpointResource") + + request = build_create_or_update_request( + resource_group_name=resource_group_name, + resource_name=resource_name, + endpoint_name=endpoint_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self._create_or_update_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + _create_or_update_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}" + } + + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + endpoint_name: str, + endpoint_description: _models.DigitalTwinsEndpointResource, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.DigitalTwinsEndpointResource]: + """Create or update DigitalTwinsInstance endpoint. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param endpoint_name: Name of Endpoint Resource. Required. + :type endpoint_name: str + :param endpoint_description: The DigitalTwinsInstance endpoint metadata and security metadata. + Required. + :type endpoint_description: + ~azure.mgmt.digitaltwins.v2022_10_31.models.DigitalTwinsEndpointResource + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either DigitalTwinsEndpointResource or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2022_10_31.models.DigitalTwinsEndpointResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + endpoint_name: str, + endpoint_description: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.DigitalTwinsEndpointResource]: + """Create or update DigitalTwinsInstance endpoint. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param endpoint_name: Name of Endpoint Resource. Required. + :type endpoint_name: str + :param endpoint_description: The DigitalTwinsInstance endpoint metadata and security metadata. + Required. + :type endpoint_description: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either DigitalTwinsEndpointResource or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2022_10_31.models.DigitalTwinsEndpointResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + endpoint_name: str, + endpoint_description: Union[_models.DigitalTwinsEndpointResource, IO], + **kwargs: Any + ) -> AsyncLROPoller[_models.DigitalTwinsEndpointResource]: + """Create or update DigitalTwinsInstance endpoint. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param endpoint_name: Name of Endpoint Resource. Required. + :type endpoint_name: str + :param endpoint_description: The DigitalTwinsInstance endpoint metadata and security metadata. + Is either a model type or a IO type. Required. + :type endpoint_description: + ~azure.mgmt.digitaltwins.v2022_10_31.models.DigitalTwinsEndpointResource or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either DigitalTwinsEndpointResource or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2022_10_31.models.DigitalTwinsEndpointResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DigitalTwinsEndpointResource] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._create_or_update_initial( + resource_group_name=resource_group_name, + resource_name=resource_name, + endpoint_name=endpoint_name, + endpoint_description=endpoint_description, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + begin_create_or_update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}" + } + + async def _delete_initial( + self, resource_group_name: str, resource_name: str, endpoint_name: str, **kwargs: Any + ) -> Optional[_models.DigitalTwinsEndpointResource]: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + cls: ClsType[Optional[_models.DigitalTwinsEndpointResource]] = kwargs.pop("cls", None) + + request = build_delete_request( + resource_group_name=resource_group_name, + resource_name=resource_name, + endpoint_name=endpoint_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self._delete_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) + + if response.status_code == 202: + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + _delete_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}" + } + + @distributed_trace_async + async def begin_delete( + self, resource_group_name: str, resource_name: str, endpoint_name: str, **kwargs: Any + ) -> AsyncLROPoller[_models.DigitalTwinsEndpointResource]: + """Delete a DigitalTwinsInstance endpoint. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param endpoint_name: Name of Endpoint Resource. Required. + :type endpoint_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either DigitalTwinsEndpointResource or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2022_10_31.models.DigitalTwinsEndpointResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + cls: ClsType[_models.DigitalTwinsEndpointResource] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._delete_initial( + resource_group_name=resource_group_name, + resource_name=resource_name, + endpoint_name=endpoint_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + begin_delete.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}" + } diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/aio/operations/_digital_twins_operations.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/aio/operations/_digital_twins_operations.py new file mode 100644 index 0000000000000..f61a53693a415 --- /dev/null +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/aio/operations/_digital_twins_operations.py @@ -0,0 +1,1029 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._digital_twins_operations import ( + build_check_name_availability_request, + build_create_or_update_request, + build_delete_request, + build_get_request, + build_list_by_resource_group_request, + build_list_request, + build_update_request, +) + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class DigitalTwinsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.digitaltwins.v2022_10_31.aio.AzureDigitalTwinsManagementClient`'s + :attr:`digital_twins` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def get(self, resource_group_name: str, resource_name: str, **kwargs: Any) -> _models.DigitalTwinsDescription: + """Get DigitalTwinsInstances resource. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: DigitalTwinsDescription or the result of cls(response) + :rtype: ~azure.mgmt.digitaltwins.v2022_10_31.models.DigitalTwinsDescription + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + cls: ClsType[_models.DigitalTwinsDescription] = kwargs.pop("cls", None) + + request = build_get_request( + resource_group_name=resource_group_name, + resource_name=resource_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } + + async def _create_or_update_initial( + self, + resource_group_name: str, + resource_name: str, + digital_twins_create: Union[_models.DigitalTwinsDescription, IO], + **kwargs: Any + ) -> _models.DigitalTwinsDescription: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DigitalTwinsDescription] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(digital_twins_create, (IO, bytes)): + _content = digital_twins_create + else: + _json = self._serialize.body(digital_twins_create, "DigitalTwinsDescription") + + request = build_create_or_update_request( + resource_group_name=resource_group_name, + resource_name=resource_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self._create_or_update_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + _create_or_update_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } + + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + digital_twins_create: _models.DigitalTwinsDescription, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.DigitalTwinsDescription]: + """Create or update the metadata of a DigitalTwinsInstance. The usual pattern to modify a property + is to retrieve the DigitalTwinsInstance and security metadata, and then combine them with the + modified values in a new body to update the DigitalTwinsInstance. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param digital_twins_create: The DigitalTwinsInstance and security metadata. Required. + :type digital_twins_create: ~azure.mgmt.digitaltwins.v2022_10_31.models.DigitalTwinsDescription + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either DigitalTwinsDescription or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2022_10_31.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + digital_twins_create: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.DigitalTwinsDescription]: + """Create or update the metadata of a DigitalTwinsInstance. The usual pattern to modify a property + is to retrieve the DigitalTwinsInstance and security metadata, and then combine them with the + modified values in a new body to update the DigitalTwinsInstance. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param digital_twins_create: The DigitalTwinsInstance and security metadata. Required. + :type digital_twins_create: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either DigitalTwinsDescription or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2022_10_31.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + digital_twins_create: Union[_models.DigitalTwinsDescription, IO], + **kwargs: Any + ) -> AsyncLROPoller[_models.DigitalTwinsDescription]: + """Create or update the metadata of a DigitalTwinsInstance. The usual pattern to modify a property + is to retrieve the DigitalTwinsInstance and security metadata, and then combine them with the + modified values in a new body to update the DigitalTwinsInstance. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param digital_twins_create: The DigitalTwinsInstance and security metadata. Is either a model + type or a IO type. Required. + :type digital_twins_create: ~azure.mgmt.digitaltwins.v2022_10_31.models.DigitalTwinsDescription + or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either DigitalTwinsDescription or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2022_10_31.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DigitalTwinsDescription] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._create_or_update_initial( + resource_group_name=resource_group_name, + resource_name=resource_name, + digital_twins_create=digital_twins_create, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + begin_create_or_update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } + + async def _update_initial( + self, + resource_group_name: str, + resource_name: str, + digital_twins_patch_description: Union[_models.DigitalTwinsPatchDescription, IO], + **kwargs: Any + ) -> _models.DigitalTwinsDescription: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DigitalTwinsDescription] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(digital_twins_patch_description, (IO, bytes)): + _content = digital_twins_patch_description + else: + _json = self._serialize.body(digital_twins_patch_description, "DigitalTwinsPatchDescription") + + request = build_update_request( + resource_group_name=resource_group_name, + resource_name=resource_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self._update_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) + + if response.status_code == 202: + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + _update_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } + + @overload + async def begin_update( + self, + resource_group_name: str, + resource_name: str, + digital_twins_patch_description: _models.DigitalTwinsPatchDescription, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.DigitalTwinsDescription]: + """Update metadata of DigitalTwinsInstance. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param digital_twins_patch_description: The DigitalTwinsInstance and security metadata. + Required. + :type digital_twins_patch_description: + ~azure.mgmt.digitaltwins.v2022_10_31.models.DigitalTwinsPatchDescription + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either DigitalTwinsDescription or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2022_10_31.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_update( + self, + resource_group_name: str, + resource_name: str, + digital_twins_patch_description: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.DigitalTwinsDescription]: + """Update metadata of DigitalTwinsInstance. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param digital_twins_patch_description: The DigitalTwinsInstance and security metadata. + Required. + :type digital_twins_patch_description: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either DigitalTwinsDescription or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2022_10_31.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_update( + self, + resource_group_name: str, + resource_name: str, + digital_twins_patch_description: Union[_models.DigitalTwinsPatchDescription, IO], + **kwargs: Any + ) -> AsyncLROPoller[_models.DigitalTwinsDescription]: + """Update metadata of DigitalTwinsInstance. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param digital_twins_patch_description: The DigitalTwinsInstance and security metadata. Is + either a model type or a IO type. Required. + :type digital_twins_patch_description: + ~azure.mgmt.digitaltwins.v2022_10_31.models.DigitalTwinsPatchDescription or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either DigitalTwinsDescription or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2022_10_31.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DigitalTwinsDescription] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._update_initial( + resource_group_name=resource_group_name, + resource_name=resource_name, + digital_twins_patch_description=digital_twins_patch_description, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + begin_update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } + + async def _delete_initial( + self, resource_group_name: str, resource_name: str, **kwargs: Any + ) -> Optional[_models.DigitalTwinsDescription]: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + cls: ClsType[Optional[_models.DigitalTwinsDescription]] = kwargs.pop("cls", None) + + request = build_delete_request( + resource_group_name=resource_group_name, + resource_name=resource_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self._delete_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) + + if response.status_code == 202: + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + _delete_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } + + @distributed_trace_async + async def begin_delete( + self, resource_group_name: str, resource_name: str, **kwargs: Any + ) -> AsyncLROPoller[_models.DigitalTwinsDescription]: + """Delete a DigitalTwinsInstance. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either DigitalTwinsDescription or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2022_10_31.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + cls: ClsType[_models.DigitalTwinsDescription] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._delete_initial( + resource_group_name=resource_group_name, + resource_name=resource_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + begin_delete.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } + + @distributed_trace + def list(self, **kwargs: Any) -> AsyncIterable["_models.DigitalTwinsDescription"]: + """Get all the DigitalTwinsInstances in a subscription. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either DigitalTwinsDescription or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.digitaltwins.v2022_10_31.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + cls: ClsType[_models.DigitalTwinsDescriptionListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("DigitalTwinsDescriptionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.DigitalTwins/digitalTwinsInstances"} + + @distributed_trace + def list_by_resource_group( + self, resource_group_name: str, **kwargs: Any + ) -> AsyncIterable["_models.DigitalTwinsDescription"]: + """Get all the DigitalTwinsInstances in a resource group. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. 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 DigitalTwinsDescription or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.digitaltwins.v2022_10_31.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + cls: ClsType[_models.DigitalTwinsDescriptionListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_by_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list_by_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("DigitalTwinsDescriptionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list_by_resource_group.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances" + } + + @overload + async def check_name_availability( + self, + location: str, + digital_twins_instance_check_name: _models.CheckNameRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.CheckNameResult: + """Check if a DigitalTwinsInstance name is available. + + :param location: Location of DigitalTwinsInstance. Required. + :type location: str + :param digital_twins_instance_check_name: Set the name parameter in the + DigitalTwinsInstanceCheckName structure to the name of the DigitalTwinsInstance to check. + Required. + :type digital_twins_instance_check_name: + ~azure.mgmt.digitaltwins.v2022_10_31.models.CheckNameRequest + :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: CheckNameResult or the result of cls(response) + :rtype: ~azure.mgmt.digitaltwins.v2022_10_31.models.CheckNameResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def check_name_availability( + self, + location: str, + digital_twins_instance_check_name: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.CheckNameResult: + """Check if a DigitalTwinsInstance name is available. + + :param location: Location of DigitalTwinsInstance. Required. + :type location: str + :param digital_twins_instance_check_name: Set the name parameter in the + DigitalTwinsInstanceCheckName structure to the name of the DigitalTwinsInstance to check. + Required. + :type digital_twins_instance_check_name: 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: CheckNameResult or the result of cls(response) + :rtype: ~azure.mgmt.digitaltwins.v2022_10_31.models.CheckNameResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def check_name_availability( + self, location: str, digital_twins_instance_check_name: Union[_models.CheckNameRequest, IO], **kwargs: Any + ) -> _models.CheckNameResult: + """Check if a DigitalTwinsInstance name is available. + + :param location: Location of DigitalTwinsInstance. Required. + :type location: str + :param digital_twins_instance_check_name: Set the name parameter in the + DigitalTwinsInstanceCheckName structure to the name of the DigitalTwinsInstance to check. Is + either a model type or a IO type. Required. + :type digital_twins_instance_check_name: + ~azure.mgmt.digitaltwins.v2022_10_31.models.CheckNameRequest 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: CheckNameResult or the result of cls(response) + :rtype: ~azure.mgmt.digitaltwins.v2022_10_31.models.CheckNameResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.CheckNameResult] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(digital_twins_instance_check_name, (IO, bytes)): + _content = digital_twins_instance_check_name + else: + _json = self._serialize.body(digital_twins_instance_check_name, "CheckNameRequest") + + request = build_check_name_availability_request( + location=location, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.check_name_availability.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("CheckNameResult", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + check_name_availability.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.DigitalTwins/locations/{location}/checkNameAvailability" + } diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/aio/operations/_operations.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/aio/operations/_operations.py new file mode 100644 index 0000000000000..a4b820a4a03a1 --- /dev/null +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/aio/operations/_operations.py @@ -0,0 +1,138 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._operations import build_list_request + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class Operations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.digitaltwins.v2022_10_31.aio.AzureDigitalTwinsManagementClient`'s + :attr:`operations` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, **kwargs: Any) -> AsyncIterable["_models.Operation"]: + """Lists all of the available DigitalTwins service REST API operations. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either Operation or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.digitaltwins.v2022_10_31.models.Operation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("OperationListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/providers/Microsoft.DigitalTwins/operations"} diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/aio/operations/_patch.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/aio/operations/_patch.py new file mode 100644 index 0000000000000..f7dd32510333d --- /dev/null +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/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/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/aio/operations/_private_endpoint_connections_operations.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/aio/operations/_private_endpoint_connections_operations.py new file mode 100644 index 0000000000000..5d1a690d969fe --- /dev/null +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/aio/operations/_private_endpoint_connections_operations.py @@ -0,0 +1,555 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, cast, 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.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +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 azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._private_endpoint_connections_operations import ( + build_create_or_update_request, + build_delete_request, + build_get_request, + build_list_request, +) + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class PrivateEndpointConnectionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.digitaltwins.v2022_10_31.aio.AzureDigitalTwinsManagementClient`'s + :attr:`private_endpoint_connections` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def list( + self, resource_group_name: str, resource_name: str, **kwargs: Any + ) -> _models.PrivateEndpointConnectionsResponse: + """List private endpoint connection properties. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PrivateEndpointConnectionsResponse or the result of cls(response) + :rtype: ~azure.mgmt.digitaltwins.v2022_10_31.models.PrivateEndpointConnectionsResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + cls: ClsType[_models.PrivateEndpointConnectionsResponse] = kwargs.pop("cls", None) + + request = build_list_request( + resource_group_name=resource_group_name, + resource_name=resource_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PrivateEndpointConnectionsResponse", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + list.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections" + } + + @distributed_trace_async + async def get( + self, resource_group_name: str, resource_name: str, private_endpoint_connection_name: str, **kwargs: Any + ) -> _models.PrivateEndpointConnection: + """Get private endpoint connection properties for the given private endpoint. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param private_endpoint_connection_name: The name of the private endpoint connection. Required. + :type private_endpoint_connection_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PrivateEndpointConnection or the result of cls(response) + :rtype: ~azure.mgmt.digitaltwins.v2022_10_31.models.PrivateEndpointConnection + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + cls: ClsType[_models.PrivateEndpointConnection] = kwargs.pop("cls", None) + + request = build_get_request( + resource_group_name=resource_group_name, + resource_name=resource_name, + private_endpoint_connection_name=private_endpoint_connection_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}" + } + + async def _delete_initial( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, resource_name: str, private_endpoint_connection_name: str, **kwargs: Any + ) -> None: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + cls: ClsType[None] = kwargs.pop("cls", None) + + request = build_delete_request( + resource_group_name=resource_group_name, + resource_name=resource_name, + private_endpoint_connection_name=private_endpoint_connection_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self._delete_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}" + } + + @distributed_trace_async + async def begin_delete( + self, resource_group_name: str, resource_name: str, private_endpoint_connection_name: str, **kwargs: Any + ) -> AsyncLROPoller[None]: + """Delete private endpoint connection with the specified name. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param private_endpoint_connection_name: The name of the private endpoint connection. Required. + :type private_endpoint_connection_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._delete_initial( # type: ignore + resource_group_name=resource_group_name, + resource_name=resource_name, + private_endpoint_connection_name=private_endpoint_connection_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + begin_delete.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}" + } + + async def _create_or_update_initial( + self, + resource_group_name: str, + resource_name: str, + private_endpoint_connection_name: str, + private_endpoint_connection: Union[_models.PrivateEndpointConnection, IO], + **kwargs: Any + ) -> _models.PrivateEndpointConnection: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PrivateEndpointConnection] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(private_endpoint_connection, (IO, bytes)): + _content = private_endpoint_connection + else: + _json = self._serialize.body(private_endpoint_connection, "PrivateEndpointConnection") + + request = build_create_or_update_request( + resource_group_name=resource_group_name, + resource_name=resource_name, + private_endpoint_connection_name=private_endpoint_connection_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self._create_or_update_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) + + if response.status_code == 202: + deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + _create_or_update_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}" + } + + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + private_endpoint_connection_name: str, + private_endpoint_connection: _models.PrivateEndpointConnection, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.PrivateEndpointConnection]: + """Update the status of a private endpoint connection with the given name. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param private_endpoint_connection_name: The name of the private endpoint connection. Required. + :type private_endpoint_connection_name: str + :param private_endpoint_connection: The private endpoint connection with updated properties. + Required. + :type private_endpoint_connection: + ~azure.mgmt.digitaltwins.v2022_10_31.models.PrivateEndpointConnection + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either PrivateEndpointConnection or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2022_10_31.models.PrivateEndpointConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + private_endpoint_connection_name: str, + private_endpoint_connection: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.PrivateEndpointConnection]: + """Update the status of a private endpoint connection with the given name. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param private_endpoint_connection_name: The name of the private endpoint connection. Required. + :type private_endpoint_connection_name: str + :param private_endpoint_connection: The private endpoint connection with updated properties. + Required. + :type private_endpoint_connection: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either PrivateEndpointConnection or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2022_10_31.models.PrivateEndpointConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + private_endpoint_connection_name: str, + private_endpoint_connection: Union[_models.PrivateEndpointConnection, IO], + **kwargs: Any + ) -> AsyncLROPoller[_models.PrivateEndpointConnection]: + """Update the status of a private endpoint connection with the given name. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param private_endpoint_connection_name: The name of the private endpoint connection. Required. + :type private_endpoint_connection_name: str + :param private_endpoint_connection: The private endpoint connection with updated properties. Is + either a model type or a IO type. Required. + :type private_endpoint_connection: + ~azure.mgmt.digitaltwins.v2022_10_31.models.PrivateEndpointConnection or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either PrivateEndpointConnection or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2022_10_31.models.PrivateEndpointConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PrivateEndpointConnection] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._create_or_update_initial( + resource_group_name=resource_group_name, + resource_name=resource_name, + private_endpoint_connection_name=private_endpoint_connection_name, + private_endpoint_connection=private_endpoint_connection, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + begin_create_or_update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}" + } diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/aio/operations/_private_link_resources_operations.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/aio/operations/_private_link_resources_operations.py new file mode 100644 index 0000000000000..92b7d69ca6682 --- /dev/null +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/aio/operations/_private_link_resources_operations.py @@ -0,0 +1,187 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import 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._private_link_resources_operations import build_get_request, build_list_request + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class PrivateLinkResourcesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.digitaltwins.v2022_10_31.aio.AzureDigitalTwinsManagementClient`'s + :attr:`private_link_resources` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def list( + self, resource_group_name: str, resource_name: str, **kwargs: Any + ) -> _models.GroupIdInformationResponse: + """List private link resources for given Digital Twin. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: GroupIdInformationResponse or the result of cls(response) + :rtype: ~azure.mgmt.digitaltwins.v2022_10_31.models.GroupIdInformationResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + cls: ClsType[_models.GroupIdInformationResponse] = kwargs.pop("cls", None) + + request = build_list_request( + resource_group_name=resource_group_name, + resource_name=resource_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("GroupIdInformationResponse", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + list.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateLinkResources" + } + + @distributed_trace_async + async def get( + self, resource_group_name: str, resource_name: str, resource_id: str, **kwargs: Any + ) -> _models.GroupIdInformation: + """Get the specified private link resource for the given Digital Twin. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param resource_id: The name of the private link resource. Required. + :type resource_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: GroupIdInformation or the result of cls(response) + :rtype: ~azure.mgmt.digitaltwins.v2022_10_31.models.GroupIdInformation + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + cls: ClsType[_models.GroupIdInformation] = kwargs.pop("cls", None) + + request = build_get_request( + resource_group_name=resource_group_name, + resource_name=resource_name, + resource_id=resource_id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("GroupIdInformation", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateLinkResources/{resourceId}" + } diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/aio/operations/_time_series_database_connections_operations.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/aio/operations/_time_series_database_connections_operations.py new file mode 100644 index 0000000000000..2a850319ddf8f --- /dev/null +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/aio/operations/_time_series_database_connections_operations.py @@ -0,0 +1,600 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + +from ... import models as _models +from ..._vendor import _convert_request +from ...operations._time_series_database_connections_operations import ( + build_create_or_update_request, + build_delete_request, + build_get_request, + build_list_request, +) + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class TimeSeriesDatabaseConnectionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.digitaltwins.v2022_10_31.aio.AzureDigitalTwinsManagementClient`'s + :attr:`time_series_database_connections` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list( + self, resource_group_name: str, resource_name: str, **kwargs: Any + ) -> AsyncIterable["_models.TimeSeriesDatabaseConnection"]: + """Get all existing time series database connections for this DigitalTwins instance. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either TimeSeriesDatabaseConnection or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.digitaltwins.v2022_10_31.models.TimeSeriesDatabaseConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + cls: ClsType[_models.TimeSeriesDatabaseConnectionListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + resource_group_name=resource_group_name, + resource_name=resource_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("TimeSeriesDatabaseConnectionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + list.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections" + } + + @distributed_trace_async + async def get( + self, resource_group_name: str, resource_name: str, time_series_database_connection_name: str, **kwargs: Any + ) -> _models.TimeSeriesDatabaseConnection: + """Get the description of an existing time series database connection. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param time_series_database_connection_name: Name of time series database connection. Required. + :type time_series_database_connection_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: TimeSeriesDatabaseConnection or the result of cls(response) + :rtype: ~azure.mgmt.digitaltwins.v2022_10_31.models.TimeSeriesDatabaseConnection + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + cls: ClsType[_models.TimeSeriesDatabaseConnection] = kwargs.pop("cls", None) + + request = build_get_request( + resource_group_name=resource_group_name, + resource_name=resource_name, + time_series_database_connection_name=time_series_database_connection_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("TimeSeriesDatabaseConnection", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections/{timeSeriesDatabaseConnectionName}" + } + + async def _create_or_update_initial( + self, + resource_group_name: str, + resource_name: str, + time_series_database_connection_name: str, + time_series_database_connection_description: Union[_models.TimeSeriesDatabaseConnection, IO], + **kwargs: Any + ) -> _models.TimeSeriesDatabaseConnection: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.TimeSeriesDatabaseConnection] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(time_series_database_connection_description, (IO, bytes)): + _content = time_series_database_connection_description + else: + _json = self._serialize.body(time_series_database_connection_description, "TimeSeriesDatabaseConnection") + + request = build_create_or_update_request( + resource_group_name=resource_group_name, + resource_name=resource_name, + time_series_database_connection_name=time_series_database_connection_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self._create_or_update_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize("TimeSeriesDatabaseConnection", pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize("TimeSeriesDatabaseConnection", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + _create_or_update_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections/{timeSeriesDatabaseConnectionName}" + } + + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + time_series_database_connection_name: str, + time_series_database_connection_description: _models.TimeSeriesDatabaseConnection, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.TimeSeriesDatabaseConnection]: + """Create or update a time series database connection. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param time_series_database_connection_name: Name of time series database connection. Required. + :type time_series_database_connection_name: str + :param time_series_database_connection_description: The time series database connection + description. Required. + :type time_series_database_connection_description: + ~azure.mgmt.digitaltwins.v2022_10_31.models.TimeSeriesDatabaseConnection + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either TimeSeriesDatabaseConnection or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2022_10_31.models.TimeSeriesDatabaseConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + time_series_database_connection_name: str, + time_series_database_connection_description: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.TimeSeriesDatabaseConnection]: + """Create or update a time series database connection. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param time_series_database_connection_name: Name of time series database connection. Required. + :type time_series_database_connection_name: str + :param time_series_database_connection_description: The time series database connection + description. Required. + :type time_series_database_connection_description: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either TimeSeriesDatabaseConnection or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2022_10_31.models.TimeSeriesDatabaseConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + time_series_database_connection_name: str, + time_series_database_connection_description: Union[_models.TimeSeriesDatabaseConnection, IO], + **kwargs: Any + ) -> AsyncLROPoller[_models.TimeSeriesDatabaseConnection]: + """Create or update a time series database connection. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param time_series_database_connection_name: Name of time series database connection. Required. + :type time_series_database_connection_name: str + :param time_series_database_connection_description: The time series database connection + description. Is either a model type or a IO type. Required. + :type time_series_database_connection_description: + ~azure.mgmt.digitaltwins.v2022_10_31.models.TimeSeriesDatabaseConnection or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either TimeSeriesDatabaseConnection or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2022_10_31.models.TimeSeriesDatabaseConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.TimeSeriesDatabaseConnection] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._create_or_update_initial( + resource_group_name=resource_group_name, + resource_name=resource_name, + time_series_database_connection_name=time_series_database_connection_name, + time_series_database_connection_description=time_series_database_connection_description, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("TimeSeriesDatabaseConnection", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + begin_create_or_update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections/{timeSeriesDatabaseConnectionName}" + } + + async def _delete_initial( + self, resource_group_name: str, resource_name: str, time_series_database_connection_name: str, **kwargs: Any + ) -> Optional[_models.TimeSeriesDatabaseConnection]: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + cls: ClsType[Optional[_models.TimeSeriesDatabaseConnection]] = kwargs.pop("cls", None) + + request = build_delete_request( + resource_group_name=resource_group_name, + resource_name=resource_name, + time_series_database_connection_name=time_series_database_connection_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self._delete_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize("TimeSeriesDatabaseConnection", pipeline_response) + + if response.status_code == 202: + deserialized = self._deserialize("TimeSeriesDatabaseConnection", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + _delete_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections/{timeSeriesDatabaseConnectionName}" + } + + @distributed_trace_async + async def begin_delete( + self, resource_group_name: str, resource_name: str, time_series_database_connection_name: str, **kwargs: Any + ) -> AsyncLROPoller[_models.TimeSeriesDatabaseConnection]: + """Delete a time series database connection. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param time_series_database_connection_name: Name of time series database connection. Required. + :type time_series_database_connection_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either TimeSeriesDatabaseConnection or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.digitaltwins.v2022_10_31.models.TimeSeriesDatabaseConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + cls: ClsType[_models.TimeSeriesDatabaseConnection] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._delete_initial( + resource_group_name=resource_group_name, + resource_name=resource_name, + time_series_database_connection_name=time_series_database_connection_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("TimeSeriesDatabaseConnection", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + begin_delete.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections/{timeSeriesDatabaseConnectionName}" + } diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/models/__init__.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/models/__init__.py new file mode 100644 index 0000000000000..91711000ace2a --- /dev/null +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/models/__init__.py @@ -0,0 +1,115 @@ +# 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 ._models_py3 import AzureDataExplorerConnectionProperties +from ._models_py3 import CheckNameRequest +from ._models_py3 import CheckNameResult +from ._models_py3 import ConnectionProperties +from ._models_py3 import ConnectionPropertiesPrivateLinkServiceConnectionState +from ._models_py3 import ConnectionState +from ._models_py3 import DigitalTwinsDescription +from ._models_py3 import DigitalTwinsDescriptionListResult +from ._models_py3 import DigitalTwinsEndpointResource +from ._models_py3 import DigitalTwinsEndpointResourceListResult +from ._models_py3 import DigitalTwinsEndpointResourceProperties +from ._models_py3 import DigitalTwinsIdentity +from ._models_py3 import DigitalTwinsPatchDescription +from ._models_py3 import DigitalTwinsPatchProperties +from ._models_py3 import DigitalTwinsResource +from ._models_py3 import ErrorDefinition +from ._models_py3 import ErrorResponse +from ._models_py3 import EventGrid +from ._models_py3 import EventHub +from ._models_py3 import ExternalResource +from ._models_py3 import GroupIdInformation +from ._models_py3 import GroupIdInformationProperties +from ._models_py3 import GroupIdInformationResponse +from ._models_py3 import ManagedIdentityReference +from ._models_py3 import Operation +from ._models_py3 import OperationDisplay +from ._models_py3 import OperationListResult +from ._models_py3 import PrivateEndpoint +from ._models_py3 import PrivateEndpointConnection +from ._models_py3 import PrivateEndpointConnectionsResponse +from ._models_py3 import ServiceBus +from ._models_py3 import SystemData +from ._models_py3 import TimeSeriesDatabaseConnection +from ._models_py3 import TimeSeriesDatabaseConnectionListResult +from ._models_py3 import TimeSeriesDatabaseConnectionProperties +from ._models_py3 import UserAssignedIdentity + +from ._azure_digital_twins_management_client_enums import AuthenticationType +from ._azure_digital_twins_management_client_enums import ConnectionPropertiesProvisioningState +from ._azure_digital_twins_management_client_enums import ConnectionType +from ._azure_digital_twins_management_client_enums import CreatedByType +from ._azure_digital_twins_management_client_enums import DigitalTwinsIdentityType +from ._azure_digital_twins_management_client_enums import EndpointProvisioningState +from ._azure_digital_twins_management_client_enums import EndpointType +from ._azure_digital_twins_management_client_enums import IdentityType +from ._azure_digital_twins_management_client_enums import PrivateLinkServiceConnectionStatus +from ._azure_digital_twins_management_client_enums import ProvisioningState +from ._azure_digital_twins_management_client_enums import PublicNetworkAccess +from ._azure_digital_twins_management_client_enums import Reason +from ._azure_digital_twins_management_client_enums import TimeSeriesDatabaseConnectionState +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "AzureDataExplorerConnectionProperties", + "CheckNameRequest", + "CheckNameResult", + "ConnectionProperties", + "ConnectionPropertiesPrivateLinkServiceConnectionState", + "ConnectionState", + "DigitalTwinsDescription", + "DigitalTwinsDescriptionListResult", + "DigitalTwinsEndpointResource", + "DigitalTwinsEndpointResourceListResult", + "DigitalTwinsEndpointResourceProperties", + "DigitalTwinsIdentity", + "DigitalTwinsPatchDescription", + "DigitalTwinsPatchProperties", + "DigitalTwinsResource", + "ErrorDefinition", + "ErrorResponse", + "EventGrid", + "EventHub", + "ExternalResource", + "GroupIdInformation", + "GroupIdInformationProperties", + "GroupIdInformationResponse", + "ManagedIdentityReference", + "Operation", + "OperationDisplay", + "OperationListResult", + "PrivateEndpoint", + "PrivateEndpointConnection", + "PrivateEndpointConnectionsResponse", + "ServiceBus", + "SystemData", + "TimeSeriesDatabaseConnection", + "TimeSeriesDatabaseConnectionListResult", + "TimeSeriesDatabaseConnectionProperties", + "UserAssignedIdentity", + "AuthenticationType", + "ConnectionPropertiesProvisioningState", + "ConnectionType", + "CreatedByType", + "DigitalTwinsIdentityType", + "EndpointProvisioningState", + "EndpointType", + "IdentityType", + "PrivateLinkServiceConnectionStatus", + "ProvisioningState", + "PublicNetworkAccess", + "Reason", + "TimeSeriesDatabaseConnectionState", +] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/models/_azure_digital_twins_management_client_enums.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/models/_azure_digital_twins_management_client_enums.py new file mode 100644 index 0000000000000..ec2b72e3b19f2 --- /dev/null +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/models/_azure_digital_twins_management_client_enums.py @@ -0,0 +1,142 @@ +# 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 enum import Enum +from azure.core import CaseInsensitiveEnumMeta + + +class AuthenticationType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Specifies the authentication type being used for connecting to the endpoint. Defaults to + 'KeyBased'. If 'KeyBased' is selected, a connection string must be specified (at least the + primary connection string). If 'IdentityBased' is select, the endpointUri and entityPath + properties must be specified. + """ + + KEY_BASED = "KeyBased" + IDENTITY_BASED = "IdentityBased" + + +class ConnectionPropertiesProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The provisioning state.""" + + PENDING = "Pending" + APPROVED = "Approved" + REJECTED = "Rejected" + DISCONNECTED = "Disconnected" + + +class ConnectionType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of time series connection resource.""" + + AZURE_DATA_EXPLORER = "AzureDataExplorer" + + +class CreatedByType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of identity that created the resource.""" + + USER = "User" + APPLICATION = "Application" + MANAGED_IDENTITY = "ManagedIdentity" + KEY = "Key" + + +class DigitalTwinsIdentityType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of Managed Identity used by the DigitalTwinsInstance.""" + + NONE = "None" + SYSTEM_ASSIGNED = "SystemAssigned" + USER_ASSIGNED = "UserAssigned" + SYSTEM_ASSIGNED_USER_ASSIGNED = "SystemAssigned,UserAssigned" + + +class EndpointProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The provisioning state.""" + + PROVISIONING = "Provisioning" + DELETING = "Deleting" + UPDATING = "Updating" + SUCCEEDED = "Succeeded" + FAILED = "Failed" + CANCELED = "Canceled" + DELETED = "Deleted" + WARNING = "Warning" + SUSPENDING = "Suspending" + RESTORING = "Restoring" + MOVING = "Moving" + DISABLED = "Disabled" + + +class EndpointType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of Digital Twins endpoint.""" + + EVENT_HUB = "EventHub" + EVENT_GRID = "EventGrid" + SERVICE_BUS = "ServiceBus" + + +class IdentityType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of managed identity used.""" + + SYSTEM_ASSIGNED = "SystemAssigned" + USER_ASSIGNED = "UserAssigned" + + +class PrivateLinkServiceConnectionStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The status of a private endpoint connection.""" + + PENDING = "Pending" + APPROVED = "Approved" + REJECTED = "Rejected" + DISCONNECTED = "Disconnected" + + +class ProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The provisioning state.""" + + PROVISIONING = "Provisioning" + DELETING = "Deleting" + UPDATING = "Updating" + SUCCEEDED = "Succeeded" + FAILED = "Failed" + CANCELED = "Canceled" + DELETED = "Deleted" + WARNING = "Warning" + SUSPENDING = "Suspending" + RESTORING = "Restoring" + MOVING = "Moving" + + +class PublicNetworkAccess(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Public network access for the DigitalTwinsInstance.""" + + ENABLED = "Enabled" + DISABLED = "Disabled" + + +class Reason(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Message providing the reason why the given name is invalid.""" + + INVALID = "Invalid" + ALREADY_EXISTS = "AlreadyExists" + + +class TimeSeriesDatabaseConnectionState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The provisioning state.""" + + PROVISIONING = "Provisioning" + DELETING = "Deleting" + UPDATING = "Updating" + SUCCEEDED = "Succeeded" + FAILED = "Failed" + CANCELED = "Canceled" + DELETED = "Deleted" + WARNING = "Warning" + SUSPENDING = "Suspending" + RESTORING = "Restoring" + MOVING = "Moving" + DISABLED = "Disabled" diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/models/_models_py3.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/models/_models_py3.py new file mode 100644 index 0000000000000..6e131afd8d7df --- /dev/null +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/models/_models_py3.py @@ -0,0 +1,1873 @@ +# 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. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +import datetime +from typing import Dict, List, Optional, TYPE_CHECKING, Union + +from ... import _serialization + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from .. import models as _models + + +class TimeSeriesDatabaseConnectionProperties(_serialization.Model): + """Properties of a time series database connection resource. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + AzureDataExplorerConnectionProperties + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :ivar connection_type: The type of time series connection resource. Required. + "AzureDataExplorer" + :vartype connection_type: str or ~azure.mgmt.digitaltwins.v2022_10_31.models.ConnectionType + :ivar provisioning_state: The provisioning state. Known values are: "Provisioning", "Deleting", + "Updating", "Succeeded", "Failed", "Canceled", "Deleted", "Warning", "Suspending", "Restoring", + "Moving", and "Disabled". + :vartype provisioning_state: str or + ~azure.mgmt.digitaltwins.v2022_10_31.models.TimeSeriesDatabaseConnectionState + :ivar identity: Managed identity properties for the time series database connection resource. + :vartype identity: ~azure.mgmt.digitaltwins.v2022_10_31.models.ManagedIdentityReference + """ + + _validation = { + "connection_type": {"required": True}, + "provisioning_state": {"readonly": True}, + } + + _attribute_map = { + "connection_type": {"key": "connectionType", "type": "str"}, + "provisioning_state": {"key": "provisioningState", "type": "str"}, + "identity": {"key": "identity", "type": "ManagedIdentityReference"}, + } + + _subtype_map = {"connection_type": {"AzureDataExplorer": "AzureDataExplorerConnectionProperties"}} + + def __init__(self, *, identity: Optional["_models.ManagedIdentityReference"] = None, **kwargs): + """ + :keyword identity: Managed identity properties for the time series database connection + resource. + :paramtype identity: ~azure.mgmt.digitaltwins.v2022_10_31.models.ManagedIdentityReference + """ + super().__init__(**kwargs) + self.connection_type: Optional[str] = None + self.provisioning_state = None + self.identity = identity + + +class AzureDataExplorerConnectionProperties( + TimeSeriesDatabaseConnectionProperties +): # pylint: disable=too-many-instance-attributes + """Properties of a time series database connection to Azure Data Explorer with data being sent via an EventHub. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :ivar connection_type: The type of time series connection resource. Required. + "AzureDataExplorer" + :vartype connection_type: str or ~azure.mgmt.digitaltwins.v2022_10_31.models.ConnectionType + :ivar provisioning_state: The provisioning state. Known values are: "Provisioning", "Deleting", + "Updating", "Succeeded", "Failed", "Canceled", "Deleted", "Warning", "Suspending", "Restoring", + "Moving", and "Disabled". + :vartype provisioning_state: str or + ~azure.mgmt.digitaltwins.v2022_10_31.models.TimeSeriesDatabaseConnectionState + :ivar identity: Managed identity properties for the time series database connection resource. + :vartype identity: ~azure.mgmt.digitaltwins.v2022_10_31.models.ManagedIdentityReference + :ivar adx_resource_id: The resource ID of the Azure Data Explorer cluster. Required. + :vartype adx_resource_id: str + :ivar adx_endpoint_uri: The URI of the Azure Data Explorer endpoint. Required. + :vartype adx_endpoint_uri: str + :ivar adx_database_name: The name of the Azure Data Explorer database. Required. + :vartype adx_database_name: str + :ivar adx_table_name: The name of the Azure Data Explorer table. Defaults to AdtPropertyEvents. + :vartype adx_table_name: str + :ivar event_hub_endpoint_uri: The URL of the EventHub namespace for identity-based + authentication. It must include the protocol sb://. Required. + :vartype event_hub_endpoint_uri: str + :ivar event_hub_entity_path: The EventHub name in the EventHub namespace for identity-based + authentication. Required. + :vartype event_hub_entity_path: str + :ivar event_hub_namespace_resource_id: The resource ID of the EventHub namespace. Required. + :vartype event_hub_namespace_resource_id: str + :ivar event_hub_consumer_group: The EventHub consumer group to use when ADX reads from + EventHub. Defaults to $Default. + :vartype event_hub_consumer_group: str + """ + + _validation = { + "connection_type": {"required": True}, + "provisioning_state": {"readonly": True}, + "adx_resource_id": {"required": True}, + "adx_endpoint_uri": {"required": True}, + "adx_database_name": {"required": True}, + "event_hub_endpoint_uri": {"required": True}, + "event_hub_entity_path": {"required": True}, + "event_hub_namespace_resource_id": {"required": True}, + } + + _attribute_map = { + "connection_type": {"key": "connectionType", "type": "str"}, + "provisioning_state": {"key": "provisioningState", "type": "str"}, + "identity": {"key": "identity", "type": "ManagedIdentityReference"}, + "adx_resource_id": {"key": "adxResourceId", "type": "str"}, + "adx_endpoint_uri": {"key": "adxEndpointUri", "type": "str"}, + "adx_database_name": {"key": "adxDatabaseName", "type": "str"}, + "adx_table_name": {"key": "adxTableName", "type": "str"}, + "event_hub_endpoint_uri": {"key": "eventHubEndpointUri", "type": "str"}, + "event_hub_entity_path": {"key": "eventHubEntityPath", "type": "str"}, + "event_hub_namespace_resource_id": {"key": "eventHubNamespaceResourceId", "type": "str"}, + "event_hub_consumer_group": {"key": "eventHubConsumerGroup", "type": "str"}, + } + + def __init__( + self, + *, + adx_resource_id: str, + adx_endpoint_uri: str, + adx_database_name: str, + event_hub_endpoint_uri: str, + event_hub_entity_path: str, + event_hub_namespace_resource_id: str, + identity: Optional["_models.ManagedIdentityReference"] = None, + adx_table_name: str = "AdtPropertyEvents", + event_hub_consumer_group: str = "$Default", + **kwargs + ): + """ + :keyword identity: Managed identity properties for the time series database connection + resource. + :paramtype identity: ~azure.mgmt.digitaltwins.v2022_10_31.models.ManagedIdentityReference + :keyword adx_resource_id: The resource ID of the Azure Data Explorer cluster. Required. + :paramtype adx_resource_id: str + :keyword adx_endpoint_uri: The URI of the Azure Data Explorer endpoint. Required. + :paramtype adx_endpoint_uri: str + :keyword adx_database_name: The name of the Azure Data Explorer database. Required. + :paramtype adx_database_name: str + :keyword adx_table_name: The name of the Azure Data Explorer table. Defaults to + AdtPropertyEvents. + :paramtype adx_table_name: str + :keyword event_hub_endpoint_uri: The URL of the EventHub namespace for identity-based + authentication. It must include the protocol sb://. Required. + :paramtype event_hub_endpoint_uri: str + :keyword event_hub_entity_path: The EventHub name in the EventHub namespace for identity-based + authentication. Required. + :paramtype event_hub_entity_path: str + :keyword event_hub_namespace_resource_id: The resource ID of the EventHub namespace. Required. + :paramtype event_hub_namespace_resource_id: str + :keyword event_hub_consumer_group: The EventHub consumer group to use when ADX reads from + EventHub. Defaults to $Default. + :paramtype event_hub_consumer_group: str + """ + super().__init__(identity=identity, **kwargs) + self.connection_type: str = "AzureDataExplorer" + self.adx_resource_id = adx_resource_id + self.adx_endpoint_uri = adx_endpoint_uri + self.adx_database_name = adx_database_name + self.adx_table_name = adx_table_name + self.event_hub_endpoint_uri = event_hub_endpoint_uri + self.event_hub_entity_path = event_hub_entity_path + self.event_hub_namespace_resource_id = event_hub_namespace_resource_id + self.event_hub_consumer_group = event_hub_consumer_group + + +class CheckNameRequest(_serialization.Model): + """The result returned from a database check name availability request. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :ivar name: Resource name. Required. + :vartype name: str + :ivar type: The type of resource, for instance Microsoft.DigitalTwins/digitalTwinsInstances. + Required. Default value is "Microsoft.DigitalTwins/digitalTwinsInstances". + :vartype type: str + """ + + _validation = { + "name": {"required": True}, + "type": {"required": True, "constant": True}, + } + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + } + + type = "Microsoft.DigitalTwins/digitalTwinsInstances" + + def __init__(self, *, name: str, **kwargs): + """ + :keyword name: Resource name. Required. + :paramtype name: str + """ + super().__init__(**kwargs) + self.name = name + + +class CheckNameResult(_serialization.Model): + """The result returned from a check name availability request. + + :ivar name_available: Specifies a Boolean value that indicates if the name is available. + :vartype name_available: bool + :ivar message: Message indicating an unavailable name due to a conflict, or a description of + the naming rules that are violated. + :vartype message: str + :ivar reason: Message providing the reason why the given name is invalid. Known values are: + "Invalid" and "AlreadyExists". + :vartype reason: str or ~azure.mgmt.digitaltwins.v2022_10_31.models.Reason + """ + + _attribute_map = { + "name_available": {"key": "nameAvailable", "type": "bool"}, + "message": {"key": "message", "type": "str"}, + "reason": {"key": "reason", "type": "str"}, + } + + def __init__( + self, + *, + name_available: Optional[bool] = None, + message: Optional[str] = None, + reason: Optional[Union[str, "_models.Reason"]] = None, + **kwargs + ): + """ + :keyword name_available: Specifies a Boolean value that indicates if the name is available. + :paramtype name_available: bool + :keyword message: Message indicating an unavailable name due to a conflict, or a description of + the naming rules that are violated. + :paramtype message: str + :keyword reason: Message providing the reason why the given name is invalid. Known values are: + "Invalid" and "AlreadyExists". + :paramtype reason: str or ~azure.mgmt.digitaltwins.v2022_10_31.models.Reason + """ + super().__init__(**kwargs) + self.name_available = name_available + self.message = message + self.reason = reason + + +class ConnectionProperties(_serialization.Model): + """The properties of a private endpoint connection. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar provisioning_state: The provisioning state. Known values are: "Pending", "Approved", + "Rejected", and "Disconnected". + :vartype provisioning_state: str or + ~azure.mgmt.digitaltwins.v2022_10_31.models.ConnectionPropertiesProvisioningState + :ivar private_endpoint: The private endpoint. + :vartype private_endpoint: ~azure.mgmt.digitaltwins.v2022_10_31.models.PrivateEndpoint + :ivar group_ids: The list of group ids for the private endpoint connection. + :vartype group_ids: list[str] + :ivar private_link_service_connection_state: The connection state. + :vartype private_link_service_connection_state: + ~azure.mgmt.digitaltwins.v2022_10_31.models.ConnectionPropertiesPrivateLinkServiceConnectionState + """ + + _validation = { + "provisioning_state": {"readonly": True}, + } + + _attribute_map = { + "provisioning_state": {"key": "provisioningState", "type": "str"}, + "private_endpoint": {"key": "privateEndpoint", "type": "PrivateEndpoint"}, + "group_ids": {"key": "groupIds", "type": "[str]"}, + "private_link_service_connection_state": { + "key": "privateLinkServiceConnectionState", + "type": "ConnectionPropertiesPrivateLinkServiceConnectionState", + }, + } + + def __init__( + self, + *, + private_endpoint: Optional["_models.PrivateEndpoint"] = None, + group_ids: Optional[List[str]] = None, + private_link_service_connection_state: Optional[ + "_models.ConnectionPropertiesPrivateLinkServiceConnectionState" + ] = None, + **kwargs + ): + """ + :keyword private_endpoint: The private endpoint. + :paramtype private_endpoint: ~azure.mgmt.digitaltwins.v2022_10_31.models.PrivateEndpoint + :keyword group_ids: The list of group ids for the private endpoint connection. + :paramtype group_ids: list[str] + :keyword private_link_service_connection_state: The connection state. + :paramtype private_link_service_connection_state: + ~azure.mgmt.digitaltwins.v2022_10_31.models.ConnectionPropertiesPrivateLinkServiceConnectionState + """ + super().__init__(**kwargs) + self.provisioning_state = None + self.private_endpoint = private_endpoint + self.group_ids = group_ids + self.private_link_service_connection_state = private_link_service_connection_state + + +class ConnectionState(_serialization.Model): + """The current state of a private endpoint connection. + + All required parameters must be populated in order to send to Azure. + + :ivar status: The status of a private endpoint connection. Required. Known values are: + "Pending", "Approved", "Rejected", and "Disconnected". + :vartype status: str or + ~azure.mgmt.digitaltwins.v2022_10_31.models.PrivateLinkServiceConnectionStatus + :ivar description: The description for the current state of a private endpoint connection. + Required. + :vartype description: str + :ivar actions_required: Actions required for a private endpoint connection. + :vartype actions_required: str + """ + + _validation = { + "status": {"required": True}, + "description": {"required": True}, + } + + _attribute_map = { + "status": {"key": "status", "type": "str"}, + "description": {"key": "description", "type": "str"}, + "actions_required": {"key": "actionsRequired", "type": "str"}, + } + + def __init__( + self, + *, + status: Union[str, "_models.PrivateLinkServiceConnectionStatus"], + description: str, + actions_required: Optional[str] = None, + **kwargs + ): + """ + :keyword status: The status of a private endpoint connection. Required. Known values are: + "Pending", "Approved", "Rejected", and "Disconnected". + :paramtype status: str or + ~azure.mgmt.digitaltwins.v2022_10_31.models.PrivateLinkServiceConnectionStatus + :keyword description: The description for the current state of a private endpoint connection. + Required. + :paramtype description: str + :keyword actions_required: Actions required for a private endpoint connection. + :paramtype actions_required: str + """ + super().__init__(**kwargs) + self.status = status + self.description = description + self.actions_required = actions_required + + +class ConnectionPropertiesPrivateLinkServiceConnectionState(ConnectionState): + """The connection state. + + All required parameters must be populated in order to send to Azure. + + :ivar status: The status of a private endpoint connection. Required. Known values are: + "Pending", "Approved", "Rejected", and "Disconnected". + :vartype status: str or + ~azure.mgmt.digitaltwins.v2022_10_31.models.PrivateLinkServiceConnectionStatus + :ivar description: The description for the current state of a private endpoint connection. + Required. + :vartype description: str + :ivar actions_required: Actions required for a private endpoint connection. + :vartype actions_required: str + """ + + _validation = { + "status": {"required": True}, + "description": {"required": True}, + } + + _attribute_map = { + "status": {"key": "status", "type": "str"}, + "description": {"key": "description", "type": "str"}, + "actions_required": {"key": "actionsRequired", "type": "str"}, + } + + def __init__( + self, + *, + status: Union[str, "_models.PrivateLinkServiceConnectionStatus"], + description: str, + actions_required: Optional[str] = None, + **kwargs + ): + """ + :keyword status: The status of a private endpoint connection. Required. Known values are: + "Pending", "Approved", "Rejected", and "Disconnected". + :paramtype status: str or + ~azure.mgmt.digitaltwins.v2022_10_31.models.PrivateLinkServiceConnectionStatus + :keyword description: The description for the current state of a private endpoint connection. + Required. + :paramtype description: str + :keyword actions_required: Actions required for a private endpoint connection. + :paramtype actions_required: str + """ + super().__init__(status=status, description=description, actions_required=actions_required, **kwargs) + + +class DigitalTwinsResource(_serialization.Model): + """The common properties of a DigitalTwinsInstance. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to Azure. + + :ivar id: The resource identifier. + :vartype id: str + :ivar name: The resource name. + :vartype name: str + :ivar type: The resource type. + :vartype type: str + :ivar location: The resource location. Required. + :vartype location: str + :ivar tags: The resource tags. + :vartype tags: dict[str, str] + :ivar identity: The managed identity for the DigitalTwinsInstance. + :vartype identity: ~azure.mgmt.digitaltwins.v2022_10_31.models.DigitalTwinsIdentity + :ivar system_data: Metadata pertaining to creation and last modification of the + DigitalTwinsInstance. + :vartype system_data: ~azure.mgmt.digitaltwins.v2022_10_31.models.SystemData + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True, "pattern": r"^(?!-)[A-Za-z0-9-]{3,63}(?= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request( + resource_group_name: str, resource_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints", + ) # 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", max_length=90, min_length=1 + ), + "resourceName": _SERIALIZER.url( + "resource_name", + resource_name, + "str", + max_length=63, + min_length=3, + pattern=r"^(?!-)[A-Za-z0-9-]{3,63}(? HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}", + ) # 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", max_length=90, min_length=1 + ), + "resourceName": _SERIALIZER.url( + "resource_name", + resource_name, + "str", + max_length=63, + min_length=3, + pattern=r"^(?!-)[A-Za-z0-9-]{3,63}(? HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}", + ) # 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", max_length=90, min_length=1 + ), + "resourceName": _SERIALIZER.url( + "resource_name", + resource_name, + "str", + max_length=63, + min_length=3, + pattern=r"^(?!-)[A-Za-z0-9-]{3,63}(? HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}", + ) # 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", max_length=90, min_length=1 + ), + "resourceName": _SERIALIZER.url( + "resource_name", + resource_name, + "str", + max_length=63, + min_length=3, + pattern=r"^(?!-)[A-Za-z0-9-]{3,63}(? Iterable["_models.DigitalTwinsEndpointResource"]: + """Get DigitalTwinsInstance Endpoints. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either DigitalTwinsEndpointResource or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.digitaltwins.v2022_10_31.models.DigitalTwinsEndpointResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + cls: ClsType[_models.DigitalTwinsEndpointResourceListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + resource_group_name=resource_group_name, + resource_name=resource_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("DigitalTwinsEndpointResourceListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints" + } + + @distributed_trace + def get( + self, resource_group_name: str, resource_name: str, endpoint_name: str, **kwargs: Any + ) -> _models.DigitalTwinsEndpointResource: + """Get DigitalTwinsInstances Endpoint. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param endpoint_name: Name of Endpoint Resource. Required. + :type endpoint_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: DigitalTwinsEndpointResource or the result of cls(response) + :rtype: ~azure.mgmt.digitaltwins.v2022_10_31.models.DigitalTwinsEndpointResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + cls: ClsType[_models.DigitalTwinsEndpointResource] = kwargs.pop("cls", None) + + request = build_get_request( + resource_group_name=resource_group_name, + resource_name=resource_name, + endpoint_name=endpoint_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}" + } + + def _create_or_update_initial( + self, + resource_group_name: str, + resource_name: str, + endpoint_name: str, + endpoint_description: Union[_models.DigitalTwinsEndpointResource, IO], + **kwargs: Any + ) -> _models.DigitalTwinsEndpointResource: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DigitalTwinsEndpointResource] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(endpoint_description, (IO, bytes)): + _content = endpoint_description + else: + _json = self._serialize.body(endpoint_description, "DigitalTwinsEndpointResource") + + request = build_create_or_update_request( + resource_group_name=resource_group_name, + resource_name=resource_name, + endpoint_name=endpoint_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self._create_or_update_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + _create_or_update_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}" + } + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + endpoint_name: str, + endpoint_description: _models.DigitalTwinsEndpointResource, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.DigitalTwinsEndpointResource]: + """Create or update DigitalTwinsInstance endpoint. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param endpoint_name: Name of Endpoint Resource. Required. + :type endpoint_name: str + :param endpoint_description: The DigitalTwinsInstance endpoint metadata and security metadata. + Required. + :type endpoint_description: + ~azure.mgmt.digitaltwins.v2022_10_31.models.DigitalTwinsEndpointResource + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either DigitalTwinsEndpointResource or the + result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2022_10_31.models.DigitalTwinsEndpointResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + endpoint_name: str, + endpoint_description: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.DigitalTwinsEndpointResource]: + """Create or update DigitalTwinsInstance endpoint. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param endpoint_name: Name of Endpoint Resource. Required. + :type endpoint_name: str + :param endpoint_description: The DigitalTwinsInstance endpoint metadata and security metadata. + Required. + :type endpoint_description: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either DigitalTwinsEndpointResource or the + result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2022_10_31.models.DigitalTwinsEndpointResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + endpoint_name: str, + endpoint_description: Union[_models.DigitalTwinsEndpointResource, IO], + **kwargs: Any + ) -> LROPoller[_models.DigitalTwinsEndpointResource]: + """Create or update DigitalTwinsInstance endpoint. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param endpoint_name: Name of Endpoint Resource. Required. + :type endpoint_name: str + :param endpoint_description: The DigitalTwinsInstance endpoint metadata and security metadata. + Is either a model type or a IO type. Required. + :type endpoint_description: + ~azure.mgmt.digitaltwins.v2022_10_31.models.DigitalTwinsEndpointResource or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either DigitalTwinsEndpointResource or the + result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2022_10_31.models.DigitalTwinsEndpointResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DigitalTwinsEndpointResource] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._create_or_update_initial( + resource_group_name=resource_group_name, + resource_name=resource_name, + endpoint_name=endpoint_name, + endpoint_description=endpoint_description, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + begin_create_or_update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}" + } + + def _delete_initial( + self, resource_group_name: str, resource_name: str, endpoint_name: str, **kwargs: Any + ) -> Optional[_models.DigitalTwinsEndpointResource]: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + cls: ClsType[Optional[_models.DigitalTwinsEndpointResource]] = kwargs.pop("cls", None) + + request = build_delete_request( + resource_group_name=resource_group_name, + resource_name=resource_name, + endpoint_name=endpoint_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self._delete_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) + + if response.status_code == 202: + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + _delete_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}" + } + + @distributed_trace + def begin_delete( + self, resource_group_name: str, resource_name: str, endpoint_name: str, **kwargs: Any + ) -> LROPoller[_models.DigitalTwinsEndpointResource]: + """Delete a DigitalTwinsInstance endpoint. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param endpoint_name: Name of Endpoint Resource. Required. + :type endpoint_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either DigitalTwinsEndpointResource or the + result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2022_10_31.models.DigitalTwinsEndpointResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + cls: ClsType[_models.DigitalTwinsEndpointResource] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._delete_initial( + resource_group_name=resource_group_name, + resource_name=resource_name, + endpoint_name=endpoint_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("DigitalTwinsEndpointResource", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + begin_delete.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/endpoints/{endpointName}" + } diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/operations/_digital_twins_operations.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/operations/_digital_twins_operations.py new file mode 100644 index 0000000000000..eb1eb68679fb5 --- /dev/null +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/operations/_digital_twins_operations.py @@ -0,0 +1,1274 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +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(resource_group_name: str, resource_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}", + ) # 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", max_length=90, min_length=1 + ), + "resourceName": _SERIALIZER.url( + "resource_name", + resource_name, + "str", + max_length=63, + min_length=3, + pattern=r"^(?!-)[A-Za-z0-9-]{3,63}(? HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}", + ) # 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", max_length=90, min_length=1 + ), + "resourceName": _SERIALIZER.url( + "resource_name", + resource_name, + "str", + max_length=63, + min_length=3, + pattern=r"^(?!-)[A-Za-z0-9-]{3,63}(? HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}", + ) # 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", max_length=90, min_length=1 + ), + "resourceName": _SERIALIZER.url( + "resource_name", + resource_name, + "str", + max_length=63, + min_length=3, + pattern=r"^(?!-)[A-Za-z0-9-]{3,63}(? HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}", + ) # 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", max_length=90, min_length=1 + ), + "resourceName": _SERIALIZER.url( + "resource_name", + resource_name, + "str", + max_length=63, + min_length=3, + pattern=r"^(?!-)[A-Za-z0-9-]{3,63}(? HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.DigitalTwins/digitalTwinsInstances" + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_by_resource_group_request(resource_group_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances", + ) # 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", max_length=90, min_length=1 + ), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_check_name_availability_request(location: str, subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.DigitalTwins/locations/{location}/checkNameAvailability", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "location": _SERIALIZER.url("location", location, "str", min_length=3), + } + + _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class DigitalTwinsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.digitaltwins.v2022_10_31.AzureDigitalTwinsManagementClient`'s + :attr:`digital_twins` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def get(self, resource_group_name: str, resource_name: str, **kwargs: Any) -> _models.DigitalTwinsDescription: + """Get DigitalTwinsInstances resource. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: DigitalTwinsDescription or the result of cls(response) + :rtype: ~azure.mgmt.digitaltwins.v2022_10_31.models.DigitalTwinsDescription + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + cls: ClsType[_models.DigitalTwinsDescription] = kwargs.pop("cls", None) + + request = build_get_request( + resource_group_name=resource_group_name, + resource_name=resource_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } + + def _create_or_update_initial( + self, + resource_group_name: str, + resource_name: str, + digital_twins_create: Union[_models.DigitalTwinsDescription, IO], + **kwargs: Any + ) -> _models.DigitalTwinsDescription: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DigitalTwinsDescription] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(digital_twins_create, (IO, bytes)): + _content = digital_twins_create + else: + _json = self._serialize.body(digital_twins_create, "DigitalTwinsDescription") + + request = build_create_or_update_request( + resource_group_name=resource_group_name, + resource_name=resource_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self._create_or_update_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + _create_or_update_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + digital_twins_create: _models.DigitalTwinsDescription, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.DigitalTwinsDescription]: + """Create or update the metadata of a DigitalTwinsInstance. The usual pattern to modify a property + is to retrieve the DigitalTwinsInstance and security metadata, and then combine them with the + modified values in a new body to update the DigitalTwinsInstance. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param digital_twins_create: The DigitalTwinsInstance and security metadata. Required. + :type digital_twins_create: ~azure.mgmt.digitaltwins.v2022_10_31.models.DigitalTwinsDescription + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either DigitalTwinsDescription or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2022_10_31.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + digital_twins_create: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.DigitalTwinsDescription]: + """Create or update the metadata of a DigitalTwinsInstance. The usual pattern to modify a property + is to retrieve the DigitalTwinsInstance and security metadata, and then combine them with the + modified values in a new body to update the DigitalTwinsInstance. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param digital_twins_create: The DigitalTwinsInstance and security metadata. Required. + :type digital_twins_create: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either DigitalTwinsDescription or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2022_10_31.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + digital_twins_create: Union[_models.DigitalTwinsDescription, IO], + **kwargs: Any + ) -> LROPoller[_models.DigitalTwinsDescription]: + """Create or update the metadata of a DigitalTwinsInstance. The usual pattern to modify a property + is to retrieve the DigitalTwinsInstance and security metadata, and then combine them with the + modified values in a new body to update the DigitalTwinsInstance. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param digital_twins_create: The DigitalTwinsInstance and security metadata. Is either a model + type or a IO type. Required. + :type digital_twins_create: ~azure.mgmt.digitaltwins.v2022_10_31.models.DigitalTwinsDescription + or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either DigitalTwinsDescription or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2022_10_31.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DigitalTwinsDescription] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._create_or_update_initial( + resource_group_name=resource_group_name, + resource_name=resource_name, + digital_twins_create=digital_twins_create, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + begin_create_or_update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } + + def _update_initial( + self, + resource_group_name: str, + resource_name: str, + digital_twins_patch_description: Union[_models.DigitalTwinsPatchDescription, IO], + **kwargs: Any + ) -> _models.DigitalTwinsDescription: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DigitalTwinsDescription] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(digital_twins_patch_description, (IO, bytes)): + _content = digital_twins_patch_description + else: + _json = self._serialize.body(digital_twins_patch_description, "DigitalTwinsPatchDescription") + + request = build_update_request( + resource_group_name=resource_group_name, + resource_name=resource_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self._update_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) + + if response.status_code == 202: + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + _update_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } + + @overload + def begin_update( + self, + resource_group_name: str, + resource_name: str, + digital_twins_patch_description: _models.DigitalTwinsPatchDescription, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.DigitalTwinsDescription]: + """Update metadata of DigitalTwinsInstance. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param digital_twins_patch_description: The DigitalTwinsInstance and security metadata. + Required. + :type digital_twins_patch_description: + ~azure.mgmt.digitaltwins.v2022_10_31.models.DigitalTwinsPatchDescription + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either DigitalTwinsDescription or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2022_10_31.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_update( + self, + resource_group_name: str, + resource_name: str, + digital_twins_patch_description: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.DigitalTwinsDescription]: + """Update metadata of DigitalTwinsInstance. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param digital_twins_patch_description: The DigitalTwinsInstance and security metadata. + Required. + :type digital_twins_patch_description: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either DigitalTwinsDescription or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2022_10_31.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_update( + self, + resource_group_name: str, + resource_name: str, + digital_twins_patch_description: Union[_models.DigitalTwinsPatchDescription, IO], + **kwargs: Any + ) -> LROPoller[_models.DigitalTwinsDescription]: + """Update metadata of DigitalTwinsInstance. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param digital_twins_patch_description: The DigitalTwinsInstance and security metadata. Is + either a model type or a IO type. Required. + :type digital_twins_patch_description: + ~azure.mgmt.digitaltwins.v2022_10_31.models.DigitalTwinsPatchDescription or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either DigitalTwinsDescription or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2022_10_31.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DigitalTwinsDescription] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._update_initial( + resource_group_name=resource_group_name, + resource_name=resource_name, + digital_twins_patch_description=digital_twins_patch_description, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + begin_update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } + + def _delete_initial( + self, resource_group_name: str, resource_name: str, **kwargs: Any + ) -> Optional[_models.DigitalTwinsDescription]: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + cls: ClsType[Optional[_models.DigitalTwinsDescription]] = kwargs.pop("cls", None) + + request = build_delete_request( + resource_group_name=resource_group_name, + resource_name=resource_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self._delete_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) + + if response.status_code == 202: + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + _delete_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } + + @distributed_trace + def begin_delete( + self, resource_group_name: str, resource_name: str, **kwargs: Any + ) -> LROPoller[_models.DigitalTwinsDescription]: + """Delete a DigitalTwinsInstance. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either DigitalTwinsDescription or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2022_10_31.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + cls: ClsType[_models.DigitalTwinsDescription] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._delete_initial( + resource_group_name=resource_group_name, + resource_name=resource_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("DigitalTwinsDescription", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + begin_delete.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}" + } + + @distributed_trace + def list(self, **kwargs: Any) -> Iterable["_models.DigitalTwinsDescription"]: + """Get all the DigitalTwinsInstances in a subscription. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either DigitalTwinsDescription or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.digitaltwins.v2022_10_31.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + cls: ClsType[_models.DigitalTwinsDescriptionListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("DigitalTwinsDescriptionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.DigitalTwins/digitalTwinsInstances"} + + @distributed_trace + def list_by_resource_group( + self, resource_group_name: str, **kwargs: Any + ) -> Iterable["_models.DigitalTwinsDescription"]: + """Get all the DigitalTwinsInstances in a resource group. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. 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 DigitalTwinsDescription or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.digitaltwins.v2022_10_31.models.DigitalTwinsDescription] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + cls: ClsType[_models.DigitalTwinsDescriptionListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_by_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list_by_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("DigitalTwinsDescriptionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list_by_resource_group.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances" + } + + @overload + def check_name_availability( + self, + location: str, + digital_twins_instance_check_name: _models.CheckNameRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.CheckNameResult: + """Check if a DigitalTwinsInstance name is available. + + :param location: Location of DigitalTwinsInstance. Required. + :type location: str + :param digital_twins_instance_check_name: Set the name parameter in the + DigitalTwinsInstanceCheckName structure to the name of the DigitalTwinsInstance to check. + Required. + :type digital_twins_instance_check_name: + ~azure.mgmt.digitaltwins.v2022_10_31.models.CheckNameRequest + :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: CheckNameResult or the result of cls(response) + :rtype: ~azure.mgmt.digitaltwins.v2022_10_31.models.CheckNameResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def check_name_availability( + self, + location: str, + digital_twins_instance_check_name: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.CheckNameResult: + """Check if a DigitalTwinsInstance name is available. + + :param location: Location of DigitalTwinsInstance. Required. + :type location: str + :param digital_twins_instance_check_name: Set the name parameter in the + DigitalTwinsInstanceCheckName structure to the name of the DigitalTwinsInstance to check. + Required. + :type digital_twins_instance_check_name: 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: CheckNameResult or the result of cls(response) + :rtype: ~azure.mgmt.digitaltwins.v2022_10_31.models.CheckNameResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def check_name_availability( + self, location: str, digital_twins_instance_check_name: Union[_models.CheckNameRequest, IO], **kwargs: Any + ) -> _models.CheckNameResult: + """Check if a DigitalTwinsInstance name is available. + + :param location: Location of DigitalTwinsInstance. Required. + :type location: str + :param digital_twins_instance_check_name: Set the name parameter in the + DigitalTwinsInstanceCheckName structure to the name of the DigitalTwinsInstance to check. Is + either a model type or a IO type. Required. + :type digital_twins_instance_check_name: + ~azure.mgmt.digitaltwins.v2022_10_31.models.CheckNameRequest 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: CheckNameResult or the result of cls(response) + :rtype: ~azure.mgmt.digitaltwins.v2022_10_31.models.CheckNameResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.CheckNameResult] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(digital_twins_instance_check_name, (IO, bytes)): + _content = digital_twins_instance_check_name + else: + _json = self._serialize.body(digital_twins_instance_check_name, "CheckNameRequest") + + request = build_check_name_availability_request( + location=location, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.check_name_availability.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("CheckNameResult", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + check_name_availability.metadata = { + "url": "/subscriptions/{subscriptionId}/providers/Microsoft.DigitalTwins/locations/{location}/checkNameAvailability" + } diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/operations/_operations.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/operations/_operations.py new file mode 100644 index 0000000000000..08bdabe1dc0ca --- /dev/null +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/operations/_operations.py @@ -0,0 +1,159 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.DigitalTwins/operations") + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class Operations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.digitaltwins.v2022_10_31.AzureDigitalTwinsManagementClient`'s + :attr:`operations` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, **kwargs: Any) -> Iterable["_models.Operation"]: + """Lists all of the available DigitalTwins service REST API operations. + + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either Operation or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.digitaltwins.v2022_10_31.models.Operation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("OperationListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/providers/Microsoft.DigitalTwins/operations"} diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/operations/_patch.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/operations/_patch.py new file mode 100644 index 0000000000000..f7dd32510333d --- /dev/null +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/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/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/operations/_private_endpoint_connections_operations.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/operations/_private_endpoint_connections_operations.py new file mode 100644 index 0000000000000..b9c8abe922eb1 --- /dev/null +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/operations/_private_endpoint_connections_operations.py @@ -0,0 +1,737 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, cast, 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.polling import LROPoller, NoPolling, PollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request( + resource_group_name: str, resource_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "resourceName": _SERIALIZER.url( + "resource_name", + resource_name, + "str", + max_length=63, + min_length=3, + pattern=r"^(?!-)[A-Za-z0-9-]{3,63}(? HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "resourceName": _SERIALIZER.url( + "resource_name", + resource_name, + "str", + max_length=63, + min_length=3, + pattern=r"^(?!-)[A-Za-z0-9-]{3,63}(? HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "resourceName": _SERIALIZER.url( + "resource_name", + resource_name, + "str", + max_length=63, + min_length=3, + pattern=r"^(?!-)[A-Za-z0-9-]{3,63}(? HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "resourceName": _SERIALIZER.url( + "resource_name", + resource_name, + "str", + max_length=63, + min_length=3, + pattern=r"^(?!-)[A-Za-z0-9-]{3,63}(? _models.PrivateEndpointConnectionsResponse: + """List private endpoint connection properties. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PrivateEndpointConnectionsResponse or the result of cls(response) + :rtype: ~azure.mgmt.digitaltwins.v2022_10_31.models.PrivateEndpointConnectionsResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + cls: ClsType[_models.PrivateEndpointConnectionsResponse] = kwargs.pop("cls", None) + + request = build_list_request( + resource_group_name=resource_group_name, + resource_name=resource_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PrivateEndpointConnectionsResponse", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + list.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections" + } + + @distributed_trace + def get( + self, resource_group_name: str, resource_name: str, private_endpoint_connection_name: str, **kwargs: Any + ) -> _models.PrivateEndpointConnection: + """Get private endpoint connection properties for the given private endpoint. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param private_endpoint_connection_name: The name of the private endpoint connection. Required. + :type private_endpoint_connection_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: PrivateEndpointConnection or the result of cls(response) + :rtype: ~azure.mgmt.digitaltwins.v2022_10_31.models.PrivateEndpointConnection + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + cls: ClsType[_models.PrivateEndpointConnection] = kwargs.pop("cls", None) + + request = build_get_request( + resource_group_name=resource_group_name, + resource_name=resource_name, + private_endpoint_connection_name=private_endpoint_connection_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}" + } + + def _delete_initial( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, resource_name: str, private_endpoint_connection_name: str, **kwargs: Any + ) -> None: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + cls: ClsType[None] = kwargs.pop("cls", None) + + request = build_delete_request( + resource_group_name=resource_group_name, + resource_name=resource_name, + private_endpoint_connection_name=private_endpoint_connection_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self._delete_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) + + _delete_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}" + } + + @distributed_trace + def begin_delete( + self, resource_group_name: str, resource_name: str, private_endpoint_connection_name: str, **kwargs: Any + ) -> LROPoller[None]: + """Delete private endpoint connection with the specified name. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param private_endpoint_connection_name: The name of the private endpoint connection. Required. + :type private_endpoint_connection_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._delete_initial( # type: ignore + resource_group_name=resource_group_name, + resource_name=resource_name, + private_endpoint_connection_name=private_endpoint_connection_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + begin_delete.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}" + } + + def _create_or_update_initial( + self, + resource_group_name: str, + resource_name: str, + private_endpoint_connection_name: str, + private_endpoint_connection: Union[_models.PrivateEndpointConnection, IO], + **kwargs: Any + ) -> _models.PrivateEndpointConnection: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PrivateEndpointConnection] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(private_endpoint_connection, (IO, bytes)): + _content = private_endpoint_connection + else: + _json = self._serialize.body(private_endpoint_connection, "PrivateEndpointConnection") + + request = build_create_or_update_request( + resource_group_name=resource_group_name, + resource_name=resource_name, + private_endpoint_connection_name=private_endpoint_connection_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self._create_or_update_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) + + if response.status_code == 202: + deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + _create_or_update_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}" + } + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + private_endpoint_connection_name: str, + private_endpoint_connection: _models.PrivateEndpointConnection, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.PrivateEndpointConnection]: + """Update the status of a private endpoint connection with the given name. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param private_endpoint_connection_name: The name of the private endpoint connection. Required. + :type private_endpoint_connection_name: str + :param private_endpoint_connection: The private endpoint connection with updated properties. + Required. + :type private_endpoint_connection: + ~azure.mgmt.digitaltwins.v2022_10_31.models.PrivateEndpointConnection + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either PrivateEndpointConnection or the result + of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2022_10_31.models.PrivateEndpointConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + private_endpoint_connection_name: str, + private_endpoint_connection: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.PrivateEndpointConnection]: + """Update the status of a private endpoint connection with the given name. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param private_endpoint_connection_name: The name of the private endpoint connection. Required. + :type private_endpoint_connection_name: str + :param private_endpoint_connection: The private endpoint connection with updated properties. + Required. + :type private_endpoint_connection: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either PrivateEndpointConnection or the result + of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2022_10_31.models.PrivateEndpointConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + private_endpoint_connection_name: str, + private_endpoint_connection: Union[_models.PrivateEndpointConnection, IO], + **kwargs: Any + ) -> LROPoller[_models.PrivateEndpointConnection]: + """Update the status of a private endpoint connection with the given name. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param private_endpoint_connection_name: The name of the private endpoint connection. Required. + :type private_endpoint_connection_name: str + :param private_endpoint_connection: The private endpoint connection with updated properties. Is + either a model type or a IO type. Required. + :type private_endpoint_connection: + ~azure.mgmt.digitaltwins.v2022_10_31.models.PrivateEndpointConnection or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either PrivateEndpointConnection or the result + of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2022_10_31.models.PrivateEndpointConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PrivateEndpointConnection] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._create_or_update_initial( + resource_group_name=resource_group_name, + resource_name=resource_name, + private_endpoint_connection_name=private_endpoint_connection_name, + private_endpoint_connection=private_endpoint_connection, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + begin_create_or_update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateEndpointConnections/{privateEndpointConnectionName}" + } diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/operations/_private_link_resources_operations.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/operations/_private_link_resources_operations.py new file mode 100644 index 0000000000000..351bab137dcc6 --- /dev/null +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/operations/_private_link_resources_operations.py @@ -0,0 +1,269 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, Optional, TypeVar + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request( + resource_group_name: str, resource_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateLinkResources", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "resourceName": _SERIALIZER.url( + "resource_name", + resource_name, + "str", + max_length=63, + min_length=3, + pattern=r"^(?!-)[A-Za-z0-9-]{3,63}(? HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateLinkResources/{resourceId}", + ) # 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", max_length=90, min_length=1 + ), + "resourceName": _SERIALIZER.url( + "resource_name", + resource_name, + "str", + max_length=63, + min_length=3, + pattern=r"^(?!-)[A-Za-z0-9-]{3,63}(? _models.GroupIdInformationResponse: + """List private link resources for given Digital Twin. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: GroupIdInformationResponse or the result of cls(response) + :rtype: ~azure.mgmt.digitaltwins.v2022_10_31.models.GroupIdInformationResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + cls: ClsType[_models.GroupIdInformationResponse] = kwargs.pop("cls", None) + + request = build_list_request( + resource_group_name=resource_group_name, + resource_name=resource_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("GroupIdInformationResponse", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + list.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateLinkResources" + } + + @distributed_trace + def get( + self, resource_group_name: str, resource_name: str, resource_id: str, **kwargs: Any + ) -> _models.GroupIdInformation: + """Get the specified private link resource for the given Digital Twin. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param resource_id: The name of the private link resource. Required. + :type resource_id: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: GroupIdInformation or the result of cls(response) + :rtype: ~azure.mgmt.digitaltwins.v2022_10_31.models.GroupIdInformation + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + cls: ClsType[_models.GroupIdInformation] = kwargs.pop("cls", None) + + request = build_get_request( + resource_group_name=resource_group_name, + resource_name=resource_name, + resource_id=resource_id, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("GroupIdInformation", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/privateLinkResources/{resourceId}" + } diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/operations/_time_series_database_connections_operations.py b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/operations/_time_series_database_connections_operations.py new file mode 100644 index 0000000000000..02182609a0dbb --- /dev/null +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/operations/_time_series_database_connections_operations.py @@ -0,0 +1,796 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import sys +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat +from azure.mgmt.core.polling.arm_polling import ARMPolling + +from .. import models as _models +from ..._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +if sys.version_info >= (3, 8): + from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +else: + from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request( + resource_group_name: str, resource_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections", + ) # 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", max_length=90, min_length=1 + ), + "resourceName": _SERIALIZER.url( + "resource_name", + resource_name, + "str", + max_length=63, + min_length=3, + pattern=r"^(?!-)[A-Za-z0-9-]{3,63}(? HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections/{timeSeriesDatabaseConnectionName}", + ) # 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", max_length=90, min_length=1 + ), + "resourceName": _SERIALIZER.url( + "resource_name", + resource_name, + "str", + max_length=63, + min_length=3, + pattern=r"^(?!-)[A-Za-z0-9-]{3,63}(? HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections/{timeSeriesDatabaseConnectionName}", + ) # 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", max_length=90, min_length=1 + ), + "resourceName": _SERIALIZER.url( + "resource_name", + resource_name, + "str", + max_length=63, + min_length=3, + pattern=r"^(?!-)[A-Za-z0-9-]{3,63}(? HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections/{timeSeriesDatabaseConnectionName}", + ) # 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", max_length=90, min_length=1 + ), + "resourceName": _SERIALIZER.url( + "resource_name", + resource_name, + "str", + max_length=63, + min_length=3, + pattern=r"^(?!-)[A-Za-z0-9-]{3,63}(? Iterable["_models.TimeSeriesDatabaseConnection"]: + """Get all existing time series database connections for this DigitalTwins instance. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either TimeSeriesDatabaseConnection or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.digitaltwins.v2022_10_31.models.TimeSeriesDatabaseConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + cls: ClsType[_models.TimeSeriesDatabaseConnectionListResult] = kwargs.pop("cls", None) + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + request = build_list_request( + resource_group_name=resource_group_name, + resource_name=resource_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.list.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("TimeSeriesDatabaseConnectionListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + list.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections" + } + + @distributed_trace + def get( + self, resource_group_name: str, resource_name: str, time_series_database_connection_name: str, **kwargs: Any + ) -> _models.TimeSeriesDatabaseConnection: + """Get the description of an existing time series database connection. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param time_series_database_connection_name: Name of time series database connection. Required. + :type time_series_database_connection_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: TimeSeriesDatabaseConnection or the result of cls(response) + :rtype: ~azure.mgmt.digitaltwins.v2022_10_31.models.TimeSeriesDatabaseConnection + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + cls: ClsType[_models.TimeSeriesDatabaseConnection] = kwargs.pop("cls", None) + + request = build_get_request( + resource_group_name=resource_group_name, + resource_name=resource_name, + time_series_database_connection_name=time_series_database_connection_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("TimeSeriesDatabaseConnection", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + get.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections/{timeSeriesDatabaseConnectionName}" + } + + def _create_or_update_initial( + self, + resource_group_name: str, + resource_name: str, + time_series_database_connection_name: str, + time_series_database_connection_description: Union[_models.TimeSeriesDatabaseConnection, IO], + **kwargs: Any + ) -> _models.TimeSeriesDatabaseConnection: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.TimeSeriesDatabaseConnection] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(time_series_database_connection_description, (IO, bytes)): + _content = time_series_database_connection_description + else: + _json = self._serialize.body(time_series_database_connection_description, "TimeSeriesDatabaseConnection") + + request = build_create_or_update_request( + resource_group_name=resource_group_name, + resource_name=resource_name, + time_series_database_connection_name=time_series_database_connection_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self._create_or_update_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if response.status_code == 200: + deserialized = self._deserialize("TimeSeriesDatabaseConnection", pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize("TimeSeriesDatabaseConnection", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + _create_or_update_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections/{timeSeriesDatabaseConnectionName}" + } + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + time_series_database_connection_name: str, + time_series_database_connection_description: _models.TimeSeriesDatabaseConnection, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.TimeSeriesDatabaseConnection]: + """Create or update a time series database connection. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param time_series_database_connection_name: Name of time series database connection. Required. + :type time_series_database_connection_name: str + :param time_series_database_connection_description: The time series database connection + description. Required. + :type time_series_database_connection_description: + ~azure.mgmt.digitaltwins.v2022_10_31.models.TimeSeriesDatabaseConnection + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either TimeSeriesDatabaseConnection or the + result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2022_10_31.models.TimeSeriesDatabaseConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + time_series_database_connection_name: str, + time_series_database_connection_description: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.TimeSeriesDatabaseConnection]: + """Create or update a time series database connection. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param time_series_database_connection_name: Name of time series database connection. Required. + :type time_series_database_connection_name: str + :param time_series_database_connection_description: The time series database connection + description. Required. + :type time_series_database_connection_description: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either TimeSeriesDatabaseConnection or the + result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2022_10_31.models.TimeSeriesDatabaseConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_or_update( + self, + resource_group_name: str, + resource_name: str, + time_series_database_connection_name: str, + time_series_database_connection_description: Union[_models.TimeSeriesDatabaseConnection, IO], + **kwargs: Any + ) -> LROPoller[_models.TimeSeriesDatabaseConnection]: + """Create or update a time series database connection. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param time_series_database_connection_name: Name of time series database connection. Required. + :type time_series_database_connection_name: str + :param time_series_database_connection_description: The time series database connection + description. Is either a model type or a IO type. Required. + :type time_series_database_connection_description: + ~azure.mgmt.digitaltwins.v2022_10_31.models.TimeSeriesDatabaseConnection or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either TimeSeriesDatabaseConnection or the + result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2022_10_31.models.TimeSeriesDatabaseConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.TimeSeriesDatabaseConnection] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._create_or_update_initial( + resource_group_name=resource_group_name, + resource_name=resource_name, + time_series_database_connection_name=time_series_database_connection_name, + time_series_database_connection_description=time_series_database_connection_description, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("TimeSeriesDatabaseConnection", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + begin_create_or_update.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections/{timeSeriesDatabaseConnectionName}" + } + + def _delete_initial( + self, resource_group_name: str, resource_name: str, time_series_database_connection_name: str, **kwargs: Any + ) -> Optional[_models.TimeSeriesDatabaseConnection]: + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + cls: ClsType[Optional[_models.TimeSeriesDatabaseConnection]] = kwargs.pop("cls", None) + + request = build_delete_request( + resource_group_name=resource_group_name, + resource_name=resource_name, + time_series_database_connection_name=time_series_database_connection_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self._delete_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) + + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + request, stream=False, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize("TimeSeriesDatabaseConnection", pipeline_response) + + if response.status_code == 202: + deserialized = self._deserialize("TimeSeriesDatabaseConnection", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + _delete_initial.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections/{timeSeriesDatabaseConnectionName}" + } + + @distributed_trace + def begin_delete( + self, resource_group_name: str, resource_name: str, time_series_database_connection_name: str, **kwargs: Any + ) -> LROPoller[_models.TimeSeriesDatabaseConnection]: + """Delete a time series database connection. + + :param resource_group_name: The name of the resource group that contains the + DigitalTwinsInstance. Required. + :type resource_group_name: str + :param resource_name: The name of the DigitalTwinsInstance. Required. + :type resource_name: str + :param time_series_database_connection_name: Name of time series database connection. Required. + :type time_series_database_connection_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either TimeSeriesDatabaseConnection or the + result of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.digitaltwins.v2022_10_31.models.TimeSeriesDatabaseConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: Literal["2022-10-31"] = kwargs.pop("api_version", _params.pop("api-version", "2022-10-31")) + cls: ClsType[_models.TimeSeriesDatabaseConnection] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._delete_initial( + resource_group_name=resource_group_name, + resource_name=resource_name, + time_series_database_connection_name=time_series_database_connection_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("TimeSeriesDatabaseConnection", pipeline_response) + if cls: + return cls(pipeline_response, deserialized, {}) + return deserialized + + if polling is True: + polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller.from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + begin_delete.metadata = { + "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DigitalTwins/digitalTwinsInstances/{resourceName}/timeSeriesDatabaseConnections/{timeSeriesDatabaseConnectionName}" + } diff --git a/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/py.typed b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/py.typed new file mode 100644 index 0000000000000..e5aff4f83af86 --- /dev/null +++ b/sdk/digitaltwins/azure-mgmt-digitaltwins/azure/mgmt/digitaltwins/v2022_10_31/py.typed @@ -0,0 +1 @@ +# Marker file for PEP 561. \ No newline at end of file