diff --git a/sdk/relay/azure-mgmt-relay/CHANGELOG.md b/sdk/relay/azure-mgmt-relay/CHANGELOG.md index b33074527be0..24ca0389d026 100644 --- a/sdk/relay/azure-mgmt-relay/CHANGELOG.md +++ b/sdk/relay/azure-mgmt-relay/CHANGELOG.md @@ -1,5 +1,11 @@ # Release History +## 1.1.1 (2026-05-09) + +### Other Changes + + - Regenerated with latest code generator tool + ## 2.0.0b1 (2022-11-08) ### Features Added diff --git a/sdk/relay/azure-mgmt-relay/MANIFEST.in b/sdk/relay/azure-mgmt-relay/MANIFEST.in index 963ad481db71..6f4e7354b049 100644 --- a/sdk/relay/azure-mgmt-relay/MANIFEST.in +++ b/sdk/relay/azure-mgmt-relay/MANIFEST.in @@ -1,8 +1,7 @@ -include _meta.json -recursive-include tests *.py *.json -recursive-include samples *.py *.md include *.md -include azure/__init__.py -include azure/mgmt/__init__.py include LICENSE include azure/mgmt/relay/py.typed +recursive-include tests *.py +recursive-include samples *.py *.md +include azure/__init__.py +include azure/mgmt/__init__.py diff --git a/sdk/relay/azure-mgmt-relay/README.md b/sdk/relay/azure-mgmt-relay/README.md index bfea97d5b392..5b0223efdacc 100644 --- a/sdk/relay/azure-mgmt-relay/README.md +++ b/sdk/relay/azure-mgmt-relay/README.md @@ -1,28 +1,61 @@ # Microsoft Azure SDK for Python This is the Microsoft Azure Relay Client Library. -This package has been tested with Python 3.7+. +This package has been tested with Python 3.10+. For a more complete view of Azure libraries, see the [azure sdk python release](https://aka.ms/azsdk/python/all). ## _Disclaimer_ _Azure SDK Python packages support for Python 2.7 has ended 01 January 2022. For more information and questions, please refer to https://github.com/Azure/azure-sdk-for-python/issues/20691_ -# Usage +## Getting started +### Prerequisites -To learn how to use this package, see the [quickstart guide](https://aka.ms/azsdk/python/mgmt) - -For docs and references, see [Python SDK References](https://docs.microsoft.com/python/api/overview/azure/relay) -Code samples for this package can be found at [Relay](https://docs.microsoft.com/samples/browse/?languages=python&term=Getting%20started%20-%20Managing&terms=Getting%20started%20-%20Managing) on docs.microsoft.com. -Additional code samples for different Azure services are available at [Samples Repo](https://github.com/Azure-Samples/azure-samples-python-management/tree/main/samples/relay) +- Python 3.10+ is required to use this package. +- [Azure subscription](https://azure.microsoft.com/free/) +### Install the package -# Provide Feedback +```bash +pip install azure-mgmt-relay +pip install azure-identity +``` -If you encounter any bugs or have suggestions, please file an issue in the -[Issues](https://github.com/Azure/azure-sdk-for-python/issues) -section of the project. +### Authentication + +By default, [Azure Active Directory](https://aka.ms/awps/aad) token authentication depends on correct configuration of the following environment variables. + +- `AZURE_CLIENT_ID` for Azure client ID. +- `AZURE_TENANT_ID` for Azure tenant ID. +- `AZURE_CLIENT_SECRET` for Azure client secret. + +In addition, Azure subscription ID can be configured via environment variable `AZURE_SUBSCRIPTION_ID`. + +With above configuration, client can be authenticated by following code: + +```python +from azure.identity import DefaultAzureCredential +from azure.mgmt.relay import RelayAPI +import os +sub_id = os.getenv("AZURE_SUBSCRIPTION_ID") +client = RelayAPI(credential=DefaultAzureCredential(), subscription_id=sub_id) +``` +## Examples +Code samples for this package can be found at: +- [Search Relay](https://docs.microsoft.com/samples/browse/?languages=python&term=Getting%20started%20-%20Managing&terms=Getting%20started%20-%20Managing) on docs.microsoft.com +- [Azure Python Mgmt SDK Samples Repo](https://aka.ms/azsdk/python/mgmt/samples) + + +## Troubleshooting + +## Next steps + +## Provide Feedback + +If you encounter any bugs or have suggestions, please file an issue in the +[Issues](https://github.com/Azure/azure-sdk-for-python/issues) +section of the project. diff --git a/sdk/relay/azure-mgmt-relay/_meta.json b/sdk/relay/azure-mgmt-relay/_meta.json deleted file mode 100644 index 3a5641673be5..000000000000 --- a/sdk/relay/azure-mgmt-relay/_meta.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "commit": "51db80e40c32f4bf4c57169476d81d36fb8c81d8", - "repository_url": "https://github.com/Azure/azure-rest-api-specs", - "autorest": "3.9.2", - "use": [ - "@autorest/python@6.2.1", - "@autorest/modelerfour@4.24.3" - ], - "autorest_command": "autorest specification/relay/resource-manager/readme.md --generate-sample=True --include-x-ms-examples-original-file=True --python --python-sdks-folder=/home/vsts/work/1/azure-sdk-for-python/sdk --use=@autorest/python@6.2.1 --use=@autorest/modelerfour@4.24.3 --version=3.9.2 --version-tolerant=False", - "readme": "specification/relay/resource-manager/readme.md" -} \ No newline at end of file diff --git a/sdk/relay/azure-mgmt-relay/_metadata.json b/sdk/relay/azure-mgmt-relay/_metadata.json new file mode 100644 index 000000000000..6cb1225f1ee8 --- /dev/null +++ b/sdk/relay/azure-mgmt-relay/_metadata.json @@ -0,0 +1,11 @@ +{ + "commit": "cbafdff192ed6ae5bad220cf0288180b33529c6f", + "repository_url": "https://github.com/Azure/azure-rest-api-specs", + "autorest": "3.10.2", + "use": [ + "@autorest/python@6.50.0", + "@autorest/modelerfour@4.27.0" + ], + "autorest_command": "autorest specification/relay/resource-manager/Microsoft.Relay/Relay/readme.md --generate-sample=True --generate-test=True --include-x-ms-examples-original-file=True --package-mode=azure-mgmt --python --python-sdks-folder=/home/codespace/workspace/sdk --tag=package-2017-04 --use=@autorest/python@6.50.0 --use=@autorest/modelerfour@4.27.0 --version=3.10.2 --version-tolerant=False", + "readme": "specification/relay/resource-manager/Microsoft.Relay/Relay/readme.md" +} \ No newline at end of file diff --git a/sdk/relay/azure-mgmt-relay/apiview-properties.json b/sdk/relay/azure-mgmt-relay/apiview-properties.json new file mode 100644 index 000000000000..65a2513950f5 --- /dev/null +++ b/sdk/relay/azure-mgmt-relay/apiview-properties.json @@ -0,0 +1,99 @@ +{ + "CrossLanguagePackageId": null, + "CrossLanguageDefinitionId": { + "azure.mgmt.relay.models.AccessKeys": null, + "azure.mgmt.relay.models.Resource": null, + "azure.mgmt.relay.models.AuthorizationRule": null, + "azure.mgmt.relay.models.AuthorizationRuleListResult": null, + "azure.mgmt.relay.models.CheckNameAvailability": null, + "azure.mgmt.relay.models.CheckNameAvailabilityResult": null, + "azure.mgmt.relay.models.ErrorResponse": null, + "azure.mgmt.relay.models.HybridConnection": null, + "azure.mgmt.relay.models.HybridConnectionListResult": null, + "azure.mgmt.relay.models.Operation": null, + "azure.mgmt.relay.models.OperationDisplay": null, + "azure.mgmt.relay.models.OperationListResult": null, + "azure.mgmt.relay.models.RegenerateAccessKeyParameters": null, + "azure.mgmt.relay.models.TrackedResource": null, + "azure.mgmt.relay.models.RelayNamespace": null, + "azure.mgmt.relay.models.RelayNamespaceListResult": null, + "azure.mgmt.relay.models.ResourceNamespacePatch": null, + "azure.mgmt.relay.models.RelayUpdateParameters": null, + "azure.mgmt.relay.models.Sku": null, + "azure.mgmt.relay.models.WcfRelay": null, + "azure.mgmt.relay.models.WcfRelaysListResult": null, + "azure.mgmt.relay.models.ProvisioningStateEnum": null, + "azure.mgmt.relay.models.AccessRights": null, + "azure.mgmt.relay.models.Relaytype": null, + "azure.mgmt.relay.models.UnavailableReason": null, + "azure.mgmt.relay.models.KeyType": null, + "azure.mgmt.relay.operations.Operations.list": null, + "azure.mgmt.relay.aio.operations.Operations.list": null, + "azure.mgmt.relay.operations.NamespacesOperations.check_name_availability": null, + "azure.mgmt.relay.aio.operations.NamespacesOperations.check_name_availability": null, + "azure.mgmt.relay.operations.NamespacesOperations.list": null, + "azure.mgmt.relay.aio.operations.NamespacesOperations.list": null, + "azure.mgmt.relay.operations.NamespacesOperations.list_by_resource_group": null, + "azure.mgmt.relay.aio.operations.NamespacesOperations.list_by_resource_group": null, + "azure.mgmt.relay.operations.NamespacesOperations.begin_create_or_update": null, + "azure.mgmt.relay.aio.operations.NamespacesOperations.begin_create_or_update": null, + "azure.mgmt.relay.operations.NamespacesOperations.begin_delete": null, + "azure.mgmt.relay.aio.operations.NamespacesOperations.begin_delete": null, + "azure.mgmt.relay.operations.NamespacesOperations.get": null, + "azure.mgmt.relay.aio.operations.NamespacesOperations.get": null, + "azure.mgmt.relay.operations.NamespacesOperations.update": null, + "azure.mgmt.relay.aio.operations.NamespacesOperations.update": null, + "azure.mgmt.relay.operations.NamespacesOperations.list_authorization_rules": null, + "azure.mgmt.relay.aio.operations.NamespacesOperations.list_authorization_rules": null, + "azure.mgmt.relay.operations.NamespacesOperations.create_or_update_authorization_rule": null, + "azure.mgmt.relay.aio.operations.NamespacesOperations.create_or_update_authorization_rule": null, + "azure.mgmt.relay.operations.NamespacesOperations.delete_authorization_rule": null, + "azure.mgmt.relay.aio.operations.NamespacesOperations.delete_authorization_rule": null, + "azure.mgmt.relay.operations.NamespacesOperations.get_authorization_rule": null, + "azure.mgmt.relay.aio.operations.NamespacesOperations.get_authorization_rule": null, + "azure.mgmt.relay.operations.NamespacesOperations.list_keys": null, + "azure.mgmt.relay.aio.operations.NamespacesOperations.list_keys": null, + "azure.mgmt.relay.operations.NamespacesOperations.regenerate_keys": null, + "azure.mgmt.relay.aio.operations.NamespacesOperations.regenerate_keys": null, + "azure.mgmt.relay.operations.HybridConnectionsOperations.list_by_namespace": null, + "azure.mgmt.relay.aio.operations.HybridConnectionsOperations.list_by_namespace": null, + "azure.mgmt.relay.operations.HybridConnectionsOperations.create_or_update": null, + "azure.mgmt.relay.aio.operations.HybridConnectionsOperations.create_or_update": null, + "azure.mgmt.relay.operations.HybridConnectionsOperations.delete": null, + "azure.mgmt.relay.aio.operations.HybridConnectionsOperations.delete": null, + "azure.mgmt.relay.operations.HybridConnectionsOperations.get": null, + "azure.mgmt.relay.aio.operations.HybridConnectionsOperations.get": null, + "azure.mgmt.relay.operations.HybridConnectionsOperations.list_authorization_rules": null, + "azure.mgmt.relay.aio.operations.HybridConnectionsOperations.list_authorization_rules": null, + "azure.mgmt.relay.operations.HybridConnectionsOperations.create_or_update_authorization_rule": null, + "azure.mgmt.relay.aio.operations.HybridConnectionsOperations.create_or_update_authorization_rule": null, + "azure.mgmt.relay.operations.HybridConnectionsOperations.delete_authorization_rule": null, + "azure.mgmt.relay.aio.operations.HybridConnectionsOperations.delete_authorization_rule": null, + "azure.mgmt.relay.operations.HybridConnectionsOperations.get_authorization_rule": null, + "azure.mgmt.relay.aio.operations.HybridConnectionsOperations.get_authorization_rule": null, + "azure.mgmt.relay.operations.HybridConnectionsOperations.list_keys": null, + "azure.mgmt.relay.aio.operations.HybridConnectionsOperations.list_keys": null, + "azure.mgmt.relay.operations.HybridConnectionsOperations.regenerate_keys": null, + "azure.mgmt.relay.aio.operations.HybridConnectionsOperations.regenerate_keys": null, + "azure.mgmt.relay.operations.WCFRelaysOperations.list_by_namespace": null, + "azure.mgmt.relay.aio.operations.WCFRelaysOperations.list_by_namespace": null, + "azure.mgmt.relay.operations.WCFRelaysOperations.create_or_update": null, + "azure.mgmt.relay.aio.operations.WCFRelaysOperations.create_or_update": null, + "azure.mgmt.relay.operations.WCFRelaysOperations.delete": null, + "azure.mgmt.relay.aio.operations.WCFRelaysOperations.delete": null, + "azure.mgmt.relay.operations.WCFRelaysOperations.get": null, + "azure.mgmt.relay.aio.operations.WCFRelaysOperations.get": null, + "azure.mgmt.relay.operations.WCFRelaysOperations.list_authorization_rules": null, + "azure.mgmt.relay.aio.operations.WCFRelaysOperations.list_authorization_rules": null, + "azure.mgmt.relay.operations.WCFRelaysOperations.create_or_update_authorization_rule": null, + "azure.mgmt.relay.aio.operations.WCFRelaysOperations.create_or_update_authorization_rule": null, + "azure.mgmt.relay.operations.WCFRelaysOperations.delete_authorization_rule": null, + "azure.mgmt.relay.aio.operations.WCFRelaysOperations.delete_authorization_rule": null, + "azure.mgmt.relay.operations.WCFRelaysOperations.get_authorization_rule": null, + "azure.mgmt.relay.aio.operations.WCFRelaysOperations.get_authorization_rule": null, + "azure.mgmt.relay.operations.WCFRelaysOperations.list_keys": null, + "azure.mgmt.relay.aio.operations.WCFRelaysOperations.list_keys": null, + "azure.mgmt.relay.operations.WCFRelaysOperations.regenerate_keys": null, + "azure.mgmt.relay.aio.operations.WCFRelaysOperations.regenerate_keys": null + } +} \ No newline at end of file diff --git a/sdk/relay/azure-mgmt-relay/azure/__init__.py b/sdk/relay/azure-mgmt-relay/azure/__init__.py index 8db66d3d0f0f..d55ccad1f573 100644 --- a/sdk/relay/azure-mgmt-relay/azure/__init__.py +++ b/sdk/relay/azure-mgmt-relay/azure/__init__.py @@ -1 +1 @@ -__path__ = __import__("pkgutil").extend_path(__path__, __name__) +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/sdk/relay/azure-mgmt-relay/azure/mgmt/__init__.py b/sdk/relay/azure-mgmt-relay/azure/mgmt/__init__.py index 8db66d3d0f0f..d55ccad1f573 100644 --- a/sdk/relay/azure-mgmt-relay/azure/mgmt/__init__.py +++ b/sdk/relay/azure-mgmt-relay/azure/mgmt/__init__.py @@ -1 +1 @@ -__path__ = __import__("pkgutil").extend_path(__path__, __name__) +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/__init__.py b/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/__init__.py index 2a2a2fb08337..69e8117afe63 100644 --- a/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/__init__.py +++ b/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/__init__.py @@ -5,15 +5,21 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._relay_api import RelayAPI +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._relay_api import RelayAPI # type: ignore from ._version import VERSION __version__ = VERSION try: from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import + from ._patch import * except ImportError: _patch_all = [] from ._patch import patch_sdk as _patch_sdk @@ -21,6 +27,6 @@ __all__ = [ "RelayAPI", ] -__all__.extend([p for p in _patch_all if p not in __all__]) +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/_configuration.py b/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/_configuration.py index 1d4c0556b285..93bd67128ff3 100644 --- a/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/_configuration.py +++ b/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/_configuration.py @@ -6,26 +6,19 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import sys -from typing import Any, TYPE_CHECKING +from typing import Any, Optional, 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 import AzureClouds from azure.core.credentials import TokenCredential -class RelayAPIConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class RelayAPIConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for RelayAPI. Note that all parameters used to create this instance are saved as instance @@ -36,14 +29,22 @@ class RelayAPIConfiguration(Configuration): # pylint: disable=too-many-instance :param subscription_id: Subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. Required. :type subscription_id: str - :keyword api_version: Api Version. Default value is "2021-11-01". Note that overriding this + :param cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is + None. + :type cloud_setting: ~azure.core.AzureClouds + :keyword api_version: Api Version. Default value is "2017-04-01". Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str """ - def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: - super(RelayAPIConfiguration, self).__init__(**kwargs) - api_version = kwargs.pop("api_version", "2021-11-01") # type: Literal["2021-11-01"] + def __init__( + self, + credential: "TokenCredential", + subscription_id: str, + cloud_setting: Optional["AzureClouds"] = None, + **kwargs: Any + ) -> None: + api_version: str = kwargs.pop("api_version", "2017-04-01") if credential is None: raise ValueError("Parameter 'credential' must not be None.") @@ -52,23 +53,22 @@ def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs self.credential = credential self.subscription_id = subscription_id + self.cloud_setting = cloud_setting self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-relay/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) - def _configure( - self, **kwargs # type: Any - ): - # type: (...) -> None + 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.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: self.authentication_policy = ARMChallengeAuthenticationPolicy( diff --git a/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/_relay_api.py b/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/_relay_api.py index 88a51614e306..c14ed1a1328b 100644 --- a/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/_relay_api.py +++ b/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/_relay_api.py @@ -7,52 +7,48 @@ # -------------------------------------------------------------------------- from copy import deepcopy -from typing import Any, TYPE_CHECKING +from typing import Any, Optional, TYPE_CHECKING, cast +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import HttpRequest, HttpResponse +from azure.core.settings import settings from azure.mgmt.core import ARMPipelineClient +from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy +from azure.mgmt.core.tools import get_arm_endpoints -from . import models +from . import models as _models from ._configuration import RelayAPIConfiguration -from ._serialization import Deserializer, Serializer -from .operations import ( - HybridConnectionsOperations, - NamespacesOperations, - Operations, - PrivateEndpointConnectionsOperations, - PrivateLinkResourcesOperations, - WCFRelaysOperations, -) +from ._utils.serialization import Deserializer, Serializer +from .operations import HybridConnectionsOperations, NamespacesOperations, Operations, WCFRelaysOperations if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports + from azure.core import AzureClouds from azure.core.credentials import TokenCredential -class RelayAPI: # pylint: disable=client-accepts-api-version-keyword +class RelayAPI: """Use these API to manage Azure Relay resources through Azure Resource Manager. + :ivar operations: Operations operations + :vartype operations: azure.mgmt.relay.operations.Operations :ivar namespaces: NamespacesOperations operations :vartype namespaces: azure.mgmt.relay.operations.NamespacesOperations :ivar hybrid_connections: HybridConnectionsOperations operations :vartype hybrid_connections: azure.mgmt.relay.operations.HybridConnectionsOperations :ivar wcf_relays: WCFRelaysOperations operations :vartype wcf_relays: azure.mgmt.relay.operations.WCFRelaysOperations - :ivar private_endpoint_connections: PrivateEndpointConnectionsOperations operations - :vartype private_endpoint_connections: - azure.mgmt.relay.operations.PrivateEndpointConnectionsOperations - :ivar private_link_resources: PrivateLinkResourcesOperations operations - :vartype private_link_resources: azure.mgmt.relay.operations.PrivateLinkResourcesOperations - :ivar operations: Operations operations - :vartype operations: azure.mgmt.relay.operations.Operations :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential :param subscription_id: Subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. Required. :type subscription_id: str - :param base_url: Service URL. Default value is "https://management.azure.com". + :param base_url: Service URL. Default value is None. :type base_url: str - :keyword api_version: Api Version. Default value is "2021-11-01". Note that overriding this + :keyword cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is + None. + :paramtype cloud_setting: ~azure.core.AzureClouds + :keyword api_version: Api Version. Default value is "2017-04-01". Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str :keyword int polling_interval: Default waiting time between two polls for LRO operations if no @@ -63,30 +59,56 @@ def __init__( self, credential: "TokenCredential", subscription_id: str, - base_url: str = "https://management.azure.com", + base_url: Optional[str] = None, + *, + cloud_setting: Optional["AzureClouds"] = None, **kwargs: Any ) -> None: - self._config = RelayAPIConfiguration(credential=credential, subscription_id=subscription_id, **kwargs) - self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + _cloud = cloud_setting or settings.current.azure_cloud # type: ignore + _endpoints = get_arm_endpoints(_cloud) + if not base_url: + base_url = _endpoints["resource_manager"] + credential_scopes = kwargs.pop("credential_scopes", _endpoints["credential_scopes"]) + self._config = RelayAPIConfiguration( + credential=credential, + subscription_id=subscription_id, + cloud_setting=cloud_setting, + credential_scopes=credential_scopes, + **kwargs + ) - client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + ARMAutoResourceProviderRegistrationPolicy(), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: ARMPipelineClient = ARMPipelineClient(base_url=cast(str, base_url), policies=_policies, **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.operations = Operations(self._client, self._config, self._serialize, self._deserialize) self.namespaces = NamespacesOperations(self._client, self._config, self._serialize, self._deserialize) self.hybrid_connections = HybridConnectionsOperations( self._client, self._config, self._serialize, self._deserialize ) self.wcf_relays = WCFRelaysOperations(self._client, self._config, self._serialize, self._deserialize) - self.private_endpoint_connections = PrivateEndpointConnectionsOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.private_link_resources = PrivateLinkResourcesOperations( - 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, *, stream: bool = False, **kwargs: Any) -> HttpResponse: """Runs the network request through the client's chained policies. >>> from azure.core.rest import HttpRequest @@ -106,17 +128,14 @@ def _send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: request_copy = deepcopy(request) request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore - def close(self): - # type: () -> None + def close(self) -> None: self._client.close() - def __enter__(self): - # type: () -> RelayAPI + def __enter__(self) -> Self: self._client.__enter__() return self - def __exit__(self, *exc_details): - # type: (Any) -> None + def __exit__(self, *exc_details: Any) -> None: self._client.__exit__(*exc_details) diff --git a/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/_utils/__init__.py b/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/_utils/__init__.py new file mode 100644 index 000000000000..0af9b28f6607 --- /dev/null +++ b/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/_utils/__init__.py @@ -0,0 +1,6 @@ +# -------------------------------------------------------------------------- +# 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. +# -------------------------------------------------------------------------- diff --git a/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/_serialization.py b/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/_utils/serialization.py similarity index 74% rename from sdk/relay/azure-mgmt-relay/azure/mgmt/relay/_serialization.py rename to sdk/relay/azure-mgmt-relay/azure/mgmt/relay/_utils/serialization.py index 7c1dedb5133d..6da830e0cf4a 100644 --- a/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/_serialization.py +++ b/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/_utils/serialization.py @@ -1,30 +1,13 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 # -------------------------------------------------------------------------- -# # 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. -# +# 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. # -------------------------------------------------------------------------- -# pylint: skip-file +# pyright: reportUnnecessaryTypeIgnoreComment=false from base64 import b64decode, b64encode import calendar @@ -37,23 +20,33 @@ import re import sys import codecs +from typing import ( + Any, + cast, + Optional, + Union, + AnyStr, + IO, + Mapping, + Callable, + MutableMapping, +) try: from urllib import quote # type: ignore except ImportError: - from urllib.parse import quote # type: ignore + from urllib.parse import quote import xml.etree.ElementTree as ET -import isodate +import isodate # type: ignore +from typing_extensions import Self -from typing import Dict, Any, cast, TYPE_CHECKING - -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback +from azure.core.exceptions import DeserializationError, SerializationError +from azure.core.serialization import NULL as CoreNull _BOM = codecs.BOM_UTF8.decode(encoding="utf-8") -if TYPE_CHECKING: - from typing import Optional, Union, AnyStr, IO, Mapping +JSON = MutableMapping[str, Any] class RawDeserializer: @@ -65,8 +58,7 @@ class RawDeserializer: CONTEXT_NAME = "deserialized_data" @classmethod - def deserialize_from_text(cls, data, content_type=None): - # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any + 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. @@ -76,6 +68,8 @@ def deserialize_from_text(cls, data, content_type=None): :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. + :return: The deserialized data. + :rtype: object """ if hasattr(data, "read"): # Assume a stream @@ -97,7 +91,7 @@ def deserialize_from_text(cls, data, content_type=None): try: return json.loads(data_as_str) except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) + raise DeserializationError("JSON is invalid: {}".format(err), err) from err elif "xml" in (content_type or []): try: @@ -109,7 +103,7 @@ def deserialize_from_text(cls, data, content_type=None): pass return ET.fromstring(data_as_str) # nosec - except ET.ParseError: + except ET.ParseError as err: # 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 @@ -128,17 +122,23 @@ def _json_attemp(data): # 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("XML is invalid") from err + elif content_type.startswith("text/"): + return data_as_str raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) @classmethod - def deserialize_from_http_generics(cls, body_bytes, headers): - # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any + 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" + + :param bytes body_bytes: The body of the response. + :param dict headers: The headers of the response. + :returns: The deserialized data. + :rtype: object """ # Try to use content-type from headers if available content_type = None @@ -156,13 +156,6 @@ def deserialize_from_http_generics(cls, body_bytes, headers): return None -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str # type: ignore - unicode_str = str # type: ignore - _LOGGER = logging.getLogger(__name__) try: @@ -170,80 +163,31 @@ def deserialize_from_http_generics(cls, body_bytes, headers): except NameError: _long_type = int - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -try: - from datetime import timezone as _FixedOffset -except ImportError: # Python 2.7 - - class _FixedOffset(datetime.tzinfo): # type: ignore - """Fixed offset in minutes east from UTC. - Copy/pasted from Python doc - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc # type: ignore -except ImportError: - TZ_UTC = UTC() # type: ignore +TZ_UTC = datetime.timezone.utc _FLATTEN = re.compile(r"(? None: + self.additional_properties: Optional[dict[str, Any]] = {} + for k in kwargs: # pylint: disable=consider-using-dict-items if k not in self._attribute_map: _LOGGER.warning("%s is not a known attribute of class %s and will be ignored", k, self.__class__) elif k in self._validation and self._validation[k].get("readonly", False): @@ -290,43 +241,57 @@ def __init__(self, **kwargs): else: setattr(self, k, kwargs[k]) - def __eq__(self, other): - """Compare objects by comparing all attributes.""" + def __eq__(self, other: Any) -> bool: + """Compare objects by comparing all attributes. + + :param object other: The object to compare + :returns: True if objects are equal + :rtype: bool + """ if isinstance(other, self.__class__): return self.__dict__ == other.__dict__ return False - def __ne__(self, other): - """Compare objects by comparing all attributes.""" + def __ne__(self, other: Any) -> bool: + """Compare objects by comparing all attributes. + + :param object other: The object to compare + :returns: True if objects are not equal + :rtype: bool + """ return not self.__eq__(other) - def __str__(self): + def __str__(self) -> str: return str(self.__dict__) @classmethod - def enable_additional_properties_sending(cls): + def enable_additional_properties_sending(cls) -> None: cls._attribute_map["additional_properties"] = {"key": "", "type": "{object}"} @classmethod - def is_xml_model(cls): + def is_xml_model(cls) -> bool: try: - cls._xml_map + cls._xml_map # type: ignore except AttributeError: return False return True @classmethod def _create_xml_node(cls): - """Create XML node.""" + """Create XML node. + + :returns: The XML node + :rtype: xml.etree.ElementTree.Element + """ try: - xml_map = cls._xml_map + xml_map = cls._xml_map # type: ignore except AttributeError: xml_map = {} return _create_xml_node(xml_map.get("name", cls.__name__), xml_map.get("prefix", None), xml_map.get("ns", None)) - def serialize(self, keep_readonly=False, **kwargs): - """Return the JSON that would be sent to azure from this model. + def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: + """Return the JSON that would be sent to server from this model. This is an alias to `as_dict(full_restapi_key_transformer, keep_readonly=False)`. @@ -337,10 +302,17 @@ def serialize(self, keep_readonly=False, **kwargs): :rtype: dict """ serializer = Serializer(self._infer_class_models()) - return serializer._serialize(self, keep_readonly=keep_readonly, **kwargs) + return serializer._serialize( # type: ignore # pylint: disable=protected-access + self, keep_readonly=keep_readonly, **kwargs + ) - def as_dict(self, keep_readonly=True, key_transformer=attribute_transformer, **kwargs): - """Return a dict that can be JSONify using json.dump. + def as_dict( + self, + keep_readonly: bool = True, + key_transformer: Callable[[str, dict[str, Any], Any], Any] = attribute_transformer, + **kwargs: Any + ) -> JSON: + """Return a dict that can be serialized using json.dump. Advanced usage might optionally use a callback as parameter: @@ -366,12 +338,15 @@ def my_key_transformer(key, attr_desc, value): If you want XML serialization, you can pass the kwargs is_xml=True. + :param bool keep_readonly: If you want to serialize the readonly attributes :param function key_transformer: A key transformer function. :returns: A dict JSON compatible object :rtype: dict """ serializer = Serializer(self._infer_class_models()) - return serializer._serialize(self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs) + return serializer._serialize( # type: ignore # pylint: disable=protected-access + self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs + ) @classmethod def _infer_class_models(cls): @@ -381,25 +356,31 @@ def _infer_class_models(cls): client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} if cls.__name__ not in client_models: raise ValueError("Not Autorest generated code") - except Exception: + except Exception: # pylint: disable=broad-exception-caught # Assume it's not Autorest generated (tests?). Add ourselves as dependencies. client_models = {cls.__name__: cls} return client_models @classmethod - def deserialize(cls, data, content_type=None): + def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Self: """Parse a str using the RestAPI syntax and return a model. :param str data: A str using RestAPI structure. JSON by default. :param str content_type: JSON by default, set application/xml if XML. :returns: An instance of this model - :raises: DeserializationError if something went wrong + :raises DeserializationError: if something went wrong + :rtype: Self """ deserializer = Deserializer(cls._infer_class_models()) - return deserializer(cls.__name__, data, content_type=content_type) + return deserializer(cls.__name__, data, content_type=content_type) # type: ignore @classmethod - def from_dict(cls, data, key_extractors=None, content_type=None): + def from_dict( + cls, + data: Any, + key_extractors: Optional[Callable[[str, dict[str, Any], Any], Any]] = None, + content_type: Optional[str] = None, + ) -> Self: """Parse a dict using given key extractor return a model. By default consider key @@ -407,13 +388,15 @@ def from_dict(cls, data, key_extractors=None, content_type=None): and last_rest_key_case_insensitive_extractor) :param dict data: A dict using RestAPI structure + :param function key_extractors: A key extractor function. :param str content_type: JSON by default, set application/xml if XML. :returns: An instance of this model - :raises: DeserializationError if something went wrong + :raises DeserializationError: if something went wrong + :rtype: Self """ deserializer = Deserializer(cls._infer_class_models()) - deserializer.key_extractors = ( - [ + deserializer.key_extractors = ( # type: ignore + [ # type: ignore attribute_key_case_insensitive_extractor, rest_key_case_insensitive_extractor, last_rest_key_case_insensitive_extractor, @@ -421,7 +404,7 @@ def from_dict(cls, data, key_extractors=None, content_type=None): if key_extractors is None else key_extractors ) - return deserializer(cls.__name__, data, content_type=content_type) + return deserializer(cls.__name__, data, content_type=content_type) # type: ignore @classmethod def _flatten_subtype(cls, key, objects): @@ -429,21 +412,25 @@ def _flatten_subtype(cls, key, objects): return {} result = dict(cls._subtype_map[key]) for valuetype in cls._subtype_map[key].values(): - result.update(objects[valuetype]._flatten_subtype(key, objects)) + result |= objects[valuetype]._flatten_subtype(key, objects) # pylint: disable=protected-access return result @classmethod def _classify(cls, response, objects): """Check the class _subtype_map for any child classes. We want to ignore any inherited _subtype_maps. - Remove the polymorphic key from the initial data. + + :param dict response: The initial data + :param dict objects: The class objects + :returns: The class to be used + :rtype: class """ for subtype_key in cls.__dict__.get("_subtype_map", {}).keys(): subtype_value = None if not isinstance(response, ET.Element): rest_api_response_key = cls._get_rest_key_parts(subtype_key)[-1] - subtype_value = response.pop(rest_api_response_key, None) or response.pop(subtype_key, None) + subtype_value = response.get(rest_api_response_key, None) or response.get(subtype_key, None) else: subtype_value = xml_key_extractor(subtype_key, cls._attribute_map[subtype_key], response) if subtype_value: @@ -453,7 +440,7 @@ def _classify(cls, response, objects): return cls flatten_mapping_type = cls._flatten_subtype(subtype_key, objects) try: - return objects[flatten_mapping_type[subtype_value]] + return objects[flatten_mapping_type[subtype_value]] # type: ignore except KeyError: _LOGGER.warning( "Subtype value %s has no mapping, use base class %s.", @@ -482,11 +469,13 @@ def _decode_attribute_map_key(key): inside the received data. :param str key: A key string from the generated code + :returns: The decoded key + :rtype: str """ return key.replace("\\.", ".") -class Serializer(object): +class Serializer: # pylint: disable=too-many-public-methods """Request object model serializer.""" basic_types = {str: "str", int: "int", bool: "bool", float: "float"} @@ -521,7 +510,7 @@ class Serializer(object): "multiple": lambda x, y: x % y != 0, } - def __init__(self, classes=None): + def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: self.serialize_type = { "iso-8601": Serializer.serialize_iso, "rfc-1123": Serializer.serialize_rfc, @@ -537,17 +526,20 @@ def __init__(self, classes=None): "[]": self.serialize_iter, "{}": self.serialize_dict, } - self.dependencies = dict(classes) if classes else {} + self.dependencies: dict[str, type] = 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): + def _serialize( # pylint: disable=too-many-nested-blocks, too-many-branches, too-many-statements, too-many-locals + self, target_obj, data_type=None, **kwargs + ): """Serialize data into a string according to type. - :param target_obj: The data to be serialized. + :param object 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. + :raises SerializationError: if serialization fails. + :returns: The serialized data. """ key_transformer = kwargs.get("key_transformer", self.key_transformer) keep_readonly = kwargs.get("keep_readonly", False) @@ -573,17 +565,19 @@ def _serialize(self, target_obj, data_type=None, **kwargs): serialized = {} if is_xml_model_serialization: - serialized = target_obj._create_xml_node() + serialized = target_obj._create_xml_node() # pylint: disable=protected-access try: - attributes = target_obj._attribute_map + attributes = target_obj._attribute_map # pylint: disable=protected-access for attr, attr_desc in attributes.items(): attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): + if not keep_readonly and target_obj._validation.get( # pylint: disable=protected-access + 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) + serialized |= target_obj.additional_properties continue try: @@ -605,62 +599,63 @@ def _serialize(self, target_obj, data_type=None, **kwargs): 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) + 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 + serialized.text = new_attr # type: ignore continue if isinstance(new_attr, list): - serialized.extend(new_attr) + 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 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) + 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) + local_node.text = str(new_attr) + serialized.append(local_node) # type: ignore else: # JSON - for k in reversed(keys): - unflattened = {k: new_attr} - new_attr = unflattened + for k in reversed(keys): # type: ignore + new_attr = {k: new_attr} _new_attr = new_attr _serialized = serialized - for k in keys: + for k in keys: # type: ignore if k not in _serialized: - _serialized.update(_new_attr) - _new_attr = _new_attr[k] + _serialized.update(_new_attr) # type: ignore + _new_attr = _new_attr[k] # type: ignore _serialized = _serialized[k] - except ValueError: - continue + except ValueError as err: + if isinstance(err, SerializationError): + raise 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 + raise SerializationError(msg) from err + return serialized def body(self, data, data_type, **kwargs): """Serialize data intended for a request body. - :param data: The data to be serialized. + :param object 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 + :raises SerializationError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized request body """ # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) + internal_data_type_str = data_type.strip("[]{}") + internal_data_type = self.dependencies.get(internal_data_type_str, None) try: is_xml_model_serialization = kwargs["is_xml"] except KeyError: @@ -675,7 +670,7 @@ def body(self, data, data_type, **kwargs): # We're not able to deal with additional properties for now. deserializer.additional_properties_detection = False if is_xml_model_serialization: - deserializer.key_extractors = [ + deserializer.key_extractors = [ # type: ignore attribute_key_case_insensitive_extractor, ] else: @@ -684,20 +679,22 @@ def body(self, data, data_type, **kwargs): attribute_key_case_insensitive_extractor, last_rest_key_case_insensitive_extractor, ] - data = deserializer._deserialize(data_type, data) + data = deserializer._deserialize(data_type, data) # pylint: disable=protected-access except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) + raise SerializationError("Unable to build a model: " + str(err)) from 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 name: The name of the URL path parameter. + :param object 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 + :returns: The serialized URL path + :raises TypeError: if serialization fails. + :raises ValueError: if data is None """ try: output = self.serialize_data(data, data_type, **kwargs) @@ -706,30 +703,30 @@ def url(self, name, data, data_type, **kwargs): if kwargs.get("skip_quote") is True: output = str(output) + output = output.replace("{", quote("{")).replace("}", quote("}")) else: output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + 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 name: The name of the query parameter. + :param object 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 + :rtype: str, list + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized query parameter """ 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)) + do_quote = not kwargs.get("skip_quote", False) + return self.serialize_iter(data, internal_data_type, do_quote=do_quote, **kwargs) # Not a list, regular serialization output = self.serialize_data(data, data_type, **kwargs) @@ -739,19 +736,20 @@ def query(self, name, data, data_type, **kwargs): output = str(output) else: output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + 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 name: The name of the header. + :param object 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 + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized header """ try: if data_type in ["[str]"]: @@ -760,35 +758,36 @@ def header(self, name, data, data_type, **kwargs): 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) + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + 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 object 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. + :raises AttributeError: if required data is None. + :raises ValueError: if data is None + :raises SerializationError: if serialization fails. + :returns: The serialized data. + :rtype: str, int, float, bool, dict, list """ if data is None: raise ValueError("No value for given attribute") try: + if data is CoreNull: + return None if data_type in self.basic_types.values(): return self.serialize_basic(data, data_type, **kwargs) - elif data_type in self.serialize_type: + if 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__) + enum_type = self.dependencies.get(data_type, cast(type, data.__class__)) if issubclass(enum_type, Enum): return Serializer.serialize_enum(data, enum_obj=enum_type) @@ -798,12 +797,11 @@ def serialize_data(self, data, data_type, **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) + raise SerializationError(msg.format(data, data_type)) from err + return self._serialize(data, **kwargs) @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): + def _get_custom_serializers(cls, data_type, **kwargs): # pylint: disable=inconsistent-return-statements custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) if custom_serializer: return custom_serializer @@ -819,23 +817,33 @@ def serialize_basic(cls, data, data_type, **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 obj data: Object to be serialized. :param str data_type: Type of object in the iterable. + :rtype: str, int, float, bool + :return: serialized object + :raises TypeError: raise if data_type is not one of str, int, float, bool. """ 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 + if data_type == "int": + return int(data) + if data_type == "float": + return float(data) + if data_type == "bool": + return bool(data) + raise TypeError("Unknown basic data type: {}".format(data_type)) @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. + :param str data: Object to be serialized. :rtype: str + :return: serialized object """ try: # If I received an enum, return its value return data.value @@ -843,14 +851,13 @@ def serialize_unicode(cls, data): pass try: - if isinstance(data, unicode): + 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) + return str(data) def serialize_iter(self, data, iter_type, div=None, **kwargs): """Serialize iterable. @@ -860,13 +867,13 @@ def serialize_iter(self, data, iter_type, div=None, **kwargs): 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 list data: 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'. + Defaults to False. :rtype: list, str + :return: serialized iterable """ if isinstance(data, str): raise SerializationError("Refuse str type as a valid iter type.") @@ -878,9 +885,14 @@ def serialize_iter(self, data, iter_type, div=None, **kwargs): for d in data: try: serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: + except ValueError as err: + if isinstance(err, SerializationError): + raise serialized.append(None) + if kwargs.get("do_quote", False): + serialized = ["" if s is None else quote(str(s), safe="") for s in serialized] + if div: serialized = ["" if s is None else str(s) for s in serialized] serialized = div.join(serialized) @@ -916,16 +928,17 @@ def serialize_dict(self, attr, dict_type, **kwargs): :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 + :return: serialized dictionary """ 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: + except ValueError as err: + if isinstance(err, SerializationError): + raise serialized[self.serialize_unicode(key)] = None if "xml" in serialization_ctxt: @@ -940,7 +953,7 @@ def serialize_dict(self, attr, dict_type, **kwargs): return serialized - def serialize_object(self, attr, **kwargs): + def serialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements """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 @@ -948,6 +961,7 @@ def serialize_object(self, attr, **kwargs): :param dict attr: Object to be serialized. :rtype: dict or str + :return: serialized object """ if attr is None: return None @@ -958,7 +972,7 @@ def serialize_object(self, attr, **kwargs): 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: + if obj_type is str: return self.serialize_unicode(attr) if obj_type is datetime.datetime: return self.serialize_iso(attr) @@ -972,7 +986,7 @@ def serialize_object(self, attr, **kwargs): 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): + if obj_type in self.dependencies.values() or isinstance(attr, Model): return self._serialize(attr) if obj_type == dict: @@ -1001,58 +1015,63 @@ def serialize_enum(attr, enum_obj=None): except AttributeError: result = attr try: - enum_obj(result) + enum_obj(result) # type: ignore return result - except ValueError: - for enum_value in enum_obj: + except ValueError as exc: + 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)) + raise SerializationError(error.format(attr, enum_obj)) from exc @staticmethod - def serialize_bytearray(attr, **kwargs): + def serialize_bytearray(attr, **kwargs): # pylint: disable=unused-argument """Serialize bytearray into base-64 string. - :param attr: Object to be serialized. + :param str attr: Object to be serialized. :rtype: str + :return: serialized base64 """ return b64encode(attr).decode() @staticmethod - def serialize_base64(attr, **kwargs): + def serialize_base64(attr, **kwargs): # pylint: disable=unused-argument """Serialize str into base-64 string. - :param attr: Object to be serialized. + :param str attr: Object to be serialized. :rtype: str + :return: serialized base64 """ encoded = b64encode(attr).decode("ascii") return encoded.strip("=").replace("+", "-").replace("/", "_") @staticmethod - def serialize_decimal(attr, **kwargs): + def serialize_decimal(attr, **kwargs): # pylint: disable=unused-argument """Serialize Decimal object to float. - :param attr: Object to be serialized. + :param decimal attr: Object to be serialized. :rtype: float + :return: serialized decimal """ return float(attr) @staticmethod - def serialize_long(attr, **kwargs): + def serialize_long(attr, **kwargs): # pylint: disable=unused-argument """Serialize long (Py2) or int (Py3). - :param attr: Object to be serialized. + :param int attr: Object to be serialized. :rtype: int/long + :return: serialized long """ return _long_type(attr) @staticmethod - def serialize_date(attr, **kwargs): + def serialize_date(attr, **kwargs): # pylint: disable=unused-argument """Serialize Date object into ISO-8601 formatted string. :param Date attr: Object to be serialized. :rtype: str + :return: serialized date """ if isinstance(attr, str): attr = isodate.parse_date(attr) @@ -1060,11 +1079,12 @@ def serialize_date(attr, **kwargs): return t @staticmethod - def serialize_time(attr, **kwargs): + def serialize_time(attr, **kwargs): # pylint: disable=unused-argument """Serialize Time object into ISO-8601 formatted string. :param datetime.time attr: Object to be serialized. :rtype: str + :return: serialized time """ if isinstance(attr, str): attr = isodate.parse_time(attr) @@ -1074,30 +1094,32 @@ def serialize_time(attr, **kwargs): return t @staticmethod - def serialize_duration(attr, **kwargs): + def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument """Serialize TimeDelta object into ISO-8601 formatted string. :param TimeDelta attr: Object to be serialized. :rtype: str + :return: serialized duration """ if isinstance(attr, str): attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) @staticmethod - def serialize_rfc(attr, **kwargs): + def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. :param Datetime attr: Object to be serialized. :rtype: str - :raises: TypeError if format invalid. + :raises TypeError: if format invalid. + :return: serialized rfc """ 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.") + except AttributeError as exc: + raise TypeError("RFC1123 object must be valid Datetime object.") from exc return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( Serializer.days[utc.tm_wday], @@ -1110,12 +1132,13 @@ def serialize_rfc(attr, **kwargs): ) @staticmethod - def serialize_iso(attr, **kwargs): + def serialize_iso(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into ISO-8601 formatted string. :param Datetime attr: Object to be serialized. :rtype: str - :raises: SerializationError if format invalid. + :raises SerializationError: if format invalid. + :return: serialized iso """ if isinstance(attr, str): attr = isodate.parse_datetime(attr) @@ -1135,19 +1158,20 @@ def serialize_iso(attr, **kwargs): return date + microseconds + "Z" except (ValueError, OverflowError) as err: msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) + raise SerializationError(msg) from err except AttributeError as err: msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) + raise TypeError(msg) from err @staticmethod - def serialize_unix(attr, **kwargs): + def serialize_unix(attr, **kwargs): # pylint: disable=unused-argument """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 + :raises SerializationError: if format invalid + :return: serialied unix """ if isinstance(attr, int): return attr @@ -1155,16 +1179,17 @@ def serialize_unix(attr, **kwargs): 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.") + except AttributeError as exc: + raise TypeError("Unix time object must be valid Datetime object.") from exc -def rest_key_extractor(attr, attr_desc, data): +def rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument key = attr_desc["key"] working_data = data while "." in key: - dict_keys = _FLATTEN.split(key) + # Need the cast, as for some reasons "split" is typed as list[str | Any] + dict_keys = cast(list[str], _FLATTEN.split(key)) if len(dict_keys) == 1: key = _decode_attribute_map_key(dict_keys[0]) break @@ -1173,14 +1198,15 @@ def rest_key_extractor(attr, attr_desc, 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): +def rest_key_case_insensitive_extractor( # pylint: disable=unused-argument, inconsistent-return-statements + attr, attr_desc, data +): key = attr_desc["key"] working_data = data @@ -1194,7 +1220,6 @@ def rest_key_case_insensitive_extractor(attr, attr_desc, 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:]) @@ -1202,17 +1227,29 @@ def rest_key_case_insensitive_extractor(attr, attr_desc, 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.""" +def last_rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument + """Extract the attribute in "data" based on the last part of the JSON path key. + + :param str attr: The attribute to extract + :param dict attr_desc: The attribute description + :param dict data: The data to extract from + :rtype: object + :returns: The extracted attribute + """ 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): +def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): # pylint: disable=unused-argument """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" + :param str attr: The attribute to extract + :param dict attr_desc: The attribute description + :param dict data: The data to extract from + :rtype: object + :returns: The extracted attribute """ key = attr_desc["key"] dict_keys = _FLATTEN.split(key) @@ -1245,11 +1282,11 @@ def _extract_name_from_internal_type(internal_type): 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) + xml_name = "{{{}}}{}".format(xml_ns, xml_name) return xml_name -def xml_key_extractor(attr, attr_desc, data): +def xml_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument,too-many-return-statements if isinstance(data, dict): return None @@ -1269,7 +1306,7 @@ def xml_key_extractor(attr, attr_desc, data): # 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) + xml_name = "{{{}}}{}".format(xml_ns, xml_name) # If it's an attribute, that's simple if xml_desc.get("attr", False): @@ -1301,22 +1338,21 @@ def xml_key_extractor(attr, attr_desc, data): if is_iter_type: if is_wrapped: return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list + 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 - ) + # 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. + ) + 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: @@ -1324,7 +1360,7 @@ def xml_key_extractor(attr, attr_desc, data): return children[0] -class Deserializer(object): +class Deserializer: """Response object model deserializer. :param dict classes: Class type dictionary for deserializing complex types. @@ -1333,9 +1369,9 @@ class Deserializer(object): 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}]?") + valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") - def __init__(self, classes=None): + def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: self.deserialize_type = { "iso-8601": Deserializer.deserialize_iso, "rfc-1123": Deserializer.deserialize_rfc, @@ -1355,7 +1391,7 @@ def __init__(self, classes=None): "duration": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } - self.dependencies = dict(classes) if classes else {} + self.dependencies: dict[str, type] = 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 @@ -1371,27 +1407,29 @@ def __call__(self, target_obj, response_data, content_type=None): :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. + :raises DeserializationError: if deserialization fails. :return: Deserialized object. + :rtype: object """ data = self._unpack_content(response_data, content_type) return self._deserialize(target_obj, data) - def _deserialize(self, target_obj, data): + def _deserialize(self, target_obj, data): # pylint: disable=inconsistent-return-statements """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. + :raises DeserializationError: if deserialization fails. :return: Deserialized object. + :rtype: 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(): + for attr, mapconfig in data._attribute_map.items(): # pylint: disable=protected-access if attr in constants: continue value = getattr(data, attr) @@ -1408,15 +1446,15 @@ def _deserialize(self, target_obj, data): response, class_name = self._classify_target(target_obj, data) - if isinstance(response, basestring): + if isinstance(response, str): return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): + if isinstance(response, type) and issubclass(response, Enum): return self.deserialize_enum(data, response) - if data is None: + if data is None or data is CoreNull: return data try: - attributes = response._attribute_map + attributes = response._attribute_map # type: ignore # pylint: disable=protected-access d_attrs = {} for attr, attr_desc in attributes.items(): # Check empty string. If it's not empty, someone has a real "additionalProperties"... @@ -1444,11 +1482,10 @@ def _deserialize(self, target_obj, data): value = self.deserialize_data(raw_value, attr_desc["type"]) d_attrs[attr] = value except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) + msg = "Unable to deserialize to object: " + class_name # type: ignore + raise DeserializationError(msg) from err + 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: @@ -1474,22 +1511,24 @@ def _classify_target(self, target, data): 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. + :param str/dict data: The response data to deserialize. + :return: The classified target object and its class name. + :rtype: tuple """ if target is None: return None, None - if isinstance(target, basestring): + if isinstance(target, str): try: target = self.dependencies[target] except KeyError: return target, target try: - target = target._classify(data, self.dependencies) + target = target._classify(data, self.dependencies) # type: ignore # pylint: disable=protected-access except AttributeError: pass # Target is not a Model, no classify - return target, target.__class__.__name__ + return target, target.__class__.__name__ # type: ignore def failsafe_deserialize(self, target_obj, data, content_type=None): """Ignores any errors encountered in deserialization, @@ -1499,12 +1538,14 @@ def failsafe_deserialize(self, target_obj, data, content_type=None): 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/dict data: The response data to deserialize. :param str content_type: Swagger "produces" if available. + :return: Deserialized object. + :rtype: object """ try: return self(target_obj, data, content_type=content_type) - except: + except: # pylint: disable=bare-except _LOGGER.debug( "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True ) @@ -1522,10 +1563,12 @@ def _unpack_content(raw_data, content_type=None): 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. + :param obj raw_data: Data to be processed. + :param str 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 + :rtype: object + :return: Unpacked content. """ # Assume this is enough to detect a Pipeline Response without importing it context = getattr(raw_data, "context", {}) @@ -1542,31 +1585,42 @@ def _unpack_content(raw_data, content_type=None): 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) + if isinstance(raw_data, (str, 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. + :param Response response: The response model class. + :param dict attrs: The deserialized response attributes. + :param dict additional_properties: Additional properties to be set. + :rtype: Response + :return: The instantiated response model. """ 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")] + readonly = [ + k + for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore + if v.get("readonly") + ] + const = [ + k + for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore + 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 + response_obj.additional_properties = additional_properties # type: ignore return response_obj except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) - raise DeserializationError(msg + str(err)) + msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) # type: ignore + raise DeserializationError(msg + str(err)) from err else: try: for attr, value in attrs.items(): @@ -1575,15 +1629,16 @@ def _instantiate_model(self, response, attrs, additional_properties=None): except Exception as exp: msg = "Unable to populate response model. " msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) + raise DeserializationError(msg) from exp - def deserialize_data(self, data, data_type): + def deserialize_data(self, data, data_type): # pylint: disable=too-many-return-statements """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. + :raises DeserializationError: if deserialization fails. :return: Deserialized object. + :rtype: object """ if data is None: return data @@ -1597,7 +1652,11 @@ def deserialize_data(self, data, data_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"{}"] + is_a_text_parsing_type = lambda x: x not in [ # pylint: disable=unnecessary-lambda-assignment + "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) @@ -1616,15 +1675,15 @@ def deserialize_data(self, data, data_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) + raise DeserializationError(msg) from err + 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. + :return: Deserialized iterable. :rtype: list """ if attr is None: @@ -1641,6 +1700,7 @@ def deserialize_dict(self, attr, dict_type): :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. + :return: Deserialized dictionary. :rtype: dict """ if isinstance(attr, list): @@ -1651,20 +1711,21 @@ def deserialize_dict(self, attr, dict_type): 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): + def deserialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements """Deserialize a generic object. This will be handled as a dictionary. :param dict attr: Dictionary to be deserialized. + :return: Deserialized object. :rtype: dict - :raises: TypeError if non-builtin datatype encountered. + :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): + if isinstance(attr, str): return self.deserialize_basic(attr, "str") obj_type = type(attr) if obj_type in self.basic_types: @@ -1690,11 +1751,10 @@ def deserialize_object(self, attr, **kwargs): pass return deserialized - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) + error = "Cannot deserialize generic object with type: " + raise TypeError(error + str(obj_type)) - def deserialize_basic(self, attr, data_type): + def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return-statements """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 @@ -1702,8 +1762,9 @@ def deserialize_basic(self, attr, data_type): :param str attr: response string to be deserialized. :param str data_type: deserialization data type. + :return: Deserialized basic type. :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. + :raises TypeError: if string format is not valid or data_type is not one of str, int, float, bool. """ # If we're here, data is supposed to be a basic type. # If it's still an XML node, take the text @@ -1713,24 +1774,27 @@ def deserialize_basic(self, attr, data_type): 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 + # 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 isinstance(attr, str): if attr.lower() in ["true", "1"]: return True - elif attr.lower() in ["false", "0"]: + if 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 + if data_type == "int": + return int(attr) + if data_type == "float": + return float(attr) + raise TypeError("Unknown basic data type: {}".format(data_type)) @staticmethod def deserialize_unicode(data): @@ -1738,6 +1802,7 @@ def deserialize_unicode(data): as a string. :param str data: response string to be deserialized. + :return: Deserialized string. :rtype: str or unicode """ # We might be here because we have an enum modeled as string, @@ -1747,12 +1812,11 @@ def deserialize_unicode(data): # Consider this is real string try: - if isinstance(data, unicode): + if isinstance(data, unicode): # type: ignore return data except NameError: return str(data) - else: - return str(data) + return str(data) @staticmethod def deserialize_enum(data, enum_obj): @@ -1764,6 +1828,7 @@ def deserialize_enum(data, enum_obj): :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. + :return: Deserialized enum object. :rtype: Enum """ if isinstance(data, enum_obj) or data is None: @@ -1772,12 +1837,11 @@ def deserialize_enum(data, enum_obj): 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: + except IndexError as exc: error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) + raise DeserializationError(error.format(data, enum_obj)) from exc try: return enum_obj(str(data)) except ValueError: @@ -1793,25 +1857,27 @@ def deserialize_bytearray(attr): """Deserialize string into bytearray. :param str attr: response string to be deserialized. + :return: Deserialized bytearray :rtype: bytearray - :raises: TypeError if string format invalid. + :raises TypeError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text - return bytearray(b64decode(attr)) + 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. + :return: Deserialized base64 string :rtype: bytearray - :raises: TypeError if string format invalid. + :raises TypeError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) - attr = attr + padding + padding = "=" * (3 - (len(attr) + 3) % 4) # type: ignore + attr = attr + padding # type: ignore encoded = attr.replace("-", "+").replace("_", "/") return b64decode(encoded) @@ -1820,36 +1886,39 @@ 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. + :return: Deserialized decimal + :raises DeserializationError: if string format invalid. + :rtype: decimal """ if isinstance(attr, ET.Element): attr = attr.text try: - return decimal.Decimal(attr) + return decimal.Decimal(str(attr)) # type: ignore except decimal.DecimalException as err: msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) + raise DeserializationError(msg) from err @staticmethod def deserialize_long(attr): """Deserialize string into long (Py2) or int (Py3). :param str attr: response string to be deserialized. + :return: Deserialized int :rtype: long or int - :raises: ValueError if string format invalid. + :raises ValueError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text - return _long_type(attr) + 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. + :return: Deserialized duration :rtype: TimeDelta - :raises: DeserializationError if string format invalid. + :raises DeserializationError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text @@ -1857,36 +1926,37 @@ def deserialize_duration(attr): 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 + raise DeserializationError(msg) from err + return duration @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. :param str attr: response string to be deserialized. + :return: Deserialized date :rtype: Date - :raises: DeserializationError if string format invalid. + :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): + 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) + return isodate.parse_date(attr, defaultmonth=0, defaultday=0) @staticmethod def deserialize_time(attr): """Deserialize ISO-8601 formatted string into time object. :param str attr: response string to be deserialized. + :return: Deserialized time :rtype: datetime.time - :raises: DeserializationError if string format invalid. + :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): + 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) @@ -1895,36 +1965,37 @@ def deserialize_rfc(attr): """Deserialize RFC-1123 formatted string into Datetime object. :param str attr: response string to be deserialized. + :return: Deserialized RFC datetime :rtype: Datetime - :raises: DeserializationError if string format invalid. + :raises DeserializationError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text try: - parsed_date = email.utils.parsedate_tz(attr) + 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)) + *parsed_date[:6], tzinfo=datetime.timezone(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 + raise DeserializationError(msg) from err + return date_obj @staticmethod def deserialize_iso(attr): """Deserialize ISO-8601 formatted string into Datetime object. :param str attr: response string to be deserialized. + :return: Deserialized ISO datetime :rtype: Datetime - :raises: DeserializationError if string format invalid. + :raises DeserializationError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text try: - attr = attr.upper() + attr = attr.upper() # type: ignore match = Deserializer.valid_date.match(attr) if not match: raise ValueError("Invalid datetime string: " + attr) @@ -1946,9 +2017,8 @@ def deserialize_iso(attr): 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 + raise DeserializationError(msg) from err + return date_obj @staticmethod def deserialize_unix(attr): @@ -1956,15 +2026,16 @@ def deserialize_unix(attr): This is represented as seconds. :param int attr: Object to be serialized. + :return: Deserialized datetime :rtype: Datetime - :raises: DeserializationError if format invalid + :raises DeserializationError: if format invalid """ if isinstance(attr, ET.Element): - attr = int(attr.text) + attr = int(attr.text) # type: ignore try: + attr = int(attr) 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 + raise DeserializationError(msg) from err + return date_obj diff --git a/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/_vendor.py b/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/_vendor.py deleted file mode 100644 index 9aad73fc743e..000000000000 --- a/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/_vendor.py +++ /dev/null @@ -1,27 +0,0 @@ -# -------------------------------------------------------------------------- -# 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/relay/azure-mgmt-relay/azure/mgmt/relay/_version.py b/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/_version.py index e32dc6ec4218..924647bfeefc 100644 --- a/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/_version.py +++ b/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "2.0.0b1" +VERSION = "1.1.1" diff --git a/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/aio/__init__.py b/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/aio/__init__.py index a83398b68d4c..a34fffb8d928 100644 --- a/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/aio/__init__.py +++ b/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/aio/__init__.py @@ -5,12 +5,18 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._relay_api import RelayAPI +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._relay_api import RelayAPI # type: ignore try: from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import + from ._patch import * except ImportError: _patch_all = [] from ._patch import patch_sdk as _patch_sdk @@ -18,6 +24,6 @@ __all__ = [ "RelayAPI", ] -__all__.extend([p for p in _patch_all if p not in __all__]) +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/aio/_configuration.py b/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/aio/_configuration.py index d83ddb8f52a6..898db05e4815 100644 --- a/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/aio/_configuration.py +++ b/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/aio/_configuration.py @@ -6,26 +6,19 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import sys -from typing import Any, TYPE_CHECKING +from typing import Any, Optional, 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 import AzureClouds from azure.core.credentials_async import AsyncTokenCredential -class RelayAPIConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class RelayAPIConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for RelayAPI. Note that all parameters used to create this instance are saved as instance @@ -36,14 +29,22 @@ class RelayAPIConfiguration(Configuration): # pylint: disable=too-many-instance :param subscription_id: Subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. Required. :type subscription_id: str - :keyword api_version: Api Version. Default value is "2021-11-01". Note that overriding this + :param cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is + None. + :type cloud_setting: ~azure.core.AzureClouds + :keyword api_version: Api Version. Default value is "2017-04-01". Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str """ - def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: - super(RelayAPIConfiguration, self).__init__(**kwargs) - api_version = kwargs.pop("api_version", "2021-11-01") # type: Literal["2021-11-01"] + def __init__( + self, + credential: "AsyncTokenCredential", + subscription_id: str, + cloud_setting: Optional["AzureClouds"] = None, + **kwargs: Any + ) -> None: + api_version: str = kwargs.pop("api_version", "2017-04-01") if credential is None: raise ValueError("Parameter 'credential' must not be None.") @@ -52,9 +53,11 @@ def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **k self.credential = credential self.subscription_id = subscription_id + self.cloud_setting = cloud_setting self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-relay/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -63,9 +66,9 @@ def _configure(self, **kwargs: Any) -> None: 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.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( diff --git a/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/aio/_relay_api.py b/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/aio/_relay_api.py index 47dc1a5e2b9e..213db48f5073 100644 --- a/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/aio/_relay_api.py +++ b/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/aio/_relay_api.py @@ -7,52 +7,48 @@ # -------------------------------------------------------------------------- from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING +from typing import Any, Awaitable, Optional, TYPE_CHECKING, cast +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.settings import settings from azure.mgmt.core import AsyncARMPipelineClient +from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy +from azure.mgmt.core.tools import get_arm_endpoints -from .. import models -from .._serialization import Deserializer, Serializer +from .. import models as _models +from .._utils.serialization import Deserializer, Serializer from ._configuration import RelayAPIConfiguration -from .operations import ( - HybridConnectionsOperations, - NamespacesOperations, - Operations, - PrivateEndpointConnectionsOperations, - PrivateLinkResourcesOperations, - WCFRelaysOperations, -) +from .operations import HybridConnectionsOperations, NamespacesOperations, Operations, WCFRelaysOperations if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports + from azure.core import AzureClouds from azure.core.credentials_async import AsyncTokenCredential -class RelayAPI: # pylint: disable=client-accepts-api-version-keyword +class RelayAPI: """Use these API to manage Azure Relay resources through Azure Resource Manager. + :ivar operations: Operations operations + :vartype operations: azure.mgmt.relay.aio.operations.Operations :ivar namespaces: NamespacesOperations operations :vartype namespaces: azure.mgmt.relay.aio.operations.NamespacesOperations :ivar hybrid_connections: HybridConnectionsOperations operations :vartype hybrid_connections: azure.mgmt.relay.aio.operations.HybridConnectionsOperations :ivar wcf_relays: WCFRelaysOperations operations :vartype wcf_relays: azure.mgmt.relay.aio.operations.WCFRelaysOperations - :ivar private_endpoint_connections: PrivateEndpointConnectionsOperations operations - :vartype private_endpoint_connections: - azure.mgmt.relay.aio.operations.PrivateEndpointConnectionsOperations - :ivar private_link_resources: PrivateLinkResourcesOperations operations - :vartype private_link_resources: azure.mgmt.relay.aio.operations.PrivateLinkResourcesOperations - :ivar operations: Operations operations - :vartype operations: azure.mgmt.relay.aio.operations.Operations :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential :param subscription_id: Subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. Required. :type subscription_id: str - :param base_url: Service URL. Default value is "https://management.azure.com". + :param base_url: Service URL. Default value is None. :type base_url: str - :keyword api_version: Api Version. Default value is "2021-11-01". Note that overriding this + :keyword cloud_setting: The cloud setting for which to get the ARM endpoint. Default value is + None. + :paramtype cloud_setting: ~azure.core.AzureClouds + :keyword api_version: Api Version. Default value is "2017-04-01". Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str :keyword int polling_interval: Default waiting time between two polls for LRO operations if no @@ -63,30 +59,60 @@ def __init__( self, credential: "AsyncTokenCredential", subscription_id: str, - base_url: str = "https://management.azure.com", + base_url: Optional[str] = None, + *, + cloud_setting: Optional["AzureClouds"] = None, **kwargs: Any ) -> None: - self._config = RelayAPIConfiguration(credential=credential, subscription_id=subscription_id, **kwargs) - self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + _cloud = cloud_setting or settings.current.azure_cloud # type: ignore + _endpoints = get_arm_endpoints(_cloud) + if not base_url: + base_url = _endpoints["resource_manager"] + credential_scopes = kwargs.pop("credential_scopes", _endpoints["credential_scopes"]) + self._config = RelayAPIConfiguration( + credential=credential, + subscription_id=subscription_id, + cloud_setting=cloud_setting, + credential_scopes=credential_scopes, + **kwargs + ) + + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + AsyncARMAutoResourceProviderRegistrationPolicy(), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: AsyncARMPipelineClient = AsyncARMPipelineClient( + base_url=cast(str, base_url), policies=_policies, **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.operations = Operations(self._client, self._config, self._serialize, self._deserialize) self.namespaces = NamespacesOperations(self._client, self._config, self._serialize, self._deserialize) self.hybrid_connections = HybridConnectionsOperations( self._client, self._config, self._serialize, self._deserialize ) self.wcf_relays = WCFRelaysOperations(self._client, self._config, self._serialize, self._deserialize) - self.private_endpoint_connections = PrivateEndpointConnectionsOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.private_link_resources = PrivateLinkResourcesOperations( - 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, *, stream: bool = False, **kwargs: Any + ) -> Awaitable[AsyncHttpResponse]: """Runs the network request through the client's chained policies. >>> from azure.core.rest import HttpRequest @@ -106,14 +132,14 @@ def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncH request_copy = deepcopy(request) request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore async def close(self) -> None: await self._client.close() - async def __aenter__(self) -> "RelayAPI": + async def __aenter__(self) -> Self: await self._client.__aenter__() return self - async def __aexit__(self, *exc_details) -> None: + async def __aexit__(self, *exc_details: Any) -> None: await self._client.__aexit__(*exc_details) diff --git a/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/aio/operations/__init__.py b/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/aio/operations/__init__.py index f12431b0cd96..50a5eb52a45c 100644 --- a/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/aio/operations/__init__.py +++ b/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/aio/operations/__init__.py @@ -5,25 +5,27 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._namespaces_operations import NamespacesOperations -from ._hybrid_connections_operations import HybridConnectionsOperations -from ._wcf_relays_operations import WCFRelaysOperations -from ._private_endpoint_connections_operations import PrivateEndpointConnectionsOperations -from ._private_link_resources_operations import PrivateLinkResourcesOperations -from ._operations import Operations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._operations import Operations # type: ignore +from ._namespaces_operations import NamespacesOperations # type: ignore +from ._hybrid_connections_operations import HybridConnectionsOperations # type: ignore +from ._wcf_relays_operations import WCFRelaysOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ + "Operations", "NamespacesOperations", "HybridConnectionsOperations", "WCFRelaysOperations", - "PrivateEndpointConnectionsOperations", - "PrivateLinkResourcesOperations", - "Operations", ] -__all__.extend([p for p in _patch_all if p not in __all__]) +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/aio/operations/_hybrid_connections_operations.py b/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/aio/operations/_hybrid_connections_operations.py index b7abd61c7df8..81d9eba3f776 100644 --- a/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/aio/operations/_hybrid_connections_operations.py +++ b/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/aio/operations/_hybrid_connections_operations.py @@ -6,10 +6,12 @@ # 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, overload +from collections.abc import MutableMapping +from io import IOBase +from typing import Any, Callable, IO, Optional, TypeVar, Union, overload import urllib.parse +from azure.core import AsyncPipelineClient from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, @@ -20,15 +22,14 @@ map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse -from azure.core.rest import HttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models -from ..._vendor import _convert_request +from ..._utils.serialization import Deserializer, Serializer from ...operations._hybrid_connections_operations import ( build_create_or_update_authorization_rule_request, build_create_or_update_request, @@ -41,13 +42,11 @@ build_list_keys_request, build_regenerate_keys_request, ) +from .._configuration import RelayAPIConfiguration -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]] +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] +List = list class HybridConnectionsOperations: @@ -64,37 +63,32 @@ class HybridConnectionsOperations: 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") + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: RelayAPIConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace - def list_authorization_rules( - self, resource_group_name: str, namespace_name: str, hybrid_connection_name: str, **kwargs: Any - ) -> AsyncIterable["_models.AuthorizationRule"]: - """Authorization rules for a hybrid connection. + def list_by_namespace( + self, resource_group_name: str, namespace_name: str, **kwargs: Any + ) -> AsyncItemPaged["_models.HybridConnection"]: + """Lists the hybrid connection within the namespace. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str :param namespace_name: The namespace name. Required. :type namespace_name: str - :param hybrid_connection_name: The hybrid connection name. Required. - :type hybrid_connection_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either AuthorizationRule or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.relay.models.AuthorizationRule] + :return: An iterator like instance of either HybridConnection or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.relay.models.HybridConnection] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - cls = kwargs.pop("cls", None) # type: ClsType[_models.AuthorizationRuleListResult] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.HybridConnectionListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -105,18 +99,15 @@ def list_authorization_rules( def prepare_request(next_link=None): if not next_link: - request = build_list_authorization_rules_request( + _request = build_list_by_namespace_request( resource_group_name=resource_group_name, namespace_name=namespace_name, - hybrid_connection_name=hybrid_connection_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_authorization_rules.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -128,53 +119,53 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _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) # type: ignore - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): - deserialized = self._deserialize("AuthorizationRuleListResult", pipeline_response) + deserialized = self._deserialize("HybridConnectionListResult", 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) + _request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + 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_authorization_rules.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/hybridConnections/{hybridConnectionName}/authorizationRules"} # type: ignore - @overload - async def create_or_update_authorization_rule( + async def create_or_update( self, resource_group_name: str, namespace_name: str, hybrid_connection_name: str, - authorization_rule_name: str, - parameters: _models.AuthorizationRule, + parameters: _models.HybridConnection, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.AuthorizationRule: - """Creates or updates an authorization rule for a hybrid connection. + ) -> _models.HybridConnection: + """Creates or updates a service hybrid connection. This operation is idempotent. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str @@ -182,32 +173,28 @@ async def create_or_update_authorization_rule( :type namespace_name: str :param hybrid_connection_name: The hybrid connection name. Required. :type hybrid_connection_name: str - :param authorization_rule_name: The authorization rule name. Required. - :type authorization_rule_name: str - :param parameters: The authorization rule parameters. Required. - :type parameters: ~azure.mgmt.relay.models.AuthorizationRule + :param parameters: Parameters supplied to create a hybrid connection. Required. + :type parameters: ~azure.mgmt.relay.models.HybridConnection :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: AuthorizationRule or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.AuthorizationRule + :return: HybridConnection or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.HybridConnection :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def create_or_update_authorization_rule( + async def create_or_update( self, resource_group_name: str, namespace_name: str, hybrid_connection_name: str, - authorization_rule_name: str, - parameters: IO, + parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.AuthorizationRule: - """Creates or updates an authorization rule for a hybrid connection. + ) -> _models.HybridConnection: + """Creates or updates a service hybrid connection. This operation is idempotent. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str @@ -215,30 +202,26 @@ async def create_or_update_authorization_rule( :type namespace_name: str :param hybrid_connection_name: The hybrid connection name. Required. :type hybrid_connection_name: str - :param authorization_rule_name: The authorization rule name. Required. - :type authorization_rule_name: str - :param parameters: The authorization rule parameters. Required. - :type parameters: IO + :param parameters: Parameters supplied to create a hybrid connection. Required. + :type parameters: IO[bytes] :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: AuthorizationRule or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.AuthorizationRule + :return: HybridConnection or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.HybridConnection :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async - async def create_or_update_authorization_rule( + async def create_or_update( self, resource_group_name: str, namespace_name: str, hybrid_connection_name: str, - authorization_rule_name: str, - parameters: Union[_models.AuthorizationRule, IO], + parameters: Union[_models.HybridConnection, IO[bytes]], **kwargs: Any - ) -> _models.AuthorizationRule: - """Creates or updates an authorization rule for a hybrid connection. + ) -> _models.HybridConnection: + """Creates or updates a service hybrid connection. This operation is idempotent. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str @@ -246,20 +229,14 @@ async def create_or_update_authorization_rule( :type namespace_name: str :param hybrid_connection_name: The hybrid connection name. Required. :type hybrid_connection_name: str - :param authorization_rule_name: The authorization rule name. Required. - :type authorization_rule_name: str - :param parameters: The authorization rule parameters. Is either a model type or a IO type. - Required. - :type parameters: ~azure.mgmt.relay.models.AuthorizationRule 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: AuthorizationRule or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.AuthorizationRule + :param parameters: Parameters supplied to create a hybrid connection. Is either a + HybridConnection type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.relay.models.HybridConnection or IO[bytes] + :return: HybridConnection or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.HybridConnection :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -270,67 +247,59 @@ async def create_or_update_authorization_rule( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - cls = kwargs.pop("cls", None) # type: ClsType[_models.AuthorizationRule] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.HybridConnection] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(parameters, (IO, bytes)): + if isinstance(parameters, (IOBase, bytes)): _content = parameters else: - _json = self._serialize.body(parameters, "AuthorizationRule") + _json = self._serialize.body(parameters, "HybridConnection") - request = build_create_or_update_authorization_rule_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, namespace_name=namespace_name, hybrid_connection_name=hybrid_connection_name, - authorization_rule_name=authorization_rule_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_authorization_rule.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("AuthorizationRule", pipeline_response) + deserialized = self._deserialize("HybridConnection", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - create_or_update_authorization_rule.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/hybridConnections/{hybridConnectionName}/authorizationRules/{authorizationRuleName}"} # type: ignore + return deserialized # type: ignore @distributed_trace_async - async def delete_authorization_rule( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - namespace_name: str, - hybrid_connection_name: str, - authorization_rule_name: str, - **kwargs: Any + async def delete( + self, resource_group_name: str, namespace_name: str, hybrid_connection_name: str, **kwargs: Any ) -> None: - """Deletes a hybrid connection authorization rule. + """Deletes a hybrid connection. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str @@ -338,14 +307,11 @@ async def delete_authorization_rule( # pylint: disable=inconsistent-return-stat :type namespace_name: str :param hybrid_connection_name: The hybrid connection name. Required. :type hybrid_connection_name: str - :param authorization_rule_name: The authorization rule name. Required. - :type authorization_rule_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -356,51 +322,43 @@ async def delete_authorization_rule( # pylint: disable=inconsistent-return-stat _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - cls = kwargs.pop("cls", None) # type: ClsType[None] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_authorization_rule_request( + _request = build_delete_request( resource_group_name=resource_group_name, namespace_name=namespace_name, hybrid_connection_name=hybrid_connection_name, - authorization_rule_name=authorization_rule_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.delete_authorization_rule.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + 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_authorization_rule.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/hybridConnections/{hybridConnectionName}/authorizationRules/{authorizationRuleName}"} # type: ignore + return cls(pipeline_response, None, {}) # type: ignore @distributed_trace_async - async def get_authorization_rule( - self, - resource_group_name: str, - namespace_name: str, - hybrid_connection_name: str, - authorization_rule_name: str, - **kwargs: Any - ) -> _models.AuthorizationRule: - """Hybrid connection authorization rule for a hybrid connection by name. + async def get( + self, resource_group_name: str, namespace_name: str, hybrid_connection_name: str, **kwargs: Any + ) -> _models.HybridConnection: + """Returns the description for the specified hybrid connection. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str @@ -408,14 +366,11 @@ async def get_authorization_rule( :type namespace_name: str :param hybrid_connection_name: The hybrid connection name. Required. :type hybrid_connection_name: str - :param authorization_rule_name: The authorization rule name. Required. - :type authorization_rule_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: AuthorizationRule or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.AuthorizationRule + :return: HybridConnection or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.HybridConnection :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -426,55 +381,47 @@ async def get_authorization_rule( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - cls = kwargs.pop("cls", None) # type: ClsType[_models.AuthorizationRule] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.HybridConnection] = kwargs.pop("cls", None) - request = build_get_authorization_rule_request( + _request = build_get_request( resource_group_name=resource_group_name, namespace_name=namespace_name, hybrid_connection_name=hybrid_connection_name, - authorization_rule_name=authorization_rule_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get_authorization_rule.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("AuthorizationRule", pipeline_response) + deserialized = self._deserialize("HybridConnection", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get_authorization_rule.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/hybridConnections/{hybridConnectionName}/authorizationRules/{authorizationRuleName}"} # type: ignore + return deserialized # type: ignore - @distributed_trace_async - async def list_keys( - self, - resource_group_name: str, - namespace_name: str, - hybrid_connection_name: str, - authorization_rule_name: str, - **kwargs: Any - ) -> _models.AccessKeys: - """Primary and secondary connection strings to the hybrid connection. + @distributed_trace + def list_authorization_rules( + self, resource_group_name: str, namespace_name: str, hybrid_connection_name: str, **kwargs: Any + ) -> AsyncItemPaged["_models.AuthorizationRule"]: + """Authorization rules for a hybrid connection. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str @@ -482,14 +429,17 @@ async def list_keys( :type namespace_name: str :param hybrid_connection_name: The hybrid connection name. Required. :type hybrid_connection_name: str - :param authorization_rule_name: The authorization rule name. Required. - :type authorization_rule_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: AccessKeys or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.AccessKeys + :return: An iterator like instance of either AuthorizationRule or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.relay.models.AuthorizationRule] :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.AuthorizationRuleListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -497,61 +447,78 @@ async def list_keys( } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessKeys] + def prepare_request(next_link=None): + if not next_link: - request = build_list_keys_request( - resource_group_name=resource_group_name, - namespace_name=namespace_name, - hybrid_connection_name=hybrid_connection_name, - authorization_rule_name=authorization_rule_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - template_url=self.list_keys.metadata["url"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request = build_list_authorization_rules_request( + resource_group_name=resource_group_name, + namespace_name=namespace_name, + hybrid_connection_name=hybrid_connection_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs - ) + 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.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request - response = pipeline_response.http_response + async def extract_data(pipeline_response): + deserialized = self._deserialize("AuthorizationRuleListResult", 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) - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + async def get_next(next_link=None): + _request = prepare_request(next_link) - deserialized = self._deserialize("AccessKeys", pipeline_response) + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response - if cls: - return cls(pipeline_response, deserialized, {}) + if response.status_code not in [200]: + map_error(status_code=response.status_code, 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 deserialized + return pipeline_response - list_keys.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/hybridConnections/{hybridConnectionName}/authorizationRules/{authorizationRuleName}/listKeys"} # type: ignore + return AsyncItemPaged(get_next, extract_data) @overload - async def regenerate_keys( + async def create_or_update_authorization_rule( self, resource_group_name: str, namespace_name: str, hybrid_connection_name: str, authorization_rule_name: str, - parameters: _models.RegenerateAccessKeyParameters, + parameters: _models.AuthorizationRule, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.AccessKeys: - """Regenerates the primary or secondary connection strings to the hybrid connection. + ) -> _models.AuthorizationRule: + """Creates or updates an authorization rule for a hybrid connection. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str @@ -561,30 +528,29 @@ async def regenerate_keys( :type hybrid_connection_name: str :param authorization_rule_name: The authorization rule name. Required. :type authorization_rule_name: str - :param parameters: Parameters supplied to regenerate authorization rule. Required. - :type parameters: ~azure.mgmt.relay.models.RegenerateAccessKeyParameters + :param parameters: The authorization rule parameters. Required. + :type parameters: ~azure.mgmt.relay.models.AuthorizationRule :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: AccessKeys or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.AccessKeys + :return: AuthorizationRule or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.AuthorizationRule :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def regenerate_keys( + async def create_or_update_authorization_rule( self, resource_group_name: str, namespace_name: str, hybrid_connection_name: str, authorization_rule_name: str, - parameters: IO, + parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.AccessKeys: - """Regenerates the primary or secondary connection strings to the hybrid connection. + ) -> _models.AuthorizationRule: + """Creates or updates an authorization rule for a hybrid connection. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str @@ -594,28 +560,27 @@ async def regenerate_keys( :type hybrid_connection_name: str :param authorization_rule_name: The authorization rule name. Required. :type authorization_rule_name: str - :param parameters: Parameters supplied to regenerate authorization rule. Required. - :type parameters: IO + :param parameters: The authorization rule parameters. Required. + :type parameters: IO[bytes] :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: AccessKeys or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.AccessKeys + :return: AuthorizationRule or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.AuthorizationRule :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async - async def regenerate_keys( + async def create_or_update_authorization_rule( self, resource_group_name: str, namespace_name: str, hybrid_connection_name: str, authorization_rule_name: str, - parameters: Union[_models.RegenerateAccessKeyParameters, IO], + parameters: Union[_models.AuthorizationRule, IO[bytes]], **kwargs: Any - ) -> _models.AccessKeys: - """Regenerates the primary or secondary connection strings to the hybrid connection. + ) -> _models.AuthorizationRule: + """Creates or updates an authorization rule for a hybrid connection. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str @@ -625,18 +590,14 @@ async def regenerate_keys( :type hybrid_connection_name: str :param authorization_rule_name: The authorization rule name. Required. :type authorization_rule_name: str - :param parameters: Parameters supplied to regenerate authorization rule. Is either a model type - or a IO type. Required. - :type parameters: ~azure.mgmt.relay.models.RegenerateAccessKeyParameters 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: AccessKeys or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.AccessKeys + :param parameters: The authorization rule parameters. Is either a AuthorizationRule type or a + IO[bytes] type. Required. + :type parameters: ~azure.mgmt.relay.models.AuthorizationRule or IO[bytes] + :return: AuthorizationRule or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.AuthorizationRule :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -647,21 +608,19 @@ async def regenerate_keys( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessKeys] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.AuthorizationRule] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(parameters, (IO, bytes)): + if isinstance(parameters, (IOBase, bytes)): _content = parameters else: - _json = self._serialize.body(parameters, "RegenerateAccessKeyParameters") + _json = self._serialize.body(parameters, "AuthorizationRule") - request = build_regenerate_keys_request( + _request = build_create_or_update_authorization_rule_request( resource_group_name=resource_group_name, namespace_name=namespace_name, hybrid_connection_name=hybrid_connection_name, @@ -671,57 +630,57 @@ async def regenerate_keys( content_type=content_type, json=_json, content=_content, - template_url=self.regenerate_keys.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("AccessKeys", pipeline_response) + deserialized = self._deserialize("AuthorizationRule", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized + return deserialized # type: ignore - regenerate_keys.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/hybridConnections/{hybridConnectionName}/authorizationRules/{authorizationRuleName}/regenerateKeys"} # type: ignore - - @distributed_trace - def list_by_namespace( - self, resource_group_name: str, namespace_name: str, **kwargs: Any - ) -> AsyncIterable["_models.HybridConnection"]: - """Lists the hybrid connection within the namespace. + @distributed_trace_async + async def delete_authorization_rule( + self, + resource_group_name: str, + namespace_name: str, + hybrid_connection_name: str, + authorization_rule_name: str, + **kwargs: Any + ) -> None: + """Deletes a hybrid connection authorization rule. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str :param namespace_name: The namespace name. Required. :type namespace_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either HybridConnection or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.relay.models.HybridConnection] + :param hybrid_connection_name: The hybrid connection name. Required. + :type hybrid_connection_name: str + :param authorization_rule_name: The authorization rule name. Required. + :type authorization_rule_name: str + :return: None or the result of cls(response) + :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - cls = kwargs.pop("cls", None) # type: ClsType[_models.HybridConnectionListResult] - - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -729,135 +688,52 @@ def list_by_namespace( } error_map.update(kwargs.pop("error_map", {}) or {}) - def prepare_request(next_link=None): - if not next_link: + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - request = build_list_by_namespace_request( - resource_group_name=resource_group_name, - namespace_name=namespace_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - template_url=self.list_by_namespace.metadata["url"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) - 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) # type: ignore - request.method = "GET" - return request + _request = build_delete_authorization_rule_request( + resource_group_name=resource_group_name, + namespace_name=namespace_name, + hybrid_connection_name=hybrid_connection_name, + authorization_rule_name=authorization_rule_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) - async def extract_data(pipeline_response): - deserialized = self._deserialize("HybridConnectionListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) - return deserialized.next_link or None, AsyncList(list_of_elem) + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) - async def get_next(next_link=None): - request = prepare_request(next_link) + response = pipeline_response.http_response - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, 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_namespace.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/hybridConnections"} # type: ignore - - @overload - async def create_or_update( - self, - resource_group_name: str, - namespace_name: str, - hybrid_connection_name: str, - parameters: _models.HybridConnection, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.HybridConnection: - """Creates or updates a service hybrid connection. This operation is idempotent. - - :param resource_group_name: Name of the Resource group within the Azure subscription. Required. - :type resource_group_name: str - :param namespace_name: The namespace name. Required. - :type namespace_name: str - :param hybrid_connection_name: The hybrid connection name. Required. - :type hybrid_connection_name: str - :param parameters: Parameters supplied to create a hybrid connection. Required. - :type parameters: ~azure.mgmt.relay.models.HybridConnection - :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: HybridConnection or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.HybridConnection - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_or_update( - self, - resource_group_name: str, - namespace_name: str, - hybrid_connection_name: str, - parameters: IO, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.HybridConnection: - """Creates or updates a service hybrid connection. This operation is idempotent. + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - :param resource_group_name: Name of the Resource group within the Azure subscription. Required. - :type resource_group_name: str - :param namespace_name: The namespace name. Required. - :type namespace_name: str - :param hybrid_connection_name: The hybrid connection name. Required. - :type hybrid_connection_name: str - :param parameters: Parameters supplied to create a hybrid connection. Required. - :type parameters: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: HybridConnection or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.HybridConnection - :raises ~azure.core.exceptions.HttpResponseError: - """ + if cls: + return cls(pipeline_response, None, {}) # type: ignore @distributed_trace_async - async def create_or_update( + async def get_authorization_rule( self, resource_group_name: str, namespace_name: str, hybrid_connection_name: str, - parameters: Union[_models.HybridConnection, IO], + authorization_rule_name: str, **kwargs: Any - ) -> _models.HybridConnection: - """Creates or updates a service hybrid connection. This operation is idempotent. + ) -> _models.AuthorizationRule: + """Hybrid connection authorization rule for a hybrid connection by name. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str @@ -865,18 +741,13 @@ async def create_or_update( :type namespace_name: str :param hybrid_connection_name: The hybrid connection name. Required. :type hybrid_connection_name: str - :param parameters: Parameters supplied to create a hybrid connection. Is either a model type or - a IO type. Required. - :type parameters: ~azure.mgmt.relay.models.HybridConnection 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: HybridConnection or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.HybridConnection + :param authorization_rule_name: The authorization rule name. Required. + :type authorization_rule_name: str + :return: AuthorizationRule or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.AuthorizationRule :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -884,64 +755,56 @@ async def create_or_update( } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - cls = kwargs.pop("cls", None) # type: ClsType[_models.HybridConnection] - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IO, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "HybridConnection") + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.AuthorizationRule] = kwargs.pop("cls", None) - request = build_create_or_update_request( + _request = build_get_authorization_rule_request( resource_group_name=resource_group_name, namespace_name=namespace_name, hybrid_connection_name=hybrid_connection_name, + authorization_rule_name=authorization_rule_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.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("HybridConnection", pipeline_response) + deserialized = self._deserialize("AuthorizationRule", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/hybridConnections/{hybridConnectionName}"} # type: ignore + return deserialized # type: ignore @distributed_trace_async - async def delete( # pylint: disable=inconsistent-return-statements - self, resource_group_name: str, namespace_name: str, hybrid_connection_name: str, **kwargs: Any - ) -> None: - """Deletes a hybrid connection. + async def list_keys( + self, + resource_group_name: str, + namespace_name: str, + hybrid_connection_name: str, + authorization_rule_name: str, + **kwargs: Any + ) -> _models.AccessKeys: + """Primary and secondary connection strings to the hybrid connection. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str @@ -949,12 +812,13 @@ async def delete( # pylint: disable=inconsistent-return-statements :type namespace_name: str :param hybrid_connection_name: The hybrid connection name. Required. :type hybrid_connection_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: None or the result of cls(response) - :rtype: None + :param authorization_rule_name: The authorization rule name. Required. + :type authorization_rule_name: str + :return: AccessKeys or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.AccessKeys :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -965,45 +829,118 @@ async def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - cls = kwargs.pop("cls", None) # type: ClsType[None] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.AccessKeys] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_list_keys_request( resource_group_name=resource_group_name, namespace_name=namespace_name, hybrid_connection_name=hybrid_connection_name, + authorization_rule_name=authorization_rule_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.delete.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response - if response.status_code not in [200, 204]: + if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + deserialized = self._deserialize("AccessKeys", pipeline_response.http_response) + if cls: - return cls(pipeline_response, None, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore - delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/hybridConnections/{hybridConnectionName}"} # type: ignore + @overload + async def regenerate_keys( + self, + resource_group_name: str, + namespace_name: str, + hybrid_connection_name: str, + authorization_rule_name: str, + parameters: _models.RegenerateAccessKeyParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.AccessKeys: + """Regenerates the primary or secondary connection strings to the hybrid connection. + + :param resource_group_name: Name of the Resource group within the Azure subscription. Required. + :type resource_group_name: str + :param namespace_name: The namespace name. Required. + :type namespace_name: str + :param hybrid_connection_name: The hybrid connection name. Required. + :type hybrid_connection_name: str + :param authorization_rule_name: The authorization rule name. Required. + :type authorization_rule_name: str + :param parameters: Parameters supplied to regenerate authorization rule. Required. + :type parameters: ~azure.mgmt.relay.models.RegenerateAccessKeyParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: AccessKeys or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.AccessKeys + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def regenerate_keys( + self, + resource_group_name: str, + namespace_name: str, + hybrid_connection_name: str, + authorization_rule_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.AccessKeys: + """Regenerates the primary or secondary connection strings to the hybrid connection. + + :param resource_group_name: Name of the Resource group within the Azure subscription. Required. + :type resource_group_name: str + :param namespace_name: The namespace name. Required. + :type namespace_name: str + :param hybrid_connection_name: The hybrid connection name. Required. + :type hybrid_connection_name: str + :param authorization_rule_name: The authorization rule name. Required. + :type authorization_rule_name: str + :param parameters: Parameters supplied to regenerate authorization rule. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: AccessKeys or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.AccessKeys + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace_async - async def get( - self, resource_group_name: str, namespace_name: str, hybrid_connection_name: str, **kwargs: Any - ) -> _models.HybridConnection: - """Returns the description for the specified hybrid connection. + async def regenerate_keys( + self, + resource_group_name: str, + namespace_name: str, + hybrid_connection_name: str, + authorization_rule_name: str, + parameters: Union[_models.RegenerateAccessKeyParameters, IO[bytes]], + **kwargs: Any + ) -> _models.AccessKeys: + """Regenerates the primary or secondary connection strings to the hybrid connection. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str @@ -1011,12 +948,16 @@ async def get( :type namespace_name: str :param hybrid_connection_name: The hybrid connection name. Required. :type hybrid_connection_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: HybridConnection or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.HybridConnection + :param authorization_rule_name: The authorization rule name. Required. + :type authorization_rule_name: str + :param parameters: Parameters supplied to regenerate authorization rule. Is either a + RegenerateAccessKeyParameters type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.relay.models.RegenerateAccessKeyParameters or IO[bytes] + :return: AccessKeys or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.AccessKeys :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1024,43 +965,54 @@ async def get( } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = kwargs.pop("headers", {}) or {} + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - cls = kwargs.pop("cls", None) # type: ClsType[_models.HybridConnection] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.AccessKeys] = kwargs.pop("cls", None) - request = build_get_request( + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "RegenerateAccessKeyParameters") + + _request = build_regenerate_keys_request( resource_group_name=resource_group_name, namespace_name=namespace_name, hybrid_connection_name=hybrid_connection_name, + authorization_rule_name=authorization_rule_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata["url"], + content_type=content_type, + json=_json, + content=_content, headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("HybridConnection", pipeline_response) + deserialized = self._deserialize("AccessKeys", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/hybridConnections/{hybridConnectionName}"} # type: ignore + return deserialized # type: ignore diff --git a/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/aio/operations/_namespaces_operations.py b/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/aio/operations/_namespaces_operations.py index 8b0193d70a36..13048899ce69 100644 --- a/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/aio/operations/_namespaces_operations.py +++ b/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/aio/operations/_namespaces_operations.py @@ -6,10 +6,12 @@ # 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 +from collections.abc import MutableMapping +from io import IOBase +from typing import Any, AsyncIterator, Callable, IO, Optional, TypeVar, Union, cast, overload import urllib.parse +from azure.core import AsyncPipelineClient from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, @@ -17,12 +19,13 @@ ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, 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.rest import AsyncHttpResponse, 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 @@ -30,16 +33,14 @@ from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models -from ..._vendor import _convert_request +from ..._utils.serialization import Deserializer, Serializer from ...operations._namespaces_operations import ( build_check_name_availability_request, build_create_or_update_authorization_rule_request, - build_create_or_update_network_rule_set_request, build_create_or_update_request, build_delete_authorization_rule_request, build_delete_request, build_get_authorization_rule_request, - build_get_network_rule_set_request, build_get_request, build_list_authorization_rules_request, build_list_by_resource_group_request, @@ -48,13 +49,11 @@ build_regenerate_keys_request, build_update_request, ) +from .._configuration import RelayAPIConfiguration -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]] +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] +List = list class NamespacesOperations: @@ -71,190 +70,57 @@ class NamespacesOperations: 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_authorization_rules( - self, resource_group_name: str, namespace_name: str, **kwargs: Any - ) -> AsyncIterable["_models.AuthorizationRule"]: - """Authorization rules for a namespace. - - :param resource_group_name: Name of the Resource group within the Azure subscription. Required. - :type resource_group_name: str - :param namespace_name: The namespace name. Required. - :type namespace_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either AuthorizationRule or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.relay.models.AuthorizationRule] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - cls = kwargs.pop("cls", None) # type: ClsType[_models.AuthorizationRuleListResult] - - 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_authorization_rules_request( - resource_group_name=resource_group_name, - namespace_name=namespace_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - template_url=self.list_authorization_rules.metadata["url"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore - - 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) # type: ignore - request.method = "GET" - return request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("AuthorizationRuleListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) - return deserialized.next_link or None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - request = prepare_request(next_link) - - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - list_authorization_rules.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/authorizationRules"} # type: ignore + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: RelayAPIConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") @overload - async def create_or_update_authorization_rule( - self, - resource_group_name: str, - namespace_name: str, - authorization_rule_name: str, - parameters: _models.AuthorizationRule, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.AuthorizationRule: - """Creates or updates an authorization rule for a namespace. + async def check_name_availability( + self, parameters: _models.CheckNameAvailability, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.CheckNameAvailabilityResult: + """Check the specified namespace name availability. - :param resource_group_name: Name of the Resource group within the Azure subscription. Required. - :type resource_group_name: str - :param namespace_name: The namespace name. Required. - :type namespace_name: str - :param authorization_rule_name: The authorization rule name. Required. - :type authorization_rule_name: str - :param parameters: The authorization rule parameters. Required. - :type parameters: ~azure.mgmt.relay.models.AuthorizationRule + :param parameters: Parameters to check availability of the specified namespace name. Required. + :type parameters: ~azure.mgmt.relay.models.CheckNameAvailability :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: AuthorizationRule or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.AuthorizationRule + :return: CheckNameAvailabilityResult or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.CheckNameAvailabilityResult :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def create_or_update_authorization_rule( - self, - resource_group_name: str, - namespace_name: str, - authorization_rule_name: str, - parameters: IO, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.AuthorizationRule: - """Creates or updates an authorization rule for a namespace. + async def check_name_availability( + self, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.CheckNameAvailabilityResult: + """Check the specified namespace name availability. - :param resource_group_name: Name of the Resource group within the Azure subscription. Required. - :type resource_group_name: str - :param namespace_name: The namespace name. Required. - :type namespace_name: str - :param authorization_rule_name: The authorization rule name. Required. - :type authorization_rule_name: str - :param parameters: The authorization rule parameters. Required. - :type parameters: IO + :param parameters: Parameters to check availability of the specified namespace name. Required. + :type parameters: IO[bytes] :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: AuthorizationRule or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.AuthorizationRule + :return: CheckNameAvailabilityResult or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.CheckNameAvailabilityResult :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async - async def create_or_update_authorization_rule( - self, - resource_group_name: str, - namespace_name: str, - authorization_rule_name: str, - parameters: Union[_models.AuthorizationRule, IO], - **kwargs: Any - ) -> _models.AuthorizationRule: - """Creates or updates an authorization rule for a namespace. + async def check_name_availability( + self, parameters: Union[_models.CheckNameAvailability, IO[bytes]], **kwargs: Any + ) -> _models.CheckNameAvailabilityResult: + """Check the specified namespace name availability. - :param resource_group_name: Name of the Resource group within the Azure subscription. Required. - :type resource_group_name: str - :param namespace_name: The namespace name. Required. - :type namespace_name: str - :param authorization_rule_name: The authorization rule name. Required. - :type authorization_rule_name: str - :param parameters: The authorization rule parameters. Is either a model type or a IO type. - Required. - :type parameters: ~azure.mgmt.relay.models.AuthorizationRule 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: AuthorizationRule or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.AuthorizationRule + :param parameters: Parameters to check availability of the specified namespace name. Is either + a CheckNameAvailability type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.relay.models.CheckNameAvailability or IO[bytes] + :return: CheckNameAvailabilityResult or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.CheckNameAvailabilityResult :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -265,74 +131,66 @@ async def create_or_update_authorization_rule( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - cls = kwargs.pop("cls", None) # type: ClsType[_models.AuthorizationRule] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.CheckNameAvailabilityResult] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(parameters, (IO, bytes)): + if isinstance(parameters, (IOBase, bytes)): _content = parameters else: - _json = self._serialize.body(parameters, "AuthorizationRule") + _json = self._serialize.body(parameters, "CheckNameAvailability") - request = build_create_or_update_authorization_rule_request( - resource_group_name=resource_group_name, - namespace_name=namespace_name, - authorization_rule_name=authorization_rule_name, + _request = build_check_name_availability_request( subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, content=_content, - template_url=self.create_or_update_authorization_rule.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("AuthorizationRule", pipeline_response) + deserialized = self._deserialize("CheckNameAvailabilityResult", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - create_or_update_authorization_rule.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/authorizationRules/{authorizationRuleName}"} # type: ignore + return deserialized # type: ignore - @distributed_trace_async - async def delete_authorization_rule( # pylint: disable=inconsistent-return-statements - self, resource_group_name: str, namespace_name: str, authorization_rule_name: str, **kwargs: Any - ) -> None: - """Deletes a namespace authorization rule. + @distributed_trace + def list(self, **kwargs: Any) -> AsyncItemPaged["_models.RelayNamespace"]: + """Lists all the available namespaces within the subscription regardless of the resourceGroups. - :param resource_group_name: Name of the Resource group within the Azure subscription. Required. - :type resource_group_name: str - :param namespace_name: The namespace name. Required. - :type namespace_name: str - :param authorization_rule_name: The authorization rule name. Required. - :type authorization_rule_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: None or the result of cls(response) - :rtype: None + :return: An iterator like instance of either RelayNamespace or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.relay.models.RelayNamespace] :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.RelayNamespaceListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -340,61 +198,81 @@ async def delete_authorization_rule( # pylint: disable=inconsistent-return-stat } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + def prepare_request(next_link=None): + if not next_link: - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - cls = kwargs.pop("cls", None) # type: ClsType[None] + _request = build_list_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) - request = build_delete_authorization_rule_request( - resource_group_name=resource_group_name, - namespace_name=namespace_name, - authorization_rule_name=authorization_rule_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - template_url=self.delete_authorization_rule.metadata["url"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + 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.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs - ) + async def extract_data(pipeline_response): + deserialized = self._deserialize("RelayNamespaceListResult", 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) - response = pipeline_response.http_response + async def get_next(next_link=None): + _request = prepare_request(next_link) - if response.status_code not in [200, 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) + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response - if cls: - return cls(pipeline_response, None, {}) + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - delete_authorization_rule.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/authorizationRules/{authorizationRuleName}"} # type: ignore + return pipeline_response - @distributed_trace_async - async def get_authorization_rule( - self, resource_group_name: str, namespace_name: str, authorization_rule_name: str, **kwargs: Any - ) -> _models.AuthorizationRule: - """Authorization rule for a namespace by name. + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace + def list_by_resource_group( + self, resource_group_name: str, **kwargs: Any + ) -> AsyncItemPaged["_models.RelayNamespace"]: + """Lists all the available namespaces within the ResourceGroup. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str - :param namespace_name: The namespace name. Required. - :type namespace_name: str - :param authorization_rule_name: The authorization rule name. Required. - :type authorization_rule_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: AuthorizationRule or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.AuthorizationRule + :return: An iterator like instance of either RelayNamespace or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.relay.models.RelayNamespace] :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.RelayNamespaceListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -402,65 +280,71 @@ async def get_authorization_rule( } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - cls = kwargs.pop("cls", None) # type: ClsType[_models.AuthorizationRule] - - request = build_get_authorization_rule_request( - resource_group_name=resource_group_name, - namespace_name=namespace_name, - authorization_rule_name=authorization_rule_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - template_url=self.get_authorization_rule.metadata["url"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore - - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs - ) + def prepare_request(next_link=None): + if not next_link: - response = pipeline_response.http_response + _request = build_list_by_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + 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.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request - deserialized = self._deserialize("AuthorizationRule", pipeline_response) + async def extract_data(pipeline_response): + deserialized = self._deserialize("RelayNamespaceListResult", 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) - if cls: - return cls(pipeline_response, deserialized, {}) + async def get_next(next_link=None): + _request = prepare_request(next_link) - return deserialized + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response - get_authorization_rule.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/authorizationRules/{authorizationRuleName}"} # type: ignore + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - @distributed_trace_async - async def list_keys( - self, resource_group_name: str, namespace_name: str, authorization_rule_name: str, **kwargs: Any - ) -> _models.AccessKeys: - """Primary and secondary connection strings to the namespace. + return pipeline_response - :param resource_group_name: Name of the Resource group within the Azure subscription. Required. - :type resource_group_name: str - :param namespace_name: The namespace name. Required. - :type namespace_name: str - :param authorization_rule_name: The authorization rule name. Required. - :type authorization_rule_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: AccessKeys or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.AccessKeys - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map = { + return AsyncItemPaged(get_next, extract_data) + + async def _create_or_update_initial( + self, + resource_group_name: str, + namespace_name: str, + parameters: Union[_models.RelayNamespace, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -468,136 +352,188 @@ async def list_keys( } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = kwargs.pop("headers", {}) or {} + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessKeys] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "RelayNamespace") - request = build_list_keys_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, namespace_name=namespace_name, - authorization_rule_name=authorization_rule_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_keys.metadata["url"], + content_type=content_type, + json=_json, + content=_content, headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response - if response.status_code not in [200]: + if response.status_code not in [200, 201]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("AccessKeys", pipeline_response) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - list_keys.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/authorizationRules/{authorizationRuleName}/listKeys"} # type: ignore + return deserialized # type: ignore @overload - async def regenerate_keys( + async def begin_create_or_update( self, resource_group_name: str, namespace_name: str, - authorization_rule_name: str, - parameters: _models.RegenerateAccessKeyParameters, + parameters: _models.RelayNamespace, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.AccessKeys: - """Regenerates the primary or secondary connection strings to the namespace. + ) -> AsyncLROPoller[_models.RelayNamespace]: + """Create Azure Relay namespace. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str :param namespace_name: The namespace name. Required. :type namespace_name: str - :param authorization_rule_name: The authorization rule name. Required. - :type authorization_rule_name: str - :param parameters: Parameters supplied to regenerate authorization rule. Required. - :type parameters: ~azure.mgmt.relay.models.RegenerateAccessKeyParameters + :param parameters: Parameters supplied to create a namespace resource. Required. + :type parameters: ~azure.mgmt.relay.models.RelayNamespace :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: AccessKeys or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.AccessKeys + :return: An instance of AsyncLROPoller that returns either RelayNamespace or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.relay.models.RelayNamespace] :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def regenerate_keys( + async def begin_create_or_update( self, resource_group_name: str, namespace_name: str, - authorization_rule_name: str, - parameters: IO, + parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.AccessKeys: - """Regenerates the primary or secondary connection strings to the namespace. + ) -> AsyncLROPoller[_models.RelayNamespace]: + """Create Azure Relay namespace. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str :param namespace_name: The namespace name. Required. :type namespace_name: str - :param authorization_rule_name: The authorization rule name. Required. - :type authorization_rule_name: str - :param parameters: Parameters supplied to regenerate authorization rule. Required. - :type parameters: IO + :param parameters: Parameters supplied to create a namespace resource. Required. + :type parameters: IO[bytes] :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: AccessKeys or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.AccessKeys + :return: An instance of AsyncLROPoller that returns either RelayNamespace or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.relay.models.RelayNamespace] :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async - async def regenerate_keys( + async def begin_create_or_update( self, resource_group_name: str, namespace_name: str, - authorization_rule_name: str, - parameters: Union[_models.RegenerateAccessKeyParameters, IO], + parameters: Union[_models.RelayNamespace, IO[bytes]], **kwargs: Any - ) -> _models.AccessKeys: - """Regenerates the primary or secondary connection strings to the namespace. + ) -> AsyncLROPoller[_models.RelayNamespace]: + """Create Azure Relay namespace. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str :param namespace_name: The namespace name. Required. :type namespace_name: str - :param authorization_rule_name: The authorization rule name. Required. - :type authorization_rule_name: str - :param parameters: Parameters supplied to regenerate authorization rule. Is either a model type - or a IO type. Required. - :type parameters: ~azure.mgmt.relay.models.RegenerateAccessKeyParameters 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: AccessKeys or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.AccessKeys + :param parameters: Parameters supplied to create a namespace resource. Is either a + RelayNamespace type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.relay.models.RelayNamespace or IO[bytes] + :return: An instance of AsyncLROPoller that returns either RelayNamespace or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.relay.models.RelayNamespace] :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.RelayNamespace] = 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, + namespace_name=namespace_name, + parameters=parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("RelayNamespace", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + 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[_models.RelayNamespace].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.RelayNamespace]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + async def _delete_initial( + self, resource_group_name: str, namespace_name: str, **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -605,111 +541,237 @@ async def regenerate_keys( } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessKeys] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IO, bytes)): - _content = parameters + _request = build_delete_request( + resource_group_name=resource_group_name, + namespace_name=namespace_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 202, 204]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, 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 = response.stream_download(self._client._pipeline, decompress=_decompress) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def begin_delete(self, resource_group_name: str, namespace_name: str, **kwargs: Any) -> AsyncLROPoller[None]: + """Deletes an existing namespace. This operation also removes all associated resources under the + namespace. + + :param resource_group_name: Name of the Resource group within the Azure subscription. Required. + :type resource_group_name: str + :param namespace_name: The namespace name. Required. + :type namespace_name: str + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._delete_initial( + resource_group_name=resource_group_name, + namespace_name=namespace_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + if polling is True: + polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) else: - _json = self._serialize.body(parameters, "RegenerateAccessKeyParameters") + polling_method = polling + if cont_token: + return AsyncLROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + @distributed_trace_async + async def get(self, resource_group_name: str, namespace_name: str, **kwargs: Any) -> _models.RelayNamespace: + """Returns the description for the specified namespace. + + :param resource_group_name: Name of the Resource group within the Azure subscription. Required. + :type resource_group_name: str + :param namespace_name: The namespace name. Required. + :type namespace_name: str + :return: RelayNamespace or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.RelayNamespace + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 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 {}) - request = build_regenerate_keys_request( + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.RelayNamespace] = kwargs.pop("cls", None) + + _request = build_get_request( resource_group_name=resource_group_name, namespace_name=namespace_name, - authorization_rule_name=authorization_rule_name, subscription_id=self._config.subscription_id, api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - template_url=self.regenerate_keys.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("AccessKeys", pipeline_response) + deserialized = self._deserialize("RelayNamespace", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - regenerate_keys.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/authorizationRules/{authorizationRuleName}/regenerateKeys"} # type: ignore + return deserialized # type: ignore @overload - async def check_name_availability( - self, parameters: _models.CheckNameAvailability, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.CheckNameAvailabilityResult: - """Check the specified namespace name availability. + async def update( + self, + resource_group_name: str, + namespace_name: str, + parameters: _models.RelayUpdateParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RelayNamespace: + """Creates or updates a namespace. Once created, this namespace's resource manifest is immutable. + This operation is idempotent. - :param parameters: Parameters to check availability of the specified namespace name. Required. - :type parameters: ~azure.mgmt.relay.models.CheckNameAvailability + :param resource_group_name: Name of the Resource group within the Azure subscription. Required. + :type resource_group_name: str + :param namespace_name: The namespace name. Required. + :type namespace_name: str + :param parameters: Parameters for updating a namespace resource. Required. + :type parameters: ~azure.mgmt.relay.models.RelayUpdateParameters :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: CheckNameAvailabilityResult or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.CheckNameAvailabilityResult + :return: RelayNamespace or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.RelayNamespace :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def check_name_availability( - self, parameters: IO, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.CheckNameAvailabilityResult: - """Check the specified namespace name availability. + async def update( + self, + resource_group_name: str, + namespace_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RelayNamespace: + """Creates or updates a namespace. Once created, this namespace's resource manifest is immutable. + This operation is idempotent. - :param parameters: Parameters to check availability of the specified namespace name. Required. - :type parameters: IO + :param resource_group_name: Name of the Resource group within the Azure subscription. Required. + :type resource_group_name: str + :param namespace_name: The namespace name. Required. + :type namespace_name: str + :param parameters: Parameters for updating a namespace resource. Required. + :type parameters: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: CheckNameAvailabilityResult or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.CheckNameAvailabilityResult + :return: RelayNamespace or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.RelayNamespace :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async - async def check_name_availability( - self, parameters: Union[_models.CheckNameAvailability, IO], **kwargs: Any - ) -> _models.CheckNameAvailabilityResult: - """Check the specified namespace name availability. + async def update( + self, + resource_group_name: str, + namespace_name: str, + parameters: Union[_models.RelayUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> _models.RelayNamespace: + """Creates or updates a namespace. Once created, this namespace's resource manifest is immutable. + This operation is idempotent. - :param parameters: Parameters to check availability of the specified namespace name. Is either - a model type or a IO type. Required. - :type parameters: ~azure.mgmt.relay.models.CheckNameAvailability or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: CheckNameAvailabilityResult or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.CheckNameAvailabilityResult + :param resource_group_name: Name of the Resource group within the Azure subscription. Required. + :type resource_group_name: str + :param namespace_name: The namespace name. Required. + :type namespace_name: str + :param parameters: Parameters for updating a namespace resource. Is either a + RelayUpdateParameters type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.relay.models.RelayUpdateParameters or IO[bytes] + :return: RelayNamespace or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.RelayNamespace :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -720,157 +782,74 @@ async def check_name_availability( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - cls = kwargs.pop("cls", None) # type: ClsType[_models.CheckNameAvailabilityResult] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.RelayNamespace] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(parameters, (IO, bytes)): + if isinstance(parameters, (IOBase, bytes)): _content = parameters else: - _json = self._serialize.body(parameters, "CheckNameAvailability") + _json = self._serialize.body(parameters, "RelayUpdateParameters") - request = build_check_name_availability_request( + _request = build_update_request( + resource_group_name=resource_group_name, + namespace_name=namespace_name, subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, content=_content, - template_url=self.check_name_availability.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response - if response.status_code not in [200]: + 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) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("CheckNameAvailabilityResult", pipeline_response) + deserialized = self._deserialize("RelayNamespace", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - - check_name_availability.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Relay/checkNameAvailability"} # type: ignore - - @distributed_trace - def list(self, **kwargs: Any) -> AsyncIterable["_models.RelayNamespace"]: - """Lists all the available namespaces within the subscription regardless of the resourceGroups. - - :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RelayNamespace or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.relay.models.RelayNamespace] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - cls = kwargs.pop("cls", None) # type: ClsType[_models.RelayNamespaceListResult] - - 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: + return cls(pipeline_response, deserialized, {}) # type: ignore - 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) # type: ignore - - 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) # type: ignore - request.method = "GET" - return request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("RelayNamespaceListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) - return deserialized.next_link or None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - request = prepare_request(next_link) - - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Relay/namespaces"} # type: ignore + return deserialized # type: ignore @distributed_trace - def list_by_resource_group( - self, resource_group_name: str, **kwargs: Any - ) -> AsyncIterable["_models.RelayNamespace"]: - """Lists all the available namespaces within the ResourceGroup. + def list_authorization_rules( + self, resource_group_name: str, namespace_name: str, **kwargs: Any + ) -> AsyncItemPaged["_models.AuthorizationRule"]: + """Authorization rules for a namespace. :param resource_group_name: Name of the Resource group within the Azure subscription. 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 RelayNamespace or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.relay.models.RelayNamespace] + :param namespace_name: The namespace name. Required. + :type namespace_name: str + :return: An iterator like instance of either AuthorizationRule or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.relay.models.AuthorizationRule] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - cls = kwargs.pop("cls", None) # type: ClsType[_models.RelayNamespaceListResult] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.AuthorizationRuleListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -881,16 +860,15 @@ def list_by_resource_group( def prepare_request(next_link=None): if not next_link: - request = build_list_by_resource_group_request( + _request = build_list_authorization_rules_request( resource_group_name=resource_group_name, + namespace_name=namespace_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) # type: ignore + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -902,266 +880,124 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _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) # type: ignore - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): - deserialized = self._deserialize("RelayNamespaceListResult", pipeline_response) + deserialized = self._deserialize("AuthorizationRuleListResult", 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) + _request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + 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.Relay/namespaces"} # type: ignore - - async def _create_or_update_initial( - self, - resource_group_name: str, - namespace_name: str, - parameters: Union[_models.RelayNamespace, IO], - **kwargs: Any - ) -> _models.RelayNamespace: - error_map = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - cls = kwargs.pop("cls", None) # type: ClsType[_models.RelayNamespace] - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IO, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "RelayNamespace") - - request = build_create_or_update_request( - resource_group_name=resource_group_name, - namespace_name=namespace_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) # type: ignore - - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 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("RelayNamespace", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("RelayNamespace", pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - - _create_or_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}"} # type: ignore - @overload - async def begin_create_or_update( + async def create_or_update_authorization_rule( self, resource_group_name: str, namespace_name: str, - parameters: _models.RelayNamespace, + authorization_rule_name: str, + parameters: _models.AuthorizationRule, *, content_type: str = "application/json", **kwargs: Any - ) -> AsyncLROPoller[_models.RelayNamespace]: - """Create Azure Relay namespace. + ) -> _models.AuthorizationRule: + """Creates or updates an authorization rule for a namespace. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str :param namespace_name: The namespace name. Required. :type namespace_name: str - :param parameters: Parameters supplied to create a namespace resource. Required. - :type parameters: ~azure.mgmt.relay.models.RelayNamespace + :param authorization_rule_name: The authorization rule name. Required. + :type authorization_rule_name: str + :param parameters: The authorization rule parameters. Required. + :type parameters: ~azure.mgmt.relay.models.AuthorizationRule :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 RelayNamespace or the result of - cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.relay.models.RelayNamespace] + :return: AuthorizationRule or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.AuthorizationRule :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def begin_create_or_update( + async def create_or_update_authorization_rule( self, resource_group_name: str, namespace_name: str, - parameters: IO, + authorization_rule_name: str, + parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> AsyncLROPoller[_models.RelayNamespace]: - """Create Azure Relay namespace. + ) -> _models.AuthorizationRule: + """Creates or updates an authorization rule for a namespace. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str :param namespace_name: The namespace name. Required. :type namespace_name: str - :param parameters: Parameters supplied to create a namespace resource. Required. - :type parameters: IO + :param authorization_rule_name: The authorization rule name. Required. + :type authorization_rule_name: str + :param parameters: The authorization rule parameters. Required. + :type parameters: IO[bytes] :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 RelayNamespace or the result of - cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.relay.models.RelayNamespace] + :return: AuthorizationRule or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.AuthorizationRule :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async - async def begin_create_or_update( + async def create_or_update_authorization_rule( self, resource_group_name: str, namespace_name: str, - parameters: Union[_models.RelayNamespace, IO], + authorization_rule_name: str, + parameters: Union[_models.AuthorizationRule, IO[bytes]], **kwargs: Any - ) -> AsyncLROPoller[_models.RelayNamespace]: - """Create Azure Relay namespace. + ) -> _models.AuthorizationRule: + """Creates or updates an authorization rule for a namespace. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str :param namespace_name: The namespace name. Required. :type namespace_name: str - :param parameters: Parameters supplied to create a namespace resource. Is either a model type - or a IO type. Required. - :type parameters: ~azure.mgmt.relay.models.RelayNamespace 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 RelayNamespace or the result of - cls(response) - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.relay.models.RelayNamespace] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - cls = kwargs.pop("cls", None) # type: ClsType[_models.RelayNamespace] - polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] - if cont_token is None: - raw_result = await self._create_or_update_initial( # type: ignore - resource_group_name=resource_group_name, - namespace_name=namespace_name, - parameters=parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("RelayNamespace", pipeline_response) - if cls: - return cls(pipeline_response, deserialized, {}) - return deserialized - - if polling is True: - polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller.from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - - begin_create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}"} # type: ignore - - async def _delete_initial( # pylint: disable=inconsistent-return-statements - self, resource_group_name: str, namespace_name: str, **kwargs: Any - ) -> None: - error_map = { + :param authorization_rule_name: The authorization rule name. Required. + :type authorization_rule_name: str + :param parameters: The authorization rule parameters. Is either a AuthorizationRule type or a + IO[bytes] type. Required. + :type parameters: ~azure.mgmt.relay.models.AuthorizationRule or IO[bytes] + :return: AuthorizationRule or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.AuthorizationRule + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1169,120 +1005,133 @@ async def _delete_initial( # pylint: disable=inconsistent-return-statements } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = kwargs.pop("headers", {}) or {} + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - cls = kwargs.pop("cls", None) # type: ClsType[None] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.AuthorizationRule] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "AuthorizationRule") - request = build_delete_request( + _request = build_create_or_update_authorization_rule_request( resource_group_name=resource_group_name, namespace_name=namespace_name, + authorization_rule_name=authorization_rule_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._delete_initial.metadata["url"], + content_type=content_type, + json=_json, + content=_content, headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response - if response.status_code not in [200, 202, 204]: + if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + deserialized = self._deserialize("AuthorizationRule", pipeline_response.http_response) + if cls: - return cls(pipeline_response, None, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}"} # type: ignore + return deserialized # type: ignore @distributed_trace_async - async def begin_delete(self, resource_group_name: str, namespace_name: str, **kwargs: Any) -> AsyncLROPoller[None]: - """Deletes an existing namespace. This operation also removes all associated resources under the - namespace. + async def delete_authorization_rule( + self, resource_group_name: str, namespace_name: str, authorization_rule_name: str, **kwargs: Any + ) -> None: + """Deletes a namespace authorization rule. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str :param namespace_name: The namespace name. Required. :type namespace_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] + :param authorization_rule_name: The authorization rule name. Required. + :type authorization_rule_name: str + :return: None or the result of cls(response) + :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - cls = kwargs.pop("cls", None) # type: ClsType[None] - polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] - if cont_token is None: - raw_result = await self._delete_initial( # type: ignore - resource_group_name=resource_group_name, - namespace_name=namespace_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - kwargs.pop("error_map", None) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) + _request = build_delete_authorization_rule_request( + resource_group_name=resource_group_name, + namespace_name=namespace_name, + authorization_rule_name=authorization_rule_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) - if polling is True: - polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller.from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}"} # type: ignore + if cls: + return cls(pipeline_response, None, {}) # type: ignore @distributed_trace_async - async def get(self, resource_group_name: str, namespace_name: str, **kwargs: Any) -> _models.RelayNamespace: - """Returns the description for the specified namespace. + async def get_authorization_rule( + self, resource_group_name: str, namespace_name: str, authorization_rule_name: str, **kwargs: Any + ) -> _models.AuthorizationRule: + """Authorization rule for a namespace by name. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str :param namespace_name: The namespace name. Required. :type namespace_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: RelayNamespace or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.RelayNamespace + :param authorization_rule_name: The authorization rule name. Required. + :type authorization_rule_name: str + :return: AuthorizationRule or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.AuthorizationRule :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1293,126 +1142,59 @@ async def get(self, resource_group_name: str, namespace_name: str, **kwargs: Any _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - cls = kwargs.pop("cls", None) # type: ClsType[_models.RelayNamespace] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.AuthorizationRule] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_authorization_rule_request( resource_group_name=resource_group_name, namespace_name=namespace_name, + authorization_rule_name=authorization_rule_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("RelayNamespace", pipeline_response) + deserialized = self._deserialize("AuthorizationRule", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - - get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}"} # type: ignore - - @overload - async def update( - self, - resource_group_name: str, - namespace_name: str, - parameters: _models.RelayUpdateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.RelayNamespace: - """Creates or updates a namespace. Once created, this namespace's resource manifest is immutable. - This operation is idempotent. - - :param resource_group_name: Name of the Resource group within the Azure subscription. Required. - :type resource_group_name: str - :param namespace_name: The namespace name. Required. - :type namespace_name: str - :param parameters: Parameters for updating a namespace resource. Required. - :type parameters: ~azure.mgmt.relay.models.RelayUpdateParameters - :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: RelayNamespace or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.RelayNamespace - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def update( - self, - resource_group_name: str, - namespace_name: str, - parameters: IO, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.RelayNamespace: - """Creates or updates a namespace. Once created, this namespace's resource manifest is immutable. - This operation is idempotent. + return cls(pipeline_response, deserialized, {}) # type: ignore - :param resource_group_name: Name of the Resource group within the Azure subscription. Required. - :type resource_group_name: str - :param namespace_name: The namespace name. Required. - :type namespace_name: str - :param parameters: Parameters for updating a namespace resource. Required. - :type parameters: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: RelayNamespace or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.RelayNamespace - :raises ~azure.core.exceptions.HttpResponseError: - """ + return deserialized # type: ignore @distributed_trace_async - async def update( - self, - resource_group_name: str, - namespace_name: str, - parameters: Union[_models.RelayUpdateParameters, IO], - **kwargs: Any - ) -> _models.RelayNamespace: - """Creates or updates a namespace. Once created, this namespace's resource manifest is immutable. - This operation is idempotent. + async def list_keys( + self, resource_group_name: str, namespace_name: str, authorization_rule_name: str, **kwargs: Any + ) -> _models.AccessKeys: + """Primary and secondary connection strings to the namespace. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str :param namespace_name: The namespace name. Required. :type namespace_name: str - :param parameters: Parameters for updating a namespace resource. Is either a model type or a IO - type. Required. - :type parameters: ~azure.mgmt.relay.models.RelayUpdateParameters 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: RelayNamespace or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.RelayNamespace + :param authorization_rule_name: The authorization rule name. Required. + :type authorization_rule_name: str + :return: AccessKeys or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.AccessKeys :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1420,141 +1202,128 @@ async def update( } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - cls = kwargs.pop("cls", None) # type: ClsType[_models.RelayNamespace] - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IO, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "RelayUpdateParameters") + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.AccessKeys] = kwargs.pop("cls", None) - request = build_update_request( + _request = build_list_keys_request( resource_group_name=resource_group_name, namespace_name=namespace_name, + authorization_rule_name=authorization_rule_name, subscription_id=self._config.subscription_id, api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - template_url=self.update.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response - if response.status_code not in [200, 201]: + if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + 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("RelayNamespace", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("RelayNamespace", pipeline_response) + deserialized = self._deserialize("AccessKeys", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}"} # type: ignore + return deserialized # type: ignore @overload - async def create_or_update_network_rule_set( + async def regenerate_keys( self, resource_group_name: str, namespace_name: str, - parameters: _models.NetworkRuleSet, + authorization_rule_name: str, + parameters: _models.RegenerateAccessKeyParameters, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.NetworkRuleSet: - """Create or update NetworkRuleSet for a Namespace. + ) -> _models.AccessKeys: + """Regenerates the primary or secondary connection strings to the namespace. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str :param namespace_name: The namespace name. Required. :type namespace_name: str - :param parameters: The Namespace IpFilterRule. Required. - :type parameters: ~azure.mgmt.relay.models.NetworkRuleSet + :param authorization_rule_name: The authorization rule name. Required. + :type authorization_rule_name: str + :param parameters: Parameters supplied to regenerate authorization rule. Required. + :type parameters: ~azure.mgmt.relay.models.RegenerateAccessKeyParameters :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: NetworkRuleSet or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.NetworkRuleSet + :return: AccessKeys or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.AccessKeys :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def create_or_update_network_rule_set( + async def regenerate_keys( self, resource_group_name: str, namespace_name: str, - parameters: IO, + authorization_rule_name: str, + parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.NetworkRuleSet: - """Create or update NetworkRuleSet for a Namespace. + ) -> _models.AccessKeys: + """Regenerates the primary or secondary connection strings to the namespace. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str :param namespace_name: The namespace name. Required. :type namespace_name: str - :param parameters: The Namespace IpFilterRule. Required. - :type parameters: IO + :param authorization_rule_name: The authorization rule name. Required. + :type authorization_rule_name: str + :param parameters: Parameters supplied to regenerate authorization rule. Required. + :type parameters: IO[bytes] :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: NetworkRuleSet or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.NetworkRuleSet + :return: AccessKeys or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.AccessKeys :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async - async def create_or_update_network_rule_set( + async def regenerate_keys( self, resource_group_name: str, namespace_name: str, - parameters: Union[_models.NetworkRuleSet, IO], + authorization_rule_name: str, + parameters: Union[_models.RegenerateAccessKeyParameters, IO[bytes]], **kwargs: Any - ) -> _models.NetworkRuleSet: - """Create or update NetworkRuleSet for a Namespace. + ) -> _models.AccessKeys: + """Regenerates the primary or secondary connection strings to the namespace. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str :param namespace_name: The namespace name. Required. :type namespace_name: str - :param parameters: The Namespace IpFilterRule. Is either a model type or a IO type. Required. - :type parameters: ~azure.mgmt.relay.models.NetworkRuleSet 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: NetworkRuleSet or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.NetworkRuleSet + :param authorization_rule_name: The authorization rule name. Required. + :type authorization_rule_name: str + :param parameters: Parameters supplied to regenerate authorization rule. Is either a + RegenerateAccessKeyParameters type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.relay.models.RegenerateAccessKeyParameters or IO[bytes] + :return: AccessKeys or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.AccessKeys :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1565,114 +1334,50 @@ async def create_or_update_network_rule_set( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - cls = kwargs.pop("cls", None) # type: ClsType[_models.NetworkRuleSet] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.AccessKeys] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(parameters, (IO, bytes)): + if isinstance(parameters, (IOBase, bytes)): _content = parameters else: - _json = self._serialize.body(parameters, "NetworkRuleSet") + _json = self._serialize.body(parameters, "RegenerateAccessKeyParameters") - request = build_create_or_update_network_rule_set_request( + _request = build_regenerate_keys_request( resource_group_name=resource_group_name, namespace_name=namespace_name, + authorization_rule_name=authorization_rule_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_network_rule_set.metadata["url"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore - - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("NetworkRuleSet", pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - - create_or_update_network_rule_set.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/networkRuleSets/default"} # type: ignore - - @distributed_trace_async - async def get_network_rule_set( - self, resource_group_name: str, namespace_name: str, **kwargs: Any - ) -> _models.NetworkRuleSet: - """Gets NetworkRuleSet for a Namespace. - - :param resource_group_name: Name of the Resource group within the Azure subscription. Required. - :type resource_group_name: str - :param namespace_name: The namespace name. Required. - :type namespace_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: NetworkRuleSet or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.NetworkRuleSet - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - cls = kwargs.pop("cls", None) # type: ClsType[_models.NetworkRuleSet] - - request = build_get_network_rule_set_request( - resource_group_name=resource_group_name, - namespace_name=namespace_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - template_url=self.get_network_rule_set.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("NetworkRuleSet", pipeline_response) + deserialized = self._deserialize("AccessKeys", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get_network_rule_set.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/networkRuleSets/default"} # type: ignore + return deserialized # type: ignore diff --git a/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/aio/operations/_operations.py b/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/aio/operations/_operations.py index c330214020a2..1fc86c6fdafa 100644 --- a/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/aio/operations/_operations.py +++ b/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/aio/operations/_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,10 +5,11 @@ # 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 +from collections.abc import MutableMapping +from typing import Any, Callable, Optional, TypeVar import urllib.parse +from azure.core import AsyncPipelineClient from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, @@ -20,22 +20,19 @@ map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse -from azure.core.rest import HttpRequest +from azure.core.rest import AsyncHttpResponse, 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 ..._utils.serialization import Deserializer, Serializer from ...operations._operations import build_list_request +from .._configuration import RelayAPIConfiguration -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]] +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] +List = list class Operations: @@ -52,16 +49,15 @@ class Operations: 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") + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: RelayAPIConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace - def list(self, **kwargs: Any) -> AsyncIterable["_models.Operation"]: + def list(self, **kwargs: Any) -> AsyncItemPaged["_models.Operation"]: """Lists all available Relay 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.relay.models.Operation] :raises ~azure.core.exceptions.HttpResponseError: @@ -69,12 +65,10 @@ def list(self, **kwargs: Any) -> AsyncIterable["_models.Operation"]: _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - cls = kwargs.pop("cls", None) # type: ClsType[_models.OperationListResult] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -85,14 +79,12 @@ def list(self, **kwargs: Any) -> AsyncIterable["_models.Operation"]: def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -104,36 +96,37 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _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) # type: ignore - request.method = "GET" - return 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) + 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) + _request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + 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.Relay/operations"} # type: ignore diff --git a/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/aio/operations/_private_endpoint_connections_operations.py b/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/aio/operations/_private_endpoint_connections_operations.py deleted file mode 100644 index 88bbd1eb68c2..000000000000 --- a/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/aio/operations/_private_endpoint_connections_operations.py +++ /dev/null @@ -1,499 +0,0 @@ -# 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._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.relay.aio.RelayAPI`'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 - def list( - self, resource_group_name: str, namespace_name: str, **kwargs: Any - ) -> AsyncIterable["_models.PrivateEndpointConnection"]: - """Gets the available PrivateEndpointConnections within a namespace. - - :param resource_group_name: Name of the Resource group within the Azure subscription. Required. - :type resource_group_name: str - :param namespace_name: The namespace name. Required. - :type namespace_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PrivateEndpointConnection or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.relay.models.PrivateEndpointConnection] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - cls = kwargs.pop("cls", None) # type: ClsType[_models.PrivateEndpointConnectionListResult] - - 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, - namespace_name=namespace_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) # type: ignore - - 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) # type: ignore - request.method = "GET" - return request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("PrivateEndpointConnectionListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) - return deserialized.next_link or None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - request = prepare_request(next_link) - - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - list.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/privateEndpointConnections"} # type: ignore - - @overload - async def create_or_update( - self, - resource_group_name: str, - namespace_name: str, - private_endpoint_connection_name: str, - parameters: _models.PrivateEndpointConnection, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.PrivateEndpointConnection: - """Creates or updates PrivateEndpointConnections of service namespace. - - :param resource_group_name: Name of the Resource group within the Azure subscription. Required. - :type resource_group_name: str - :param namespace_name: The namespace name. Required. - :type namespace_name: str - :param private_endpoint_connection_name: The PrivateEndpointConnection name. Required. - :type private_endpoint_connection_name: str - :param parameters: Parameters supplied to update Status of PrivateEndPoint Connection to - namespace resource. Required. - :type parameters: ~azure.mgmt.relay.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 - :return: PrivateEndpointConnection or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.PrivateEndpointConnection - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_or_update( - self, - resource_group_name: str, - namespace_name: str, - private_endpoint_connection_name: str, - parameters: IO, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.PrivateEndpointConnection: - """Creates or updates PrivateEndpointConnections of service namespace. - - :param resource_group_name: Name of the Resource group within the Azure subscription. Required. - :type resource_group_name: str - :param namespace_name: The namespace name. Required. - :type namespace_name: str - :param private_endpoint_connection_name: The PrivateEndpointConnection name. Required. - :type private_endpoint_connection_name: str - :param parameters: Parameters supplied to update Status of PrivateEndPoint Connection to - namespace resource. Required. - :type parameters: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: PrivateEndpointConnection or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.PrivateEndpointConnection - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create_or_update( - self, - resource_group_name: str, - namespace_name: str, - private_endpoint_connection_name: str, - parameters: Union[_models.PrivateEndpointConnection, IO], - **kwargs: Any - ) -> _models.PrivateEndpointConnection: - """Creates or updates PrivateEndpointConnections of service namespace. - - :param resource_group_name: Name of the Resource group within the Azure subscription. Required. - :type resource_group_name: str - :param namespace_name: The namespace name. Required. - :type namespace_name: str - :param private_endpoint_connection_name: The PrivateEndpointConnection name. Required. - :type private_endpoint_connection_name: str - :param parameters: Parameters supplied to update Status of PrivateEndPoint Connection to - namespace resource. Is either a model type or a IO type. Required. - :type parameters: ~azure.mgmt.relay.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 - :return: PrivateEndpointConnection or the result of cls(response) - :rtype: ~azure.mgmt.relay.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 = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - cls = kwargs.pop("cls", None) # type: ClsType[_models.PrivateEndpointConnection] - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IO, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "PrivateEndpointConnection") - - request = build_create_or_update_request( - resource_group_name=resource_group_name, - namespace_name=namespace_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.metadata["url"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore - - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201, 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 == 201: - deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) - - if response.status_code == 202: - deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - - create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore - - async def _delete_initial( # pylint: disable=inconsistent-return-statements - self, resource_group_name: str, namespace_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 = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - cls = kwargs.pop("cls", None) # type: ClsType[None] - - request = build_delete_request( - resource_group_name=resource_group_name, - namespace_name=namespace_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) # type: ignore - - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202, 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.Relay/namespaces/{namespaceName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore - - @distributed_trace_async - async def begin_delete( - self, resource_group_name: str, namespace_name: str, private_endpoint_connection_name: str, **kwargs: Any - ) -> AsyncLROPoller[None]: - """Deletes an existing namespace. This operation also removes all associated resources under the - namespace. - - :param resource_group_name: Name of the Resource group within the Azure subscription. Required. - :type resource_group_name: str - :param namespace_name: The namespace name. Required. - :type namespace_name: str - :param private_endpoint_connection_name: The PrivateEndpointConnection name. 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 = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - cls = kwargs.pop("cls", None) # type: ClsType[None] - polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] - if cont_token is None: - raw_result = await self._delete_initial( # type: ignore - resource_group_name=resource_group_name, - namespace_name=namespace_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 = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller.from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - - begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore - - @distributed_trace_async - async def get( - self, resource_group_name: str, namespace_name: str, private_endpoint_connection_name: str, **kwargs: Any - ) -> _models.PrivateEndpointConnection: - """Gets a description for the specified Private Endpoint Connection name. - - :param resource_group_name: Name of the Resource group within the Azure subscription. Required. - :type resource_group_name: str - :param namespace_name: The namespace name. Required. - :type namespace_name: str - :param private_endpoint_connection_name: The PrivateEndpointConnection name. 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.relay.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 = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - cls = kwargs.pop("cls", None) # type: ClsType[_models.PrivateEndpointConnection] - - request = build_get_request( - resource_group_name=resource_group_name, - namespace_name=namespace_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) # type: ignore - - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - - get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore diff --git a/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/aio/operations/_private_link_resources_operations.py b/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/aio/operations/_private_link_resources_operations.py deleted file mode 100644 index 5210879dcfb1..000000000000 --- a/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/aio/operations/_private_link_resources_operations.py +++ /dev/null @@ -1,185 +0,0 @@ -# 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.relay.aio.RelayAPI`'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 get( - self, resource_group_name: str, namespace_name: str, private_link_resource_name: str, **kwargs: Any - ) -> _models.PrivateLinkResource: - """Gets a description for the specified Private Endpoint Connection name. - - :param resource_group_name: Name of the Resource group within the Azure subscription. Required. - :type resource_group_name: str - :param namespace_name: The namespace name. Required. - :type namespace_name: str - :param private_link_resource_name: The PrivateLinkResource name. Required. - :type private_link_resource_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: PrivateLinkResource or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.PrivateLinkResource - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - cls = kwargs.pop("cls", None) # type: ClsType[_models.PrivateLinkResource] - - request = build_get_request( - resource_group_name=resource_group_name, - namespace_name=namespace_name, - private_link_resource_name=private_link_resource_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - template_url=self.get.metadata["url"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore - - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PrivateLinkResource", pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - - get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/privateLinkResources/{privateLinkResourceName}"} # type: ignore - - @distributed_trace_async - async def list( - self, resource_group_name: str, namespace_name: str, **kwargs: Any - ) -> _models.PrivateLinkResourcesListResult: - """Gets lists of resources that supports Privatelinks. - - :param resource_group_name: Name of the Resource group within the Azure subscription. Required. - :type resource_group_name: str - :param namespace_name: The namespace name. Required. - :type namespace_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: PrivateLinkResourcesListResult or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.PrivateLinkResourcesListResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - cls = kwargs.pop("cls", None) # type: ClsType[_models.PrivateLinkResourcesListResult] - - request = build_list_request( - resource_group_name=resource_group_name, - namespace_name=namespace_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) # type: ignore - - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PrivateLinkResourcesListResult", pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - - list.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/privateLinkResources"} # type: ignore diff --git a/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/aio/operations/_wcf_relays_operations.py b/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/aio/operations/_wcf_relays_operations.py index e7510d897d80..ee0d945a2250 100644 --- a/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/aio/operations/_wcf_relays_operations.py +++ b/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/aio/operations/_wcf_relays_operations.py @@ -6,10 +6,12 @@ # 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, overload +from collections.abc import MutableMapping +from io import IOBase +from typing import Any, Callable, IO, Optional, TypeVar, Union, overload import urllib.parse +from azure.core import AsyncPipelineClient from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, @@ -20,15 +22,14 @@ map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse -from azure.core.rest import HttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models -from ..._vendor import _convert_request +from ..._utils.serialization import Deserializer, Serializer from ...operations._wcf_relays_operations import ( build_create_or_update_authorization_rule_request, build_create_or_update_request, @@ -41,13 +42,11 @@ build_list_keys_request, build_regenerate_keys_request, ) +from .._configuration import RelayAPIConfiguration -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]] +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] +List = list class WCFRelaysOperations: @@ -64,37 +63,32 @@ class WCFRelaysOperations: 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") + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: RelayAPIConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace - def list_authorization_rules( - self, resource_group_name: str, namespace_name: str, relay_name: str, **kwargs: Any - ) -> AsyncIterable["_models.AuthorizationRule"]: - """Authorization rules for a WCF relay. + def list_by_namespace( + self, resource_group_name: str, namespace_name: str, **kwargs: Any + ) -> AsyncItemPaged["_models.WcfRelay"]: + """Lists the WCF relays within the namespace. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str :param namespace_name: The namespace name. Required. :type namespace_name: str - :param relay_name: The relay name. Required. - :type relay_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either AuthorizationRule or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.relay.models.AuthorizationRule] + :return: An iterator like instance of either WcfRelay or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.relay.models.WcfRelay] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - cls = kwargs.pop("cls", None) # type: ClsType[_models.AuthorizationRuleListResult] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.WcfRelaysListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -105,18 +99,15 @@ def list_authorization_rules( def prepare_request(next_link=None): if not next_link: - request = build_list_authorization_rules_request( + _request = build_list_by_namespace_request( resource_group_name=resource_group_name, namespace_name=namespace_name, - relay_name=relay_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_authorization_rules.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -128,52 +119,53 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _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) # type: ignore - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): - deserialized = self._deserialize("AuthorizationRuleListResult", pipeline_response) + deserialized = self._deserialize("WcfRelaysListResult", 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) + _request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + 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_authorization_rules.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/wcfRelays/{relayName}/authorizationRules"} # type: ignore - @overload - async def create_or_update_authorization_rule( + async def create_or_update( self, resource_group_name: str, namespace_name: str, relay_name: str, - authorization_rule_name: str, - parameters: _models.AuthorizationRule, + parameters: _models.WcfRelay, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.AuthorizationRule: - """Creates or updates an authorization rule for a WCF relay. + ) -> _models.WcfRelay: + """Creates or updates a WCF relay. This operation is idempotent. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str @@ -181,32 +173,28 @@ async def create_or_update_authorization_rule( :type namespace_name: str :param relay_name: The relay name. Required. :type relay_name: str - :param authorization_rule_name: The authorization rule name. Required. - :type authorization_rule_name: str - :param parameters: The authorization rule parameters. Required. - :type parameters: ~azure.mgmt.relay.models.AuthorizationRule + :param parameters: Parameters supplied to create a WCF relay. Required. + :type parameters: ~azure.mgmt.relay.models.WcfRelay :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: AuthorizationRule or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.AuthorizationRule + :return: WcfRelay or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.WcfRelay :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def create_or_update_authorization_rule( + async def create_or_update( self, resource_group_name: str, namespace_name: str, relay_name: str, - authorization_rule_name: str, - parameters: IO, + parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.AuthorizationRule: - """Creates or updates an authorization rule for a WCF relay. + ) -> _models.WcfRelay: + """Creates or updates a WCF relay. This operation is idempotent. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str @@ -214,30 +202,26 @@ async def create_or_update_authorization_rule( :type namespace_name: str :param relay_name: The relay name. Required. :type relay_name: str - :param authorization_rule_name: The authorization rule name. Required. - :type authorization_rule_name: str - :param parameters: The authorization rule parameters. Required. - :type parameters: IO + :param parameters: Parameters supplied to create a WCF relay. Required. + :type parameters: IO[bytes] :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: AuthorizationRule or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.AuthorizationRule + :return: WcfRelay or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.WcfRelay :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async - async def create_or_update_authorization_rule( + async def create_or_update( self, resource_group_name: str, namespace_name: str, relay_name: str, - authorization_rule_name: str, - parameters: Union[_models.AuthorizationRule, IO], + parameters: Union[_models.WcfRelay, IO[bytes]], **kwargs: Any - ) -> _models.AuthorizationRule: - """Creates or updates an authorization rule for a WCF relay. + ) -> _models.WcfRelay: + """Creates or updates a WCF relay. This operation is idempotent. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str @@ -245,20 +229,14 @@ async def create_or_update_authorization_rule( :type namespace_name: str :param relay_name: The relay name. Required. :type relay_name: str - :param authorization_rule_name: The authorization rule name. Required. - :type authorization_rule_name: str - :param parameters: The authorization rule parameters. Is either a model type or a IO type. - Required. - :type parameters: ~azure.mgmt.relay.models.AuthorizationRule 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: AuthorizationRule or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.AuthorizationRule + :param parameters: Parameters supplied to create a WCF relay. Is either a WcfRelay type or a + IO[bytes] type. Required. + :type parameters: ~azure.mgmt.relay.models.WcfRelay or IO[bytes] + :return: WcfRelay or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.WcfRelay :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -269,67 +247,57 @@ async def create_or_update_authorization_rule( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - cls = kwargs.pop("cls", None) # type: ClsType[_models.AuthorizationRule] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.WcfRelay] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(parameters, (IO, bytes)): + if isinstance(parameters, (IOBase, bytes)): _content = parameters else: - _json = self._serialize.body(parameters, "AuthorizationRule") + _json = self._serialize.body(parameters, "WcfRelay") - request = build_create_or_update_authorization_rule_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, namespace_name=namespace_name, relay_name=relay_name, - authorization_rule_name=authorization_rule_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_authorization_rule.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("AuthorizationRule", pipeline_response) + deserialized = self._deserialize("WcfRelay", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - create_or_update_authorization_rule.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/wcfRelays/{relayName}/authorizationRules/{authorizationRuleName}"} # type: ignore + return deserialized # type: ignore @distributed_trace_async - async def delete_authorization_rule( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - namespace_name: str, - relay_name: str, - authorization_rule_name: str, - **kwargs: Any - ) -> None: - """Deletes a WCF relay authorization rule. + async def delete(self, resource_group_name: str, namespace_name: str, relay_name: str, **kwargs: Any) -> None: + """Deletes a WCF relay. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str @@ -337,14 +305,11 @@ async def delete_authorization_rule( # pylint: disable=inconsistent-return-stat :type namespace_name: str :param relay_name: The relay name. Required. :type relay_name: str - :param authorization_rule_name: The authorization rule name. Required. - :type authorization_rule_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -355,51 +320,43 @@ async def delete_authorization_rule( # pylint: disable=inconsistent-return-stat _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - cls = kwargs.pop("cls", None) # type: ClsType[None] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_authorization_rule_request( + _request = build_delete_request( resource_group_name=resource_group_name, namespace_name=namespace_name, relay_name=relay_name, - authorization_rule_name=authorization_rule_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.delete_authorization_rule.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + 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_authorization_rule.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/wcfRelays/{relayName}/authorizationRules/{authorizationRuleName}"} # type: ignore + return cls(pipeline_response, None, {}) # type: ignore @distributed_trace_async - async def get_authorization_rule( - self, - resource_group_name: str, - namespace_name: str, - relay_name: str, - authorization_rule_name: str, - **kwargs: Any - ) -> _models.AuthorizationRule: - """Get authorizationRule for a WCF relay by name. + async def get( + self, resource_group_name: str, namespace_name: str, relay_name: str, **kwargs: Any + ) -> Optional[_models.WcfRelay]: + """Returns the description for the specified WCF relay. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str @@ -407,14 +364,11 @@ async def get_authorization_rule( :type namespace_name: str :param relay_name: The relay name. Required. :type relay_name: str - :param authorization_rule_name: The authorization rule name. Required. - :type authorization_rule_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: AuthorizationRule or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.AuthorizationRule + :return: WcfRelay or None or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.WcfRelay or None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -425,55 +379,49 @@ async def get_authorization_rule( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - cls = kwargs.pop("cls", None) # type: ClsType[_models.AuthorizationRule] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[Optional[_models.WcfRelay]] = kwargs.pop("cls", None) - request = build_get_authorization_rule_request( + _request = build_get_request( resource_group_name=resource_group_name, namespace_name=namespace_name, relay_name=relay_name, - authorization_rule_name=authorization_rule_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get_authorization_rule.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response - if response.status_code not in [200]: + if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("AuthorizationRule", pipeline_response) + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize("WcfRelay", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get_authorization_rule.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/wcfRelays/{relayName}/authorizationRules/{authorizationRuleName}"} # type: ignore + return deserialized # type: ignore - @distributed_trace_async - async def list_keys( - self, - resource_group_name: str, - namespace_name: str, - relay_name: str, - authorization_rule_name: str, - **kwargs: Any - ) -> _models.AccessKeys: - """Primary and secondary connection strings to the WCF relay. + @distributed_trace + def list_authorization_rules( + self, resource_group_name: str, namespace_name: str, relay_name: str, **kwargs: Any + ) -> AsyncItemPaged["_models.AuthorizationRule"]: + """Authorization rules for a WCF relay. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str @@ -481,14 +429,17 @@ async def list_keys( :type namespace_name: str :param relay_name: The relay name. Required. :type relay_name: str - :param authorization_rule_name: The authorization rule name. Required. - :type authorization_rule_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: AccessKeys or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.AccessKeys + :return: An iterator like instance of either AuthorizationRule or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.relay.models.AuthorizationRule] :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.AuthorizationRuleListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -496,61 +447,74 @@ async def list_keys( } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessKeys] + def prepare_request(next_link=None): + if not next_link: - request = build_list_keys_request( - resource_group_name=resource_group_name, - namespace_name=namespace_name, - relay_name=relay_name, - authorization_rule_name=authorization_rule_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - template_url=self.list_keys.metadata["url"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request = build_list_authorization_rules_request( + resource_group_name=resource_group_name, + namespace_name=namespace_name, + relay_name=relay_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs - ) + 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.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request - response = pipeline_response.http_response + async def extract_data(pipeline_response): + deserialized = self._deserialize("AuthorizationRuleListResult", 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) - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + async def get_next(next_link=None): + _request = prepare_request(next_link) - deserialized = self._deserialize("AccessKeys", pipeline_response) + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response - if cls: - return cls(pipeline_response, deserialized, {}) + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) - return deserialized + return pipeline_response - list_keys.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/wcfRelays/{relayName}/authorizationRules/{authorizationRuleName}/listKeys"} # type: ignore + return AsyncItemPaged(get_next, extract_data) @overload - async def regenerate_keys( + async def create_or_update_authorization_rule( self, resource_group_name: str, namespace_name: str, relay_name: str, authorization_rule_name: str, - parameters: _models.RegenerateAccessKeyParameters, + parameters: _models.AuthorizationRule, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.AccessKeys: - """Regenerates the primary or secondary connection strings to the WCF relay. + ) -> _models.AuthorizationRule: + """Creates or updates an authorization rule for a WCF relay. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str @@ -560,30 +524,29 @@ async def regenerate_keys( :type relay_name: str :param authorization_rule_name: The authorization rule name. Required. :type authorization_rule_name: str - :param parameters: Parameters supplied to regenerate authorization rule. Required. - :type parameters: ~azure.mgmt.relay.models.RegenerateAccessKeyParameters + :param parameters: The authorization rule parameters. Required. + :type parameters: ~azure.mgmt.relay.models.AuthorizationRule :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: AccessKeys or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.AccessKeys + :return: AuthorizationRule or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.AuthorizationRule :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def regenerate_keys( + async def create_or_update_authorization_rule( self, resource_group_name: str, namespace_name: str, relay_name: str, authorization_rule_name: str, - parameters: IO, + parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.AccessKeys: - """Regenerates the primary or secondary connection strings to the WCF relay. + ) -> _models.AuthorizationRule: + """Creates or updates an authorization rule for a WCF relay. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str @@ -593,28 +556,27 @@ async def regenerate_keys( :type relay_name: str :param authorization_rule_name: The authorization rule name. Required. :type authorization_rule_name: str - :param parameters: Parameters supplied to regenerate authorization rule. Required. - :type parameters: IO + :param parameters: The authorization rule parameters. Required. + :type parameters: IO[bytes] :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: AccessKeys or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.AccessKeys + :return: AuthorizationRule or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.AuthorizationRule :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async - async def regenerate_keys( + async def create_or_update_authorization_rule( self, resource_group_name: str, namespace_name: str, relay_name: str, authorization_rule_name: str, - parameters: Union[_models.RegenerateAccessKeyParameters, IO], + parameters: Union[_models.AuthorizationRule, IO[bytes]], **kwargs: Any - ) -> _models.AccessKeys: - """Regenerates the primary or secondary connection strings to the WCF relay. + ) -> _models.AuthorizationRule: + """Creates or updates an authorization rule for a WCF relay. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str @@ -624,18 +586,14 @@ async def regenerate_keys( :type relay_name: str :param authorization_rule_name: The authorization rule name. Required. :type authorization_rule_name: str - :param parameters: Parameters supplied to regenerate authorization rule. Is either a model type - or a IO type. Required. - :type parameters: ~azure.mgmt.relay.models.RegenerateAccessKeyParameters 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: AccessKeys or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.AccessKeys + :param parameters: The authorization rule parameters. Is either a AuthorizationRule type or a + IO[bytes] type. Required. + :type parameters: ~azure.mgmt.relay.models.AuthorizationRule or IO[bytes] + :return: AuthorizationRule or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.AuthorizationRule :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -646,21 +604,19 @@ async def regenerate_keys( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessKeys] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.AuthorizationRule] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(parameters, (IO, bytes)): + if isinstance(parameters, (IOBase, bytes)): _content = parameters else: - _json = self._serialize.body(parameters, "RegenerateAccessKeyParameters") + _json = self._serialize.body(parameters, "AuthorizationRule") - request = build_regenerate_keys_request( + _request = build_create_or_update_authorization_rule_request( resource_group_name=resource_group_name, namespace_name=namespace_name, relay_name=relay_name, @@ -670,57 +626,57 @@ async def regenerate_keys( content_type=content_type, json=_json, content=_content, - template_url=self.regenerate_keys.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("AccessKeys", pipeline_response) + deserialized = self._deserialize("AuthorizationRule", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - regenerate_keys.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/wcfRelays/{relayName}/authorizationRules/{authorizationRuleName}/regenerateKeys"} # type: ignore + return deserialized # type: ignore - @distributed_trace - def list_by_namespace( - self, resource_group_name: str, namespace_name: str, **kwargs: Any - ) -> AsyncIterable["_models.WcfRelay"]: - """Lists the WCF relays within the namespace. + @distributed_trace_async + async def delete_authorization_rule( + self, + resource_group_name: str, + namespace_name: str, + relay_name: str, + authorization_rule_name: str, + **kwargs: Any + ) -> None: + """Deletes a WCF relay authorization rule. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str :param namespace_name: The namespace name. Required. :type namespace_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either WcfRelay or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.relay.models.WcfRelay] + :param relay_name: The relay name. Required. + :type relay_name: str + :param authorization_rule_name: The authorization rule name. Required. + :type authorization_rule_name: str + :return: None or the result of cls(response) + :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - cls = kwargs.pop("cls", None) # type: ClsType[_models.WcfRelaysListResult] - - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -728,135 +684,52 @@ def list_by_namespace( } error_map.update(kwargs.pop("error_map", {}) or {}) - def prepare_request(next_link=None): - if not next_link: + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - request = build_list_by_namespace_request( - resource_group_name=resource_group_name, - namespace_name=namespace_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - template_url=self.list_by_namespace.metadata["url"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) - 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) # type: ignore - request.method = "GET" - return request + _request = build_delete_authorization_rule_request( + resource_group_name=resource_group_name, + namespace_name=namespace_name, + relay_name=relay_name, + authorization_rule_name=authorization_rule_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) - async def extract_data(pipeline_response): - deserialized = self._deserialize("WcfRelaysListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) - return deserialized.next_link or None, AsyncList(list_of_elem) + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) - async def get_next(next_link=None): - request = prepare_request(next_link) + response = pipeline_response.http_response - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, 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_namespace.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/wcfRelays"} # type: ignore - - @overload - async def create_or_update( - self, - resource_group_name: str, - namespace_name: str, - relay_name: str, - parameters: _models.WcfRelay, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.WcfRelay: - """Creates or updates a WCF relay. This operation is idempotent. - - :param resource_group_name: Name of the Resource group within the Azure subscription. Required. - :type resource_group_name: str - :param namespace_name: The namespace name. Required. - :type namespace_name: str - :param relay_name: The relay name. Required. - :type relay_name: str - :param parameters: Parameters supplied to create a WCF relay. Required. - :type parameters: ~azure.mgmt.relay.models.WcfRelay - :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: WcfRelay or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.WcfRelay - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_or_update( - self, - resource_group_name: str, - namespace_name: str, - relay_name: str, - parameters: IO, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.WcfRelay: - """Creates or updates a WCF relay. This operation is idempotent. + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - :param resource_group_name: Name of the Resource group within the Azure subscription. Required. - :type resource_group_name: str - :param namespace_name: The namespace name. Required. - :type namespace_name: str - :param relay_name: The relay name. Required. - :type relay_name: str - :param parameters: Parameters supplied to create a WCF relay. Required. - :type parameters: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: WcfRelay or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.WcfRelay - :raises ~azure.core.exceptions.HttpResponseError: - """ + if cls: + return cls(pipeline_response, None, {}) # type: ignore @distributed_trace_async - async def create_or_update( + async def get_authorization_rule( self, resource_group_name: str, namespace_name: str, relay_name: str, - parameters: Union[_models.WcfRelay, IO], + authorization_rule_name: str, **kwargs: Any - ) -> _models.WcfRelay: - """Creates or updates a WCF relay. This operation is idempotent. + ) -> _models.AuthorizationRule: + """Get authorizationRule for a WCF relay by name. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str @@ -864,18 +737,13 @@ async def create_or_update( :type namespace_name: str :param relay_name: The relay name. Required. :type relay_name: str - :param parameters: Parameters supplied to create a WCF relay. Is either a model type or a IO - type. Required. - :type parameters: ~azure.mgmt.relay.models.WcfRelay 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: WcfRelay or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.WcfRelay + :param authorization_rule_name: The authorization rule name. Required. + :type authorization_rule_name: str + :return: AuthorizationRule or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.AuthorizationRule :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -883,64 +751,56 @@ async def create_or_update( } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - cls = kwargs.pop("cls", None) # type: ClsType[_models.WcfRelay] - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IO, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "WcfRelay") + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.AuthorizationRule] = kwargs.pop("cls", None) - request = build_create_or_update_request( + _request = build_get_authorization_rule_request( resource_group_name=resource_group_name, namespace_name=namespace_name, relay_name=relay_name, + authorization_rule_name=authorization_rule_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.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("WcfRelay", pipeline_response) + deserialized = self._deserialize("AuthorizationRule", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/wcfRelays/{relayName}"} # type: ignore + return deserialized # type: ignore @distributed_trace_async - async def delete( # pylint: disable=inconsistent-return-statements - self, resource_group_name: str, namespace_name: str, relay_name: str, **kwargs: Any - ) -> None: - """Deletes a WCF relay. + async def list_keys( + self, + resource_group_name: str, + namespace_name: str, + relay_name: str, + authorization_rule_name: str, + **kwargs: Any + ) -> _models.AccessKeys: + """Primary and secondary connection strings to the WCF relay. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str @@ -948,12 +808,13 @@ async def delete( # pylint: disable=inconsistent-return-statements :type namespace_name: str :param relay_name: The relay name. Required. :type relay_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: None or the result of cls(response) - :rtype: None + :param authorization_rule_name: The authorization rule name. Required. + :type authorization_rule_name: str + :return: AccessKeys or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.AccessKeys :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -964,45 +825,118 @@ async def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - cls = kwargs.pop("cls", None) # type: ClsType[None] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.AccessKeys] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_list_keys_request( resource_group_name=resource_group_name, namespace_name=namespace_name, relay_name=relay_name, + authorization_rule_name=authorization_rule_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.delete.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response - if response.status_code not in [200, 204]: + if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + deserialized = self._deserialize("AccessKeys", pipeline_response.http_response) + if cls: - return cls(pipeline_response, None, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def regenerate_keys( + self, + resource_group_name: str, + namespace_name: str, + relay_name: str, + authorization_rule_name: str, + parameters: _models.RegenerateAccessKeyParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.AccessKeys: + """Regenerates the primary or secondary connection strings to the WCF relay. - delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/wcfRelays/{relayName}"} # type: ignore + :param resource_group_name: Name of the Resource group within the Azure subscription. Required. + :type resource_group_name: str + :param namespace_name: The namespace name. Required. + :type namespace_name: str + :param relay_name: The relay name. Required. + :type relay_name: str + :param authorization_rule_name: The authorization rule name. Required. + :type authorization_rule_name: str + :param parameters: Parameters supplied to regenerate authorization rule. Required. + :type parameters: ~azure.mgmt.relay.models.RegenerateAccessKeyParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: AccessKeys or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.AccessKeys + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def regenerate_keys( + self, + resource_group_name: str, + namespace_name: str, + relay_name: str, + authorization_rule_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.AccessKeys: + """Regenerates the primary or secondary connection strings to the WCF relay. + + :param resource_group_name: Name of the Resource group within the Azure subscription. Required. + :type resource_group_name: str + :param namespace_name: The namespace name. Required. + :type namespace_name: str + :param relay_name: The relay name. Required. + :type relay_name: str + :param authorization_rule_name: The authorization rule name. Required. + :type authorization_rule_name: str + :param parameters: Parameters supplied to regenerate authorization rule. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: AccessKeys or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.AccessKeys + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace_async - async def get( - self, resource_group_name: str, namespace_name: str, relay_name: str, **kwargs: Any - ) -> Optional[_models.WcfRelay]: - """Returns the description for the specified WCF relay. + async def regenerate_keys( + self, + resource_group_name: str, + namespace_name: str, + relay_name: str, + authorization_rule_name: str, + parameters: Union[_models.RegenerateAccessKeyParameters, IO[bytes]], + **kwargs: Any + ) -> _models.AccessKeys: + """Regenerates the primary or secondary connection strings to the WCF relay. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str @@ -1010,12 +944,16 @@ async def get( :type namespace_name: str :param relay_name: The relay name. Required. :type relay_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: WcfRelay or None or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.WcfRelay or None + :param authorization_rule_name: The authorization rule name. Required. + :type authorization_rule_name: str + :param parameters: Parameters supplied to regenerate authorization rule. Is either a + RegenerateAccessKeyParameters type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.relay.models.RegenerateAccessKeyParameters or IO[bytes] + :return: AccessKeys or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.AccessKeys :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1023,45 +961,54 @@ async def get( } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = kwargs.pop("headers", {}) or {} + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.WcfRelay]] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.AccessKeys] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "RegenerateAccessKeyParameters") - request = build_get_request( + _request = build_regenerate_keys_request( resource_group_name=resource_group_name, namespace_name=namespace_name, relay_name=relay_name, + authorization_rule_name=authorization_rule_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata["url"], + content_type=content_type, + json=_json, + content=_content, headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response - if response.status_code not in [200, 204]: + if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + 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("WcfRelay", pipeline_response) + deserialized = self._deserialize("AccessKeys", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/wcfRelays/{relayName}"} # type: ignore + return deserialized # type: ignore diff --git a/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/models/__init__.py b/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/models/__init__.py index cc760845da29..f9b0be5353e4 100644 --- a/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/models/__init__.py +++ b/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/models/__init__.py @@ -5,55 +5,47 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._models_py3 import AccessKeys -from ._models_py3 import AuthorizationRule -from ._models_py3 import AuthorizationRuleListResult -from ._models_py3 import CheckNameAvailability -from ._models_py3 import CheckNameAvailabilityResult -from ._models_py3 import ConnectionState -from ._models_py3 import ErrorAdditionalInfo -from ._models_py3 import ErrorDetail -from ._models_py3 import ErrorResponse -from ._models_py3 import HybridConnection -from ._models_py3 import HybridConnectionListResult -from ._models_py3 import NWRuleSetIpRules -from ._models_py3 import NetworkRuleSet -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 PrivateEndpointConnectionListResult -from ._models_py3 import PrivateLinkResource -from ._models_py3 import PrivateLinkResourcesListResult -from ._models_py3 import ProxyResource -from ._models_py3 import RegenerateAccessKeyParameters -from ._models_py3 import RelayNamespace -from ._models_py3 import RelayNamespaceListResult -from ._models_py3 import RelayUpdateParameters -from ._models_py3 import Resource -from ._models_py3 import ResourceNamespacePatch -from ._models_py3 import Sku -from ._models_py3 import SystemData -from ._models_py3 import TrackedResource -from ._models_py3 import WcfRelay -from ._models_py3 import WcfRelaysListResult +from typing import TYPE_CHECKING -from ._relay_api_enums import AccessRights -from ._relay_api_enums import CreatedByType -from ._relay_api_enums import DefaultAction -from ._relay_api_enums import EndPointProvisioningState -from ._relay_api_enums import KeyType -from ._relay_api_enums import NetworkRuleIPAction -from ._relay_api_enums import PrivateLinkConnectionStatus -from ._relay_api_enums import PublicNetworkAccess -from ._relay_api_enums import Relaytype -from ._relay_api_enums import SkuName -from ._relay_api_enums import SkuTier -from ._relay_api_enums import UnavailableReason +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models_py3 import ( # type: ignore + AccessKeys, + AuthorizationRule, + AuthorizationRuleListResult, + CheckNameAvailability, + CheckNameAvailabilityResult, + ErrorResponse, + HybridConnection, + HybridConnectionListResult, + Operation, + OperationDisplay, + OperationListResult, + RegenerateAccessKeyParameters, + RelayNamespace, + RelayNamespaceListResult, + RelayUpdateParameters, + Resource, + ResourceNamespacePatch, + Sku, + TrackedResource, + WcfRelay, + WcfRelaysListResult, +) + +from ._relay_api_enums import ( # type: ignore + AccessRights, + KeyType, + ProvisioningStateEnum, + Relaytype, + UnavailableReason, +) from ._patch import __all__ as _patch_all -from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ @@ -62,23 +54,12 @@ "AuthorizationRuleListResult", "CheckNameAvailability", "CheckNameAvailabilityResult", - "ConnectionState", - "ErrorAdditionalInfo", - "ErrorDetail", "ErrorResponse", "HybridConnection", "HybridConnectionListResult", - "NWRuleSetIpRules", - "NetworkRuleSet", "Operation", "OperationDisplay", "OperationListResult", - "PrivateEndpoint", - "PrivateEndpointConnection", - "PrivateEndpointConnectionListResult", - "PrivateLinkResource", - "PrivateLinkResourcesListResult", - "ProxyResource", "RegenerateAccessKeyParameters", "RelayNamespace", "RelayNamespaceListResult", @@ -86,22 +67,14 @@ "Resource", "ResourceNamespacePatch", "Sku", - "SystemData", "TrackedResource", "WcfRelay", "WcfRelaysListResult", "AccessRights", - "CreatedByType", - "DefaultAction", - "EndPointProvisioningState", "KeyType", - "NetworkRuleIPAction", - "PrivateLinkConnectionStatus", - "PublicNetworkAccess", + "ProvisioningStateEnum", "Relaytype", - "SkuName", - "SkuTier", "UnavailableReason", ] -__all__.extend([p for p in _patch_all if p not in __all__]) +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/models/_models_py3.py b/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/models/_models_py3.py index e2ad18b2daa2..8a9475039758 100644 --- a/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/models/_models_py3.py +++ b/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/models/_models_py3.py @@ -1,5 +1,4 @@ # 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. @@ -8,20 +7,12 @@ # -------------------------------------------------------------------------- import datetime -import sys -from typing import Any, Dict, List, Optional, TYPE_CHECKING, Union +from typing import Any, Literal, Optional, TYPE_CHECKING, Union -from .. import _serialization - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +from .._utils import serialization as _serialization if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from .. import models as _models -JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object class AccessKeys(_serialization.Model): @@ -59,8 +50,8 @@ def __init__( primary_key: Optional[str] = None, secondary_key: Optional[str] = None, key_name: Optional[str] = None, - **kwargs - ): + **kwargs: Any + ) -> None: """ :keyword primary_connection_string: Primary connection string of the created namespace authorization rule. @@ -85,64 +76,53 @@ def __init__( self.key_name = key_name -class ProxyResource(_serialization.Model): - """Common fields that are returned in the response for all Azure Resource Manager resources. +class Resource(_serialization.Model): + """The resource definition. Variables are only populated by the server, and will be ignored when sending a request. - :ivar id: Fully qualified resource ID for the resource. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :ivar id: Resource ID. :vartype id: str - :ivar name: The name of the resource. + :ivar name: Resource name. :vartype name: str - :ivar type: The type of the resource. E.g. "Microsoft.EventHub/Namespaces" or - "Microsoft.EventHub/Namespaces/EventHubs". + :ivar type: Resource type. :vartype type: str - :ivar location: The geo-location where the resource lives. - :vartype location: str """ _validation = { "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, - "location": {"readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, - "location": {"key": "location", "type": "str"}, } - def __init__(self, **kwargs): + def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) - self.id = None - self.name = None - self.type = None - self.location = None + self.id: Optional[str] = None + self.name: Optional[str] = None + self.type: Optional[str] = None -class AuthorizationRule(ProxyResource): - """Single item in a List or Get AuthorizationRule operation. +class AuthorizationRule(Resource): + """Description of a namespace authorization rule. Variables are only populated by the server, and will be ignored when sending a request. - :ivar id: Fully qualified resource ID for the resource. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + All required parameters must be populated in order to send to server. + + :ivar id: Resource ID. :vartype id: str - :ivar name: The name of the resource. + :ivar name: Resource name. :vartype name: str - :ivar type: The type of the resource. E.g. "Microsoft.EventHub/Namespaces" or - "Microsoft.EventHub/Namespaces/EventHubs". + :ivar type: Resource type. :vartype type: str - :ivar location: The geo-location where the resource lives. - :vartype location: str - :ivar system_data: The system meta data relating to this resource. - :vartype system_data: ~azure.mgmt.relay.models.SystemData - :ivar rights: The rights associated with the rule. + :ivar rights: The rights associated with the rule. Required. :vartype rights: list[str or ~azure.mgmt.relay.models.AccessRights] """ @@ -150,26 +130,22 @@ class AuthorizationRule(ProxyResource): "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, - "location": {"readonly": True}, - "system_data": {"readonly": True}, + "rights": {"required": True, "unique": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, - "location": {"key": "location", "type": "str"}, - "system_data": {"key": "systemData", "type": "SystemData"}, "rights": {"key": "properties.rights", "type": "[str]"}, } - def __init__(self, *, rights: Optional[List[Union[str, "_models.AccessRights"]]] = None, **kwargs): + def __init__(self, *, rights: list[Union[str, "_models.AccessRights"]], **kwargs: Any) -> None: """ - :keyword rights: The rights associated with the rule. + :keyword rights: The rights associated with the rule. Required. :paramtype rights: list[str or ~azure.mgmt.relay.models.AccessRights] """ super().__init__(**kwargs) - self.system_data = None self.rights = rights @@ -189,8 +165,12 @@ class AuthorizationRuleListResult(_serialization.Model): } def __init__( - self, *, value: Optional[List["_models.AuthorizationRule"]] = None, next_link: Optional[str] = None, **kwargs - ): + self, + *, + value: Optional[list["_models.AuthorizationRule"]] = None, + next_link: Optional[str] = None, + **kwargs: Any + ) -> None: """ :keyword value: Result of the list authorization rules operation. :paramtype value: list[~azure.mgmt.relay.models.AuthorizationRule] @@ -206,7 +186,7 @@ def __init__( class CheckNameAvailability(_serialization.Model): """Description of the check name availability request properties. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. :ivar name: The namespace name to check for availability. The namespace name can contain only letters, numbers, and hyphens. The namespace must start with a letter, and it must end with a @@ -222,7 +202,7 @@ class CheckNameAvailability(_serialization.Model): "name": {"key": "name", "type": "str"}, } - def __init__(self, *, name: str, **kwargs): + def __init__(self, *, name: str, **kwargs: Any) -> None: """ :keyword name: The namespace name to check for availability. The namespace name can contain only letters, numbers, and hyphens. The namespace must start with a letter, and it must end @@ -264,8 +244,8 @@ def __init__( *, name_available: Optional[bool] = None, reason: Optional[Union[str, "_models.UnavailableReason"]] = None, - **kwargs - ): + **kwargs: Any + ) -> None: """ :keyword name_available: Value indicating namespace is available. Returns true if the namespace is available; otherwise, false. @@ -276,153 +256,49 @@ def __init__( :paramtype reason: str or ~azure.mgmt.relay.models.UnavailableReason """ super().__init__(**kwargs) - self.message = None + self.message: Optional[str] = None self.name_available = name_available self.reason = reason -class ConnectionState(_serialization.Model): - """ConnectionState information. - - :ivar status: Status of the connection. Known values are: "Pending", "Approved", "Rejected", - and "Disconnected". - :vartype status: str or ~azure.mgmt.relay.models.PrivateLinkConnectionStatus - :ivar description: Description of the connection state. - :vartype description: str - """ - - _attribute_map = { - "status": {"key": "status", "type": "str"}, - "description": {"key": "description", "type": "str"}, - } - - def __init__( - self, - *, - status: Optional[Union[str, "_models.PrivateLinkConnectionStatus"]] = None, - description: Optional[str] = None, - **kwargs - ): - """ - :keyword status: Status of the connection. Known values are: "Pending", "Approved", "Rejected", - and "Disconnected". - :paramtype status: str or ~azure.mgmt.relay.models.PrivateLinkConnectionStatus - :keyword description: Description of the connection state. - :paramtype description: str - """ - super().__init__(**kwargs) - self.status = status - self.description = description - - -class ErrorAdditionalInfo(_serialization.Model): - """The resource management error additional info. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar type: The additional info type. - :vartype type: str - :ivar info: The additional info. - :vartype info: JSON - """ - - _validation = { - "type": {"readonly": True}, - "info": {"readonly": True}, - } - - _attribute_map = { - "type": {"key": "type", "type": "str"}, - "info": {"key": "info", "type": "object"}, - } - - def __init__(self, **kwargs): - """ """ - super().__init__(**kwargs) - self.type = None - self.info = None - - -class ErrorDetail(_serialization.Model): - """The error detail. - - Variables are only populated by the server, and will be ignored when sending a request. +class ErrorResponse(_serialization.Model): + """Error reponse indicates Relay service is not able to process the incoming request. The reason + is provided in the error message. - :ivar code: The error code. + :ivar code: Error code. :vartype code: str - :ivar message: The error message. + :ivar message: Error message indicating why the operation failed. :vartype message: str - :ivar target: The error target. - :vartype target: str - :ivar details: The error details. - :vartype details: list[~azure.mgmt.relay.models.ErrorDetail] - :ivar additional_info: The error additional info. - :vartype additional_info: list[~azure.mgmt.relay.models.ErrorAdditionalInfo] """ - _validation = { - "code": {"readonly": True}, - "message": {"readonly": True}, - "target": {"readonly": True}, - "details": {"readonly": True}, - "additional_info": {"readonly": True}, - } - _attribute_map = { "code": {"key": "code", "type": "str"}, "message": {"key": "message", "type": "str"}, - "target": {"key": "target", "type": "str"}, - "details": {"key": "details", "type": "[ErrorDetail]"}, - "additional_info": {"key": "additionalInfo", "type": "[ErrorAdditionalInfo]"}, - } - - def __init__(self, **kwargs): - """ """ - super().__init__(**kwargs) - self.code = None - self.message = None - self.target = None - self.details = None - self.additional_info = None - - -class ErrorResponse(_serialization.Model): - """Common error response for all Azure Resource Manager APIs to return error details for failed operations. (This also follows the OData error response format.). - - :ivar error: The error object. - :vartype error: ~azure.mgmt.relay.models.ErrorDetail - """ - - _attribute_map = { - "error": {"key": "error", "type": "ErrorDetail"}, } - def __init__(self, *, error: Optional["_models.ErrorDetail"] = None, **kwargs): + def __init__(self, *, code: Optional[str] = None, message: Optional[str] = None, **kwargs: Any) -> None: """ - :keyword error: The error object. - :paramtype error: ~azure.mgmt.relay.models.ErrorDetail + :keyword code: Error code. + :paramtype code: str + :keyword message: Error message indicating why the operation failed. + :paramtype message: str """ super().__init__(**kwargs) - self.error = error + self.code = code + self.message = message -class HybridConnection(ProxyResource): +class HybridConnection(Resource): """Description of hybrid connection resource. Variables are only populated by the server, and will be ignored when sending a request. - :ivar id: Fully qualified resource ID for the resource. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :ivar id: Resource ID. :vartype id: str - :ivar name: The name of the resource. + :ivar name: Resource name. :vartype name: str - :ivar type: The type of the resource. E.g. "Microsoft.EventHub/Namespaces" or - "Microsoft.EventHub/Namespaces/EventHubs". + :ivar type: Resource type. :vartype type: str - :ivar location: The geo-location where the resource lives. - :vartype location: str - :ivar system_data: The system meta data relating to this resource. - :vartype system_data: ~azure.mgmt.relay.models.SystemData :ivar created_at: The time the hybrid connection was created. :vartype created_at: ~datetime.datetime :ivar updated_at: The time the namespace was updated. @@ -444,8 +320,6 @@ class HybridConnection(ProxyResource): "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, - "location": {"readonly": True}, - "system_data": {"readonly": True}, "created_at": {"readonly": True}, "updated_at": {"readonly": True}, "listener_count": {"readonly": True, "maximum": 25, "minimum": 0}, @@ -455,8 +329,6 @@ class HybridConnection(ProxyResource): "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, - "location": {"key": "location", "type": "str"}, - "system_data": {"key": "systemData", "type": "SystemData"}, "created_at": {"key": "properties.createdAt", "type": "iso-8601"}, "updated_at": {"key": "properties.updatedAt", "type": "iso-8601"}, "listener_count": {"key": "properties.listenerCount", "type": "int"}, @@ -465,8 +337,12 @@ class HybridConnection(ProxyResource): } def __init__( - self, *, requires_client_authorization: Optional[bool] = None, user_metadata: Optional[str] = None, **kwargs - ): + self, + *, + requires_client_authorization: Optional[bool] = None, + user_metadata: Optional[str] = None, + **kwargs: Any + ) -> None: """ :keyword requires_client_authorization: Returns true if client authorization is needed for this hybrid connection; otherwise, false. @@ -478,10 +354,9 @@ def __init__( :paramtype user_metadata: str """ super().__init__(**kwargs) - self.system_data = None - self.created_at = None - self.updated_at = None - self.listener_count = None + self.created_at: Optional[datetime.datetime] = None + self.updated_at: Optional[datetime.datetime] = None + self.listener_count: Optional[int] = None self.requires_client_authorization = requires_client_authorization self.user_metadata = user_metadata @@ -502,8 +377,12 @@ class HybridConnectionListResult(_serialization.Model): } def __init__( - self, *, value: Optional[List["_models.HybridConnection"]] = None, next_link: Optional[str] = None, **kwargs - ): + self, + *, + value: Optional[list["_models.HybridConnection"]] = None, + next_link: Optional[str] = None, + **kwargs: Any + ) -> None: """ :keyword value: Result of the list hybrid connections. :paramtype value: list[~azure.mgmt.relay.models.HybridConnection] @@ -516,136 +395,6 @@ def __init__( self.next_link = next_link -class Resource(_serialization.Model): - """The resource definition. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Resource ID. - :vartype id: str - :ivar name: Resource name. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - } - - def __init__(self, **kwargs): - """ """ - super().__init__(**kwargs) - self.id = None - self.name = None - self.type = None - - -class NetworkRuleSet(Resource): - """Description of topic resource. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Resource ID. - :vartype id: str - :ivar name: Resource name. - :vartype name: str - :ivar type: Resource type. - :vartype type: str - :ivar system_data: The system meta data relating to this resource. - :vartype system_data: ~azure.mgmt.relay.models.SystemData - :ivar default_action: Default Action for Network Rule Set. Known values are: "Allow" and - "Deny". - :vartype default_action: str or ~azure.mgmt.relay.models.DefaultAction - :ivar public_network_access: This determines if traffic is allowed over public network. By - default it is enabled. Known values are: "Enabled", "Disabled", and "SecuredByPerimeter". - :vartype public_network_access: str or ~azure.mgmt.relay.models.PublicNetworkAccess - :ivar ip_rules: List of IpRules. - :vartype ip_rules: list[~azure.mgmt.relay.models.NWRuleSetIpRules] - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "system_data": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "system_data": {"key": "systemData", "type": "SystemData"}, - "default_action": {"key": "properties.defaultAction", "type": "str"}, - "public_network_access": {"key": "properties.publicNetworkAccess", "type": "str"}, - "ip_rules": {"key": "properties.ipRules", "type": "[NWRuleSetIpRules]"}, - } - - def __init__( - self, - *, - default_action: Optional[Union[str, "_models.DefaultAction"]] = None, - public_network_access: Optional[Union[str, "_models.PublicNetworkAccess"]] = None, - ip_rules: Optional[List["_models.NWRuleSetIpRules"]] = None, - **kwargs - ): - """ - :keyword default_action: Default Action for Network Rule Set. Known values are: "Allow" and - "Deny". - :paramtype default_action: str or ~azure.mgmt.relay.models.DefaultAction - :keyword public_network_access: This determines if traffic is allowed over public network. By - default it is enabled. Known values are: "Enabled", "Disabled", and "SecuredByPerimeter". - :paramtype public_network_access: str or ~azure.mgmt.relay.models.PublicNetworkAccess - :keyword ip_rules: List of IpRules. - :paramtype ip_rules: list[~azure.mgmt.relay.models.NWRuleSetIpRules] - """ - super().__init__(**kwargs) - self.system_data = None - self.default_action = default_action - self.public_network_access = public_network_access - self.ip_rules = ip_rules - - -class NWRuleSetIpRules(_serialization.Model): - """The response from the List namespace operation. - - :ivar ip_mask: IP Mask. - :vartype ip_mask: str - :ivar action: The IP Filter Action. "Allow" - :vartype action: str or ~azure.mgmt.relay.models.NetworkRuleIPAction - """ - - _attribute_map = { - "ip_mask": {"key": "ipMask", "type": "str"}, - "action": {"key": "action", "type": "str"}, - } - - def __init__( - self, - *, - ip_mask: Optional[str] = None, - action: Optional[Union[str, "_models.NetworkRuleIPAction"]] = None, - **kwargs - ): - """ - :keyword ip_mask: IP Mask. - :paramtype ip_mask: str - :keyword action: The IP Filter Action. "Allow" - :paramtype action: str or ~azure.mgmt.relay.models.NetworkRuleIPAction - """ - super().__init__(**kwargs) - self.ip_mask = ip_mask - self.action = action - - class Operation(_serialization.Model): """A Relay REST API operation. @@ -653,88 +402,69 @@ class Operation(_serialization.Model): :ivar name: Operation name: {provider}/{resource}/{operation}. :vartype name: str - :ivar is_data_action: Indicates whether the operation is a data action. - :vartype is_data_action: bool - :ivar display: Display of the operation. + :ivar display: The object that represents the operation. :vartype display: ~azure.mgmt.relay.models.OperationDisplay - :ivar origin: Origin of the operation. - :vartype origin: str - :ivar properties: Properties of the operation. - :vartype properties: JSON """ _validation = { "name": {"readonly": True}, - "is_data_action": {"readonly": True}, - "display": {"readonly": True}, - "origin": {"readonly": True}, } _attribute_map = { "name": {"key": "name", "type": "str"}, - "is_data_action": {"key": "isDataAction", "type": "bool"}, "display": {"key": "display", "type": "OperationDisplay"}, - "origin": {"key": "origin", "type": "str"}, - "properties": {"key": "properties", "type": "object"}, } - def __init__(self, *, properties: Optional[JSON] = None, **kwargs): + def __init__(self, *, display: Optional["_models.OperationDisplay"] = None, **kwargs: Any) -> None: """ - :keyword properties: Properties of the operation. - :paramtype properties: JSON + :keyword display: The object that represents the operation. + :paramtype display: ~azure.mgmt.relay.models.OperationDisplay """ super().__init__(**kwargs) - self.name = None - self.is_data_action = None - self.display = None - self.origin = None - self.properties = properties + self.name: Optional[str] = None + self.display = display class OperationDisplay(_serialization.Model): - """Operation display payload. + """The object that represents the operation. Variables are only populated by the server, and will be ignored when sending a request. - :ivar provider: Resource provider of the operation. + :ivar provider: Service provider: Relay. :vartype provider: str - :ivar resource: Resource of the operation. + :ivar resource: Resource on which the operation is performed: Invoice, etc. :vartype resource: str - :ivar operation: Localized friendly name for the operation. + :ivar operation: Operation type: Read, write, delete, etc. :vartype operation: str - :ivar description: Localized friendly description for the operation. - :vartype description: str """ _validation = { "provider": {"readonly": True}, "resource": {"readonly": True}, "operation": {"readonly": True}, - "description": {"readonly": True}, } _attribute_map = { "provider": {"key": "provider", "type": "str"}, "resource": {"key": "resource", "type": "str"}, "operation": {"key": "operation", "type": "str"}, - "description": {"key": "description", "type": "str"}, } - def __init__(self, **kwargs): + def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) - self.provider = None - self.resource = None - self.operation = None - self.description = None + self.provider: Optional[str] = None + self.resource: Optional[str] = None + self.operation: Optional[str] = None class OperationListResult(_serialization.Model): - """Result of the request to list Relay operations. It contains a list of operations and a URL link to get the next set of results. + """Result of the request to list Relay 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. - :ivar value: List of Relay operations supported by the Microsoft.Relay resource provider. + :ivar value: List of Relay operations supported by resource provider. :vartype value: list[~azure.mgmt.relay.models.Operation] :ivar next_link: URL to get the next set of operation list results if there are any. :vartype next_link: str @@ -750,229 +480,18 @@ class OperationListResult(_serialization.Model): "next_link": {"key": "nextLink", "type": "str"}, } - def __init__(self, **kwargs): + def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) - self.value = None - self.next_link = None - - -class PrivateEndpoint(_serialization.Model): - """PrivateEndpoint information. - - :ivar id: The ARM identifier for Private Endpoint. - :vartype id: str - """ - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - } - - def __init__(self, *, id: Optional[str] = None, **kwargs): # pylint: disable=redefined-builtin - """ - :keyword id: The ARM identifier for Private Endpoint. - :paramtype id: str - """ - super().__init__(**kwargs) - self.id = id - - -class PrivateEndpointConnection(ProxyResource): - """Properties of the PrivateEndpointConnection. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: Fully qualified resource ID for the resource. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. - :vartype id: str - :ivar name: The name of the resource. - :vartype name: str - :ivar type: The type of the resource. E.g. "Microsoft.EventHub/Namespaces" or - "Microsoft.EventHub/Namespaces/EventHubs". - :vartype type: str - :ivar location: The geo-location where the resource lives. - :vartype location: str - :ivar system_data: The system meta data relating to this resource. - :vartype system_data: ~azure.mgmt.relay.models.SystemData - :ivar private_endpoint: The Private Endpoint resource for this Connection. - :vartype private_endpoint: ~azure.mgmt.relay.models.PrivateEndpoint - :ivar private_link_service_connection_state: Details about the state of the connection. - :vartype private_link_service_connection_state: ~azure.mgmt.relay.models.ConnectionState - :ivar provisioning_state: Provisioning state of the Private Endpoint Connection. Known values - are: "Creating", "Updating", "Deleting", "Succeeded", "Canceled", and "Failed". - :vartype provisioning_state: str or ~azure.mgmt.relay.models.EndPointProvisioningState - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "location": {"readonly": True}, - "system_data": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "location": {"key": "location", "type": "str"}, - "system_data": {"key": "systemData", "type": "SystemData"}, - "private_endpoint": {"key": "properties.privateEndpoint", "type": "PrivateEndpoint"}, - "private_link_service_connection_state": { - "key": "properties.privateLinkServiceConnectionState", - "type": "ConnectionState", - }, - "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, - } - - def __init__( - self, - *, - private_endpoint: Optional["_models.PrivateEndpoint"] = None, - private_link_service_connection_state: Optional["_models.ConnectionState"] = None, - provisioning_state: Optional[Union[str, "_models.EndPointProvisioningState"]] = None, - **kwargs - ): - """ - :keyword private_endpoint: The Private Endpoint resource for this Connection. - :paramtype private_endpoint: ~azure.mgmt.relay.models.PrivateEndpoint - :keyword private_link_service_connection_state: Details about the state of the connection. - :paramtype private_link_service_connection_state: ~azure.mgmt.relay.models.ConnectionState - :keyword provisioning_state: Provisioning state of the Private Endpoint Connection. Known - values are: "Creating", "Updating", "Deleting", "Succeeded", "Canceled", and "Failed". - :paramtype provisioning_state: str or ~azure.mgmt.relay.models.EndPointProvisioningState - """ - super().__init__(**kwargs) - self.system_data = None - self.private_endpoint = private_endpoint - self.private_link_service_connection_state = private_link_service_connection_state - self.provisioning_state = provisioning_state - - -class PrivateEndpointConnectionListResult(_serialization.Model): - """Result of the list of all private endpoint connections operation. - - :ivar value: A collection of private endpoint connection resources. - :vartype value: list[~azure.mgmt.relay.models.PrivateEndpointConnection] - :ivar next_link: A link for the next page of private endpoint connection resources. - :vartype next_link: str - """ - - _attribute_map = { - "value": {"key": "value", "type": "[PrivateEndpointConnection]"}, - "next_link": {"key": "nextLink", "type": "str"}, - } - - def __init__( - self, - *, - value: Optional[List["_models.PrivateEndpointConnection"]] = None, - next_link: Optional[str] = None, - **kwargs - ): - """ - :keyword value: A collection of private endpoint connection resources. - :paramtype value: list[~azure.mgmt.relay.models.PrivateEndpointConnection] - :keyword next_link: A link for the next page of private endpoint connection resources. - :paramtype next_link: str - """ - super().__init__(**kwargs) - self.value = value - self.next_link = next_link - - -class PrivateLinkResource(_serialization.Model): - """Information of the private link resource. - - :ivar id: Fully qualified identifier of the resource. - :vartype id: str - :ivar name: Name of the resource. - :vartype name: str - :ivar type: Type of the resource. - :vartype type: str - :ivar group_id: The private link resource group id. - :vartype group_id: str - :ivar required_members: The private link resource required member names. - :vartype required_members: list[str] - :ivar required_zone_names: The private link resource Private link DNS zone name. - :vartype required_zone_names: list[str] - """ - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "group_id": {"key": "properties.groupId", "type": "str"}, - "required_members": {"key": "properties.requiredMembers", "type": "[str]"}, - "required_zone_names": {"key": "properties.requiredZoneNames", "type": "[str]"}, - } - - def __init__( - self, - *, - id: Optional[str] = None, # pylint: disable=redefined-builtin - name: Optional[str] = None, - type: Optional[str] = None, - group_id: Optional[str] = None, - required_members: Optional[List[str]] = None, - required_zone_names: Optional[List[str]] = None, - **kwargs - ): - """ - :keyword id: Fully qualified identifier of the resource. - :paramtype id: str - :keyword name: Name of the resource. - :paramtype name: str - :keyword type: Type of the resource. - :paramtype type: str - :keyword group_id: The private link resource group id. - :paramtype group_id: str - :keyword required_members: The private link resource required member names. - :paramtype required_members: list[str] - :keyword required_zone_names: The private link resource Private link DNS zone name. - :paramtype required_zone_names: list[str] - """ - super().__init__(**kwargs) - self.id = id - self.name = name - self.type = type - self.group_id = group_id - self.required_members = required_members - self.required_zone_names = required_zone_names - - -class PrivateLinkResourcesListResult(_serialization.Model): - """Result of the List private link resources operation. - - :ivar value: A collection of private link resources. - :vartype value: list[~azure.mgmt.relay.models.PrivateLinkResource] - :ivar next_link: A link for the next page of private link resources. - :vartype next_link: str - """ - - _attribute_map = { - "value": {"key": "value", "type": "[PrivateLinkResource]"}, - "next_link": {"key": "nextLink", "type": "str"}, - } - - def __init__( - self, *, value: Optional[List["_models.PrivateLinkResource"]] = None, next_link: Optional[str] = None, **kwargs - ): - """ - :keyword value: A collection of private link resources. - :paramtype value: list[~azure.mgmt.relay.models.PrivateLinkResource] - :keyword next_link: A link for the next page of private link resources. - :paramtype next_link: str - """ - super().__init__(**kwargs) - self.value = value - self.next_link = next_link + self.value: Optional[list["_models.Operation"]] = None + self.next_link: Optional[str] = None class RegenerateAccessKeyParameters(_serialization.Model): - """Parameters supplied to the regenerate authorization rule operation, specifies which key needs to be reset. + """Parameters supplied to the regenerate authorization rule operation, specifies which key neeeds + to be reset. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. :ivar key_type: The access key to regenerate. Required. Known values are: "PrimaryKey" and "SecondaryKey". @@ -991,7 +510,7 @@ class RegenerateAccessKeyParameters(_serialization.Model): "key": {"key": "key", "type": "str"}, } - def __init__(self, *, key_type: Union[str, "_models.KeyType"], key: Optional[str] = None, **kwargs): + def __init__(self, *, key_type: Union[str, "_models.KeyType"], key: Optional[str] = None, **kwargs: Any) -> None: """ :keyword key_type: The access key to regenerate. Required. Known values are: "PrimaryKey" and "SecondaryKey". @@ -1010,7 +529,7 @@ class TrackedResource(Resource): Variables are only populated by the server, and will be ignored when sending a request. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. :ivar id: Resource ID. :vartype id: str @@ -1039,7 +558,7 @@ class TrackedResource(Resource): "tags": {"key": "tags", "type": "{str}"}, } - def __init__(self, *, location: str, tags: Optional[Dict[str, str]] = None, **kwargs): + def __init__(self, *, location: str, tags: Optional[dict[str, str]] = None, **kwargs: Any) -> None: """ :keyword location: Resource location. Required. :paramtype location: str @@ -1051,12 +570,12 @@ def __init__(self, *, location: str, tags: Optional[Dict[str, str]] = None, **kw self.tags = tags -class RelayNamespace(TrackedResource): # pylint: disable=too-many-instance-attributes +class RelayNamespace(TrackedResource): """Description of a namespace resource. Variables are only populated by the server, and will be ignored when sending a request. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. :ivar id: Resource ID. :vartype id: str @@ -1070,12 +589,9 @@ class RelayNamespace(TrackedResource): # pylint: disable=too-many-instance-attr :vartype tags: dict[str, str] :ivar sku: SKU of the namespace. :vartype sku: ~azure.mgmt.relay.models.Sku - :ivar system_data: The system meta data relating to this resource. - :vartype system_data: ~azure.mgmt.relay.models.SystemData - :ivar provisioning_state: Provisioning state of the Namespace. - :vartype provisioning_state: str - :ivar status: Status of the Namespace. - :vartype status: str + :ivar provisioning_state: Known values are: "Created", "Succeeded", "Deleted", "Failed", + "Updating", and "Unknown". + :vartype provisioning_state: str or ~azure.mgmt.relay.models.ProvisioningStateEnum :ivar created_at: The time the namespace was created. :vartype created_at: ~datetime.datetime :ivar updated_at: The time the namespace was updated. @@ -1084,11 +600,6 @@ class RelayNamespace(TrackedResource): # pylint: disable=too-many-instance-attr :vartype service_bus_endpoint: str :ivar metric_id: Identifier for Azure Insights metrics. :vartype metric_id: str - :ivar private_endpoint_connections: List of private endpoint connections. - :vartype private_endpoint_connections: list[~azure.mgmt.relay.models.PrivateEndpointConnection] - :ivar public_network_access: This determines if traffic is allowed over public network. By - default it is enabled. Known values are: "Enabled", "Disabled", and "SecuredByPerimeter". - :vartype public_network_access: str or ~azure.mgmt.relay.models.PublicNetworkAccess """ _validation = { @@ -1096,9 +607,7 @@ class RelayNamespace(TrackedResource): # pylint: disable=too-many-instance-attr "name": {"readonly": True}, "type": {"readonly": True}, "location": {"required": True}, - "system_data": {"readonly": True}, "provisioning_state": {"readonly": True}, - "status": {"readonly": True}, "created_at": {"readonly": True}, "updated_at": {"readonly": True}, "service_bus_endpoint": {"readonly": True}, @@ -1112,30 +621,21 @@ class RelayNamespace(TrackedResource): # pylint: disable=too-many-instance-attr "location": {"key": "location", "type": "str"}, "tags": {"key": "tags", "type": "{str}"}, "sku": {"key": "sku", "type": "Sku"}, - "system_data": {"key": "systemData", "type": "SystemData"}, "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, - "status": {"key": "properties.status", "type": "str"}, "created_at": {"key": "properties.createdAt", "type": "iso-8601"}, "updated_at": {"key": "properties.updatedAt", "type": "iso-8601"}, "service_bus_endpoint": {"key": "properties.serviceBusEndpoint", "type": "str"}, "metric_id": {"key": "properties.metricId", "type": "str"}, - "private_endpoint_connections": { - "key": "properties.privateEndpointConnections", - "type": "[PrivateEndpointConnection]", - }, - "public_network_access": {"key": "properties.publicNetworkAccess", "type": "str"}, } def __init__( self, *, location: str, - tags: Optional[Dict[str, str]] = None, + tags: Optional[dict[str, str]] = None, sku: Optional["_models.Sku"] = None, - private_endpoint_connections: Optional[List["_models.PrivateEndpointConnection"]] = None, - public_network_access: Optional[Union[str, "_models.PublicNetworkAccess"]] = None, - **kwargs - ): + **kwargs: Any + ) -> None: """ :keyword location: Resource location. Required. :paramtype location: str @@ -1143,24 +643,14 @@ def __init__( :paramtype tags: dict[str, str] :keyword sku: SKU of the namespace. :paramtype sku: ~azure.mgmt.relay.models.Sku - :keyword private_endpoint_connections: List of private endpoint connections. - :paramtype private_endpoint_connections: - list[~azure.mgmt.relay.models.PrivateEndpointConnection] - :keyword public_network_access: This determines if traffic is allowed over public network. By - default it is enabled. Known values are: "Enabled", "Disabled", and "SecuredByPerimeter". - :paramtype public_network_access: str or ~azure.mgmt.relay.models.PublicNetworkAccess """ super().__init__(location=location, tags=tags, **kwargs) self.sku = sku - self.system_data = None - self.provisioning_state = None - self.status = None - self.created_at = None - self.updated_at = None - self.service_bus_endpoint = None - self.metric_id = None - self.private_endpoint_connections = private_endpoint_connections - self.public_network_access = public_network_access + self.provisioning_state: Optional[Union[str, "_models.ProvisioningStateEnum"]] = None + self.created_at: Optional[datetime.datetime] = None + self.updated_at: Optional[datetime.datetime] = None + self.service_bus_endpoint: Optional[str] = None + self.metric_id: Optional[str] = None class RelayNamespaceListResult(_serialization.Model): @@ -1179,8 +669,8 @@ class RelayNamespaceListResult(_serialization.Model): } def __init__( - self, *, value: Optional[List["_models.RelayNamespace"]] = None, next_link: Optional[str] = None, **kwargs - ): + self, *, value: Optional[list["_models.RelayNamespace"]] = None, next_link: Optional[str] = None, **kwargs: Any + ) -> None: """ :keyword value: Result of the list namespace operation. :paramtype value: list[~azure.mgmt.relay.models.RelayNamespace] @@ -1221,7 +711,7 @@ class ResourceNamespacePatch(Resource): "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: Any) -> None: """ :keyword tags: Resource tags. :paramtype tags: dict[str, str] @@ -1230,7 +720,7 @@ def __init__(self, *, tags: Optional[Dict[str, str]] = None, **kwargs): self.tags = tags -class RelayUpdateParameters(ResourceNamespacePatch): # pylint: disable=too-many-instance-attributes +class RelayUpdateParameters(ResourceNamespacePatch): """Description of a namespace resource. Variables are only populated by the server, and will be ignored when sending a request. @@ -1245,10 +735,9 @@ class RelayUpdateParameters(ResourceNamespacePatch): # pylint: disable=too-many :vartype tags: dict[str, str] :ivar sku: SKU of the namespace. :vartype sku: ~azure.mgmt.relay.models.Sku - :ivar provisioning_state: Provisioning state of the Namespace. - :vartype provisioning_state: str - :ivar status: Status of the Namespace. - :vartype status: str + :ivar provisioning_state: Known values are: "Created", "Succeeded", "Deleted", "Failed", + "Updating", and "Unknown". + :vartype provisioning_state: str or ~azure.mgmt.relay.models.ProvisioningStateEnum :ivar created_at: The time the namespace was created. :vartype created_at: ~datetime.datetime :ivar updated_at: The time the namespace was updated. @@ -1257,11 +746,6 @@ class RelayUpdateParameters(ResourceNamespacePatch): # pylint: disable=too-many :vartype service_bus_endpoint: str :ivar metric_id: Identifier for Azure Insights metrics. :vartype metric_id: str - :ivar private_endpoint_connections: List of private endpoint connections. - :vartype private_endpoint_connections: list[~azure.mgmt.relay.models.PrivateEndpointConnection] - :ivar public_network_access: This determines if traffic is allowed over public network. By - default it is enabled. Known values are: "Enabled", "Disabled", and "SecuredByPerimeter". - :vartype public_network_access: str or ~azure.mgmt.relay.models.PublicNetworkAccess """ _validation = { @@ -1269,7 +753,6 @@ class RelayUpdateParameters(ResourceNamespacePatch): # pylint: disable=too-many "name": {"readonly": True}, "type": {"readonly": True}, "provisioning_state": {"readonly": True}, - "status": {"readonly": True}, "created_at": {"readonly": True}, "updated_at": {"readonly": True}, "service_bus_endpoint": {"readonly": True}, @@ -1283,64 +766,45 @@ class RelayUpdateParameters(ResourceNamespacePatch): # pylint: disable=too-many "tags": {"key": "tags", "type": "{str}"}, "sku": {"key": "sku", "type": "Sku"}, "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, - "status": {"key": "properties.status", "type": "str"}, "created_at": {"key": "properties.createdAt", "type": "iso-8601"}, "updated_at": {"key": "properties.updatedAt", "type": "iso-8601"}, "service_bus_endpoint": {"key": "properties.serviceBusEndpoint", "type": "str"}, "metric_id": {"key": "properties.metricId", "type": "str"}, - "private_endpoint_connections": { - "key": "properties.privateEndpointConnections", - "type": "[PrivateEndpointConnection]", - }, - "public_network_access": {"key": "properties.publicNetworkAccess", "type": "str"}, } def __init__( - self, - *, - tags: Optional[Dict[str, str]] = None, - sku: Optional["_models.Sku"] = None, - private_endpoint_connections: Optional[List["_models.PrivateEndpointConnection"]] = None, - public_network_access: Optional[Union[str, "_models.PublicNetworkAccess"]] = None, - **kwargs - ): + self, *, tags: Optional[dict[str, str]] = None, sku: Optional["_models.Sku"] = None, **kwargs: Any + ) -> None: """ :keyword tags: Resource tags. :paramtype tags: dict[str, str] :keyword sku: SKU of the namespace. :paramtype sku: ~azure.mgmt.relay.models.Sku - :keyword private_endpoint_connections: List of private endpoint connections. - :paramtype private_endpoint_connections: - list[~azure.mgmt.relay.models.PrivateEndpointConnection] - :keyword public_network_access: This determines if traffic is allowed over public network. By - default it is enabled. Known values are: "Enabled", "Disabled", and "SecuredByPerimeter". - :paramtype public_network_access: str or ~azure.mgmt.relay.models.PublicNetworkAccess """ super().__init__(tags=tags, **kwargs) self.sku = sku - self.provisioning_state = None - self.status = None - self.created_at = None - self.updated_at = None - self.service_bus_endpoint = None - self.metric_id = None - self.private_endpoint_connections = private_endpoint_connections - self.public_network_access = public_network_access + self.provisioning_state: Optional[Union[str, "_models.ProvisioningStateEnum"]] = None + self.created_at: Optional[datetime.datetime] = None + self.updated_at: Optional[datetime.datetime] = None + self.service_bus_endpoint: Optional[str] = None + self.metric_id: Optional[str] = None class Sku(_serialization.Model): """SKU of the namespace. - All required parameters must be populated in order to send to Azure. + 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 server. - :ivar name: Name of this SKU. Required. "Standard" - :vartype name: str or ~azure.mgmt.relay.models.SkuName - :ivar tier: The tier of this SKU. "Standard" - :vartype tier: str or ~azure.mgmt.relay.models.SkuTier + :ivar name: Name of this SKU. Required. Default value is "Standard". + :vartype name: str + :ivar tier: The tier of this SKU. Default value is "Standard". + :vartype tier: str """ _validation = { - "name": {"required": True}, + "name": {"required": True, "constant": True}, } _attribute_map = { @@ -1348,101 +812,28 @@ class Sku(_serialization.Model): "tier": {"key": "tier", "type": "str"}, } - def __init__( - self, *, name: Union[str, "_models.SkuName"], tier: Optional[Union[str, "_models.SkuTier"]] = None, **kwargs - ): - """ - :keyword name: Name of this SKU. Required. "Standard" - :paramtype name: str or ~azure.mgmt.relay.models.SkuName - :keyword tier: The tier of this SKU. "Standard" - :paramtype tier: str or ~azure.mgmt.relay.models.SkuTier - """ - super().__init__(**kwargs) - self.name = name - self.tier = tier - + name = "Standard" -class SystemData(_serialization.Model): - """Metadata pertaining to creation and last modification of the resource. - - :ivar created_by: The identity that created the resource. - :vartype created_by: str - :ivar created_by_type: The type of identity that created the resource. Known values are: - "User", "Application", "ManagedIdentity", and "Key". - :vartype created_by_type: str or ~azure.mgmt.relay.models.CreatedByType - :ivar created_at: The timestamp of resource creation (UTC). - :vartype created_at: ~datetime.datetime - :ivar last_modified_by: The identity that last modified the resource. - :vartype last_modified_by: str - :ivar last_modified_by_type: The type of identity that last modified the resource. Known values - are: "User", "Application", "ManagedIdentity", and "Key". - :vartype last_modified_by_type: str or ~azure.mgmt.relay.models.CreatedByType - :ivar last_modified_at: The timestamp of resource last modification (UTC). - :vartype last_modified_at: ~datetime.datetime - """ - - _attribute_map = { - "created_by": {"key": "createdBy", "type": "str"}, - "created_by_type": {"key": "createdByType", "type": "str"}, - "created_at": {"key": "createdAt", "type": "iso-8601"}, - "last_modified_by": {"key": "lastModifiedBy", "type": "str"}, - "last_modified_by_type": {"key": "lastModifiedByType", "type": "str"}, - "last_modified_at": {"key": "lastModifiedAt", "type": "iso-8601"}, - } - - def __init__( - self, - *, - created_by: Optional[str] = None, - created_by_type: Optional[Union[str, "_models.CreatedByType"]] = None, - created_at: Optional[datetime.datetime] = None, - last_modified_by: Optional[str] = None, - last_modified_by_type: Optional[Union[str, "_models.CreatedByType"]] = None, - last_modified_at: Optional[datetime.datetime] = None, - **kwargs - ): + def __init__(self, *, tier: Optional[Literal["Standard"]] = None, **kwargs: Any) -> None: """ - :keyword created_by: The identity that created the resource. - :paramtype created_by: str - :keyword created_by_type: The type of identity that created the resource. Known values are: - "User", "Application", "ManagedIdentity", and "Key". - :paramtype created_by_type: str or ~azure.mgmt.relay.models.CreatedByType - :keyword created_at: The timestamp of resource creation (UTC). - :paramtype created_at: ~datetime.datetime - :keyword last_modified_by: The identity that last modified the resource. - :paramtype last_modified_by: str - :keyword last_modified_by_type: The type of identity that last modified the resource. Known - values are: "User", "Application", "ManagedIdentity", and "Key". - :paramtype last_modified_by_type: str or ~azure.mgmt.relay.models.CreatedByType - :keyword last_modified_at: The timestamp of resource last modification (UTC). - :paramtype last_modified_at: ~datetime.datetime + :keyword tier: The tier of this SKU. Default value is "Standard". + :paramtype tier: str """ super().__init__(**kwargs) - self.created_by = created_by - self.created_by_type = created_by_type - self.created_at = created_at - self.last_modified_by = last_modified_by - self.last_modified_by_type = last_modified_by_type - self.last_modified_at = last_modified_at + self.tier = tier -class WcfRelay(ProxyResource): # pylint: disable=too-many-instance-attributes +class WcfRelay(Resource): """Description of the WCF relay resource. Variables are only populated by the server, and will be ignored when sending a request. - :ivar id: Fully qualified resource ID for the resource. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :ivar id: Resource ID. :vartype id: str - :ivar name: The name of the resource. + :ivar name: Resource name. :vartype name: str - :ivar type: The type of the resource. E.g. "Microsoft.EventHub/Namespaces" or - "Microsoft.EventHub/Namespaces/EventHubs". + :ivar type: Resource type. :vartype type: str - :ivar location: The geo-location where the resource lives. - :vartype location: str - :ivar system_data: The system meta data relating to this resource. - :vartype system_data: ~azure.mgmt.relay.models.SystemData :ivar is_dynamic: Returns true if the relay is dynamic; otherwise, false. :vartype is_dynamic: bool :ivar created_at: The time the WCF relay was created. @@ -1470,8 +861,6 @@ class WcfRelay(ProxyResource): # pylint: disable=too-many-instance-attributes "id": {"readonly": True}, "name": {"readonly": True}, "type": {"readonly": True}, - "location": {"readonly": True}, - "system_data": {"readonly": True}, "is_dynamic": {"readonly": True}, "created_at": {"readonly": True}, "updated_at": {"readonly": True}, @@ -1482,8 +871,6 @@ class WcfRelay(ProxyResource): # pylint: disable=too-many-instance-attributes "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, - "location": {"key": "location", "type": "str"}, - "system_data": {"key": "systemData", "type": "SystemData"}, "is_dynamic": {"key": "properties.isDynamic", "type": "bool"}, "created_at": {"key": "properties.createdAt", "type": "iso-8601"}, "updated_at": {"key": "properties.updatedAt", "type": "iso-8601"}, @@ -1501,8 +888,8 @@ def __init__( requires_client_authorization: Optional[bool] = None, requires_transport_security: Optional[bool] = None, user_metadata: Optional[str] = None, - **kwargs - ): + **kwargs: Any + ) -> None: """ :keyword relay_type: WCF relay type. Known values are: "NetTcp" and "Http". :paramtype relay_type: str or ~azure.mgmt.relay.models.Relaytype @@ -1518,11 +905,10 @@ def __init__( :paramtype user_metadata: str """ super().__init__(**kwargs) - self.system_data = None - self.is_dynamic = None - self.created_at = None - self.updated_at = None - self.listener_count = None + self.is_dynamic: Optional[bool] = None + self.created_at: Optional[datetime.datetime] = None + self.updated_at: Optional[datetime.datetime] = None + self.listener_count: Optional[int] = None self.relay_type = relay_type self.requires_client_authorization = requires_client_authorization self.requires_transport_security = requires_transport_security @@ -1544,7 +930,9 @@ class WcfRelaysListResult(_serialization.Model): "next_link": {"key": "nextLink", "type": "str"}, } - def __init__(self, *, value: Optional[List["_models.WcfRelay"]] = None, next_link: Optional[str] = None, **kwargs): + def __init__( + self, *, value: Optional[list["_models.WcfRelay"]] = None, next_link: Optional[str] = None, **kwargs: Any + ) -> None: """ :keyword value: Result of the list WCF relay operation. :paramtype value: list[~azure.mgmt.relay.models.WcfRelay] diff --git a/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/models/_relay_api_enums.py b/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/models/_relay_api_enums.py index dfaa1c8f28fc..7a3e527504e8 100644 --- a/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/models/_relay_api_enums.py +++ b/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/models/_relay_api_enums.py @@ -18,33 +18,6 @@ class AccessRights(str, Enum, metaclass=CaseInsensitiveEnumMeta): LISTEN = "Listen" -class CreatedByType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The type of identity that created the resource.""" - - USER = "User" - APPLICATION = "Application" - MANAGED_IDENTITY = "ManagedIdentity" - KEY = "Key" - - -class DefaultAction(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Default Action for Network Rule Set.""" - - ALLOW = "Allow" - DENY = "Deny" - - -class EndPointProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Provisioning state of the Private Endpoint Connection.""" - - CREATING = "Creating" - UPDATING = "Updating" - DELETING = "Deleting" - SUCCEEDED = "Succeeded" - CANCELED = "Canceled" - FAILED = "Failed" - - class KeyType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The access key to regenerate.""" @@ -52,27 +25,15 @@ class KeyType(str, Enum, metaclass=CaseInsensitiveEnumMeta): SECONDARY_KEY = "SecondaryKey" -class NetworkRuleIPAction(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The IP Filter Action.""" - - ALLOW = "Allow" - +class ProvisioningStateEnum(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """ProvisioningStateEnum.""" -class PrivateLinkConnectionStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Status of the connection.""" - - PENDING = "Pending" - APPROVED = "Approved" - REJECTED = "Rejected" - DISCONNECTED = "Disconnected" - - -class PublicNetworkAccess(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """This determines if traffic is allowed over public network. By default it is enabled.""" - - ENABLED = "Enabled" - DISABLED = "Disabled" - SECURED_BY_PERIMETER = "SecuredByPerimeter" + CREATED = "Created" + SUCCEEDED = "Succeeded" + DELETED = "Deleted" + FAILED = "Failed" + UPDATING = "Updating" + UNKNOWN = "Unknown" class Relaytype(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -82,18 +43,6 @@ class Relaytype(str, Enum, metaclass=CaseInsensitiveEnumMeta): HTTP = "Http" -class SkuName(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Name of this SKU.""" - - STANDARD = "Standard" - - -class SkuTier(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The tier of this SKU.""" - - STANDARD = "Standard" - - class UnavailableReason(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Specifies the reason for the unavailability of the service.""" diff --git a/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/operations/__init__.py b/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/operations/__init__.py index f12431b0cd96..50a5eb52a45c 100644 --- a/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/operations/__init__.py +++ b/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/operations/__init__.py @@ -5,25 +5,27 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._namespaces_operations import NamespacesOperations -from ._hybrid_connections_operations import HybridConnectionsOperations -from ._wcf_relays_operations import WCFRelaysOperations -from ._private_endpoint_connections_operations import PrivateEndpointConnectionsOperations -from ._private_link_resources_operations import PrivateLinkResourcesOperations -from ._operations import Operations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._operations import Operations # type: ignore +from ._namespaces_operations import NamespacesOperations # type: ignore +from ._hybrid_connections_operations import HybridConnectionsOperations # type: ignore +from ._wcf_relays_operations import WCFRelaysOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ + "Operations", "NamespacesOperations", "HybridConnectionsOperations", "WCFRelaysOperations", - "PrivateEndpointConnectionsOperations", - "PrivateLinkResourcesOperations", - "Operations", ] -__all__.extend([p for p in _patch_all if p not in __all__]) +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/operations/_hybrid_connections_operations.py b/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/operations/_hybrid_connections_operations.py index 616dd6300893..fc3cbffbbe72 100644 --- a/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/operations/_hybrid_connections_operations.py +++ b/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/operations/_hybrid_connections_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=line-too-long,useless-suppression,too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,10 +6,12 @@ # 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, overload +from collections.abc import MutableMapping +from io import IOBase +from typing import Any, Callable, IO, Optional, TypeVar, Union, overload import urllib.parse +from azure.core import PipelineClient from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, @@ -20,51 +22,46 @@ ) 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.rest import HttpRequest, HttpResponse 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 +from .._configuration import RelayAPIConfiguration +from .._utils.serialization import Deserializer, Serializer -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]] +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] +List = list _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_list_authorization_rules_request( - resource_group_name: str, namespace_name: str, hybrid_connection_name: str, subscription_id: str, **kwargs: Any +def build_list_by_namespace_request( + resource_group_name: str, namespace_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-11-01")) # type: Literal["2021-11-01"] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-04-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/hybridConnections/{hybridConnectionName}/authorizationRules", - ) # pylint: disable=line-too-long + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/hybridConnections", + ) path_format_arguments = { "resourceGroupName": _SERIALIZER.url( "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 ), "namespaceName": _SERIALIZER.url("namespace_name", namespace_name, "str", max_length=50, min_length=6), - "hybridConnectionName": _SERIALIZER.url("hybrid_connection_name", hybrid_connection_name, "str", min_length=1), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -75,39 +72,31 @@ def build_list_authorization_rules_request( return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_create_or_update_authorization_rule_request( - resource_group_name: str, - namespace_name: str, - hybrid_connection_name: str, - authorization_rule_name: str, - subscription_id: str, - **kwargs: Any +def build_create_or_update_request( + resource_group_name: str, namespace_name: str, hybrid_connection_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-11-01")) # type: Literal["2021-11-01"] - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/hybridConnections/{hybridConnectionName}/authorizationRules/{authorizationRuleName}", - ) # pylint: disable=line-too-long + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/hybridConnections/{hybridConnectionName}", + ) path_format_arguments = { "resourceGroupName": _SERIALIZER.url( "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 ), "namespaceName": _SERIALIZER.url("namespace_name", namespace_name, "str", max_length=50, min_length=6), "hybridConnectionName": _SERIALIZER.url("hybrid_connection_name", hybrid_connection_name, "str", min_length=1), - "authorizationRuleName": _SERIALIZER.url( - "authorization_rule_name", authorization_rule_name, "str", min_length=1 - ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -120,38 +109,30 @@ def build_create_or_update_authorization_rule_request( return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) -def build_delete_authorization_rule_request( - resource_group_name: str, - namespace_name: str, - hybrid_connection_name: str, - authorization_rule_name: str, - subscription_id: str, - **kwargs: Any +def build_delete_request( + resource_group_name: str, namespace_name: str, hybrid_connection_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-11-01")) # type: Literal["2021-11-01"] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-04-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/hybridConnections/{hybridConnectionName}/authorizationRules/{authorizationRuleName}", - ) # pylint: disable=line-too-long + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/hybridConnections/{hybridConnectionName}", + ) path_format_arguments = { "resourceGroupName": _SERIALIZER.url( "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 ), "namespaceName": _SERIALIZER.url("namespace_name", namespace_name, "str", max_length=50, min_length=6), "hybridConnectionName": _SERIALIZER.url("hybrid_connection_name", hybrid_connection_name, "str", min_length=1), - "authorizationRuleName": _SERIALIZER.url( - "authorization_rule_name", authorization_rule_name, "str", min_length=1 - ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -162,38 +143,30 @@ def build_delete_authorization_rule_request( return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) -def build_get_authorization_rule_request( - resource_group_name: str, - namespace_name: str, - hybrid_connection_name: str, - authorization_rule_name: str, - subscription_id: str, - **kwargs: Any +def build_get_request( + resource_group_name: str, namespace_name: str, hybrid_connection_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-11-01")) # type: Literal["2021-11-01"] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-04-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/hybridConnections/{hybridConnectionName}/authorizationRules/{authorizationRuleName}", - ) # pylint: disable=line-too-long + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/hybridConnections/{hybridConnectionName}", + ) path_format_arguments = { "resourceGroupName": _SERIALIZER.url( "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 ), "namespaceName": _SERIALIZER.url("namespace_name", namespace_name, "str", max_length=50, min_length=6), "hybridConnectionName": _SERIALIZER.url("hybrid_connection_name", hybrid_connection_name, "str", min_length=1), - "authorizationRuleName": _SERIALIZER.url( - "authorization_rule_name", authorization_rule_name, "str", min_length=1 - ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -204,38 +177,30 @@ def build_get_authorization_rule_request( return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_list_keys_request( - resource_group_name: str, - namespace_name: str, - hybrid_connection_name: str, - authorization_rule_name: str, - subscription_id: str, - **kwargs: Any +def build_list_authorization_rules_request( + resource_group_name: str, namespace_name: str, hybrid_connection_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-11-01")) # type: Literal["2021-11-01"] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-04-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/hybridConnections/{hybridConnectionName}/authorizationRules/{authorizationRuleName}/listKeys", - ) # pylint: disable=line-too-long + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/hybridConnections/{hybridConnectionName}/authorizationRules", + ) path_format_arguments = { "resourceGroupName": _SERIALIZER.url( "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 ), "namespaceName": _SERIALIZER.url("namespace_name", namespace_name, "str", max_length=50, min_length=6), "hybridConnectionName": _SERIALIZER.url("hybrid_connection_name", hybrid_connection_name, "str", min_length=1), - "authorizationRuleName": _SERIALIZER.url( - "authorization_rule_name", authorization_rule_name, "str", min_length=1 - ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -243,10 +208,10 @@ def build_list_keys_request( # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_regenerate_keys_request( +def build_create_or_update_authorization_rule_request( # pylint: disable=name-too-long resource_group_name: str, namespace_name: str, hybrid_connection_name: str, @@ -257,15 +222,15 @@ def build_regenerate_keys_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-11-01")) # type: Literal["2021-11-01"] - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/hybridConnections/{hybridConnectionName}/authorizationRules/{authorizationRuleName}/regenerateKeys", - ) # pylint: disable=line-too-long + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/hybridConnections/{hybridConnectionName}/authorizationRules/{authorizationRuleName}", + ) path_format_arguments = { "resourceGroupName": _SERIALIZER.url( "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 @@ -278,7 +243,7 @@ def build_regenerate_keys_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -288,32 +253,41 @@ def build_regenerate_keys_request( _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) + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) -def build_list_by_namespace_request( - resource_group_name: str, namespace_name: str, subscription_id: str, **kwargs: Any +def build_delete_authorization_rule_request( + resource_group_name: str, + namespace_name: str, + hybrid_connection_name: str, + authorization_rule_name: str, + subscription_id: str, + **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-11-01")) # type: Literal["2021-11-01"] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-04-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/hybridConnections", - ) # pylint: disable=line-too-long + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/hybridConnections/{hybridConnectionName}/authorizationRules/{authorizationRuleName}", + ) path_format_arguments = { "resourceGroupName": _SERIALIZER.url( "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 ), "namespaceName": _SERIALIZER.url("namespace_name", namespace_name, "str", max_length=50, min_length=6), + "hybridConnectionName": _SERIALIZER.url("hybrid_connection_name", hybrid_connection_name, "str", min_length=1), + "authorizationRuleName": _SERIALIZER.url( + "authorization_rule_name", authorization_rule_name, "str", min_length=1 + ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -321,70 +295,83 @@ def build_list_by_namespace_request( # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) -def build_create_or_update_request( - resource_group_name: str, namespace_name: str, hybrid_connection_name: str, subscription_id: str, **kwargs: Any +def build_get_authorization_rule_request( + resource_group_name: str, + namespace_name: str, + hybrid_connection_name: str, + authorization_rule_name: str, + subscription_id: str, + **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-11-01")) # type: Literal["2021-11-01"] - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-04-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/hybridConnections/{hybridConnectionName}", - ) # pylint: disable=line-too-long + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/hybridConnections/{hybridConnectionName}/authorizationRules/{authorizationRuleName}", + ) path_format_arguments = { "resourceGroupName": _SERIALIZER.url( "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 ), "namespaceName": _SERIALIZER.url("namespace_name", namespace_name, "str", max_length=50, min_length=6), "hybridConnectionName": _SERIALIZER.url("hybrid_connection_name", hybrid_connection_name, "str", min_length=1), + "authorizationRuleName": _SERIALIZER.url( + "authorization_rule_name", authorization_rule_name, "str", min_length=1 + ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_delete_request( - resource_group_name: str, namespace_name: str, hybrid_connection_name: str, subscription_id: str, **kwargs: Any +def build_list_keys_request( + resource_group_name: str, + namespace_name: str, + hybrid_connection_name: str, + authorization_rule_name: str, + subscription_id: str, + **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-11-01")) # type: Literal["2021-11-01"] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-04-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/hybridConnections/{hybridConnectionName}", - ) # pylint: disable=line-too-long + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/hybridConnections/{hybridConnectionName}/authorizationRules/{authorizationRuleName}/listKeys", + ) path_format_arguments = { "resourceGroupName": _SERIALIZER.url( "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 ), "namespaceName": _SERIALIZER.url("namespace_name", namespace_name, "str", max_length=50, min_length=6), "hybridConnectionName": _SERIALIZER.url("hybrid_connection_name", hybrid_connection_name, "str", min_length=1), + "authorizationRuleName": _SERIALIZER.url( + "authorization_rule_name", authorization_rule_name, "str", min_length=1 + ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -392,41 +379,52 @@ def build_delete_request( # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_get_request( - resource_group_name: str, namespace_name: str, hybrid_connection_name: str, subscription_id: str, **kwargs: Any +def build_regenerate_keys_request( + resource_group_name: str, + namespace_name: str, + hybrid_connection_name: str, + authorization_rule_name: str, + subscription_id: str, + **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-11-01")) # type: Literal["2021-11-01"] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/hybridConnections/{hybridConnectionName}", - ) # pylint: disable=line-too-long + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/hybridConnections/{hybridConnectionName}/authorizationRules/{authorizationRuleName}/regenerateKeys", + ) path_format_arguments = { "resourceGroupName": _SERIALIZER.url( "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 ), "namespaceName": _SERIALIZER.url("namespace_name", namespace_name, "str", max_length=50, min_length=6), "hybridConnectionName": _SERIALIZER.url("hybrid_connection_name", hybrid_connection_name, "str", min_length=1), + "authorizationRuleName": _SERIALIZER.url( + "authorization_rule_name", authorization_rule_name, "str", min_length=1 + ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _url.format(**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="GET", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) class HybridConnectionsOperations: @@ -441,39 +439,34 @@ class HybridConnectionsOperations: models = _models - def __init__(self, *args, **kwargs): + 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") + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: RelayAPIConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace - def list_authorization_rules( - self, resource_group_name: str, namespace_name: str, hybrid_connection_name: str, **kwargs: Any - ) -> Iterable["_models.AuthorizationRule"]: - """Authorization rules for a hybrid connection. + def list_by_namespace( + self, resource_group_name: str, namespace_name: str, **kwargs: Any + ) -> ItemPaged["_models.HybridConnection"]: + """Lists the hybrid connection within the namespace. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str :param namespace_name: The namespace name. Required. :type namespace_name: str - :param hybrid_connection_name: The hybrid connection name. Required. - :type hybrid_connection_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either AuthorizationRule or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.relay.models.AuthorizationRule] + :return: An iterator like instance of either HybridConnection or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.relay.models.HybridConnection] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - cls = kwargs.pop("cls", None) # type: ClsType[_models.AuthorizationRuleListResult] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.HybridConnectionListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -484,18 +477,15 @@ def list_authorization_rules( def prepare_request(next_link=None): if not next_link: - request = build_list_authorization_rules_request( + _request = build_list_by_namespace_request( resource_group_name=resource_group_name, namespace_name=namespace_name, - hybrid_connection_name=hybrid_connection_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_authorization_rules.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -507,53 +497,53 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _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) # type: ignore - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): - deserialized = self._deserialize("AuthorizationRuleListResult", pipeline_response) + deserialized = self._deserialize("HybridConnectionListResult", 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) + _request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + 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_authorization_rules.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/hybridConnections/{hybridConnectionName}/authorizationRules"} # type: ignore - @overload - def create_or_update_authorization_rule( + def create_or_update( self, resource_group_name: str, namespace_name: str, hybrid_connection_name: str, - authorization_rule_name: str, - parameters: _models.AuthorizationRule, + parameters: _models.HybridConnection, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.AuthorizationRule: - """Creates or updates an authorization rule for a hybrid connection. + ) -> _models.HybridConnection: + """Creates or updates a service hybrid connection. This operation is idempotent. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str @@ -561,32 +551,28 @@ def create_or_update_authorization_rule( :type namespace_name: str :param hybrid_connection_name: The hybrid connection name. Required. :type hybrid_connection_name: str - :param authorization_rule_name: The authorization rule name. Required. - :type authorization_rule_name: str - :param parameters: The authorization rule parameters. Required. - :type parameters: ~azure.mgmt.relay.models.AuthorizationRule + :param parameters: Parameters supplied to create a hybrid connection. Required. + :type parameters: ~azure.mgmt.relay.models.HybridConnection :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: AuthorizationRule or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.AuthorizationRule + :return: HybridConnection or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.HybridConnection :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def create_or_update_authorization_rule( + def create_or_update( self, resource_group_name: str, namespace_name: str, hybrid_connection_name: str, - authorization_rule_name: str, - parameters: IO, + parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.AuthorizationRule: - """Creates or updates an authorization rule for a hybrid connection. + ) -> _models.HybridConnection: + """Creates or updates a service hybrid connection. This operation is idempotent. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str @@ -594,30 +580,26 @@ def create_or_update_authorization_rule( :type namespace_name: str :param hybrid_connection_name: The hybrid connection name. Required. :type hybrid_connection_name: str - :param authorization_rule_name: The authorization rule name. Required. - :type authorization_rule_name: str - :param parameters: The authorization rule parameters. Required. - :type parameters: IO + :param parameters: Parameters supplied to create a hybrid connection. Required. + :type parameters: IO[bytes] :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: AuthorizationRule or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.AuthorizationRule + :return: HybridConnection or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.HybridConnection :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace - def create_or_update_authorization_rule( + def create_or_update( self, resource_group_name: str, namespace_name: str, hybrid_connection_name: str, - authorization_rule_name: str, - parameters: Union[_models.AuthorizationRule, IO], + parameters: Union[_models.HybridConnection, IO[bytes]], **kwargs: Any - ) -> _models.AuthorizationRule: - """Creates or updates an authorization rule for a hybrid connection. + ) -> _models.HybridConnection: + """Creates or updates a service hybrid connection. This operation is idempotent. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str @@ -625,20 +607,14 @@ def create_or_update_authorization_rule( :type namespace_name: str :param hybrid_connection_name: The hybrid connection name. Required. :type hybrid_connection_name: str - :param authorization_rule_name: The authorization rule name. Required. - :type authorization_rule_name: str - :param parameters: The authorization rule parameters. Is either a model type or a IO type. - Required. - :type parameters: ~azure.mgmt.relay.models.AuthorizationRule 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: AuthorizationRule or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.AuthorizationRule + :param parameters: Parameters supplied to create a hybrid connection. Is either a + HybridConnection type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.relay.models.HybridConnection or IO[bytes] + :return: HybridConnection or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.HybridConnection :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -649,67 +625,59 @@ def create_or_update_authorization_rule( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - cls = kwargs.pop("cls", None) # type: ClsType[_models.AuthorizationRule] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.HybridConnection] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(parameters, (IO, bytes)): + if isinstance(parameters, (IOBase, bytes)): _content = parameters else: - _json = self._serialize.body(parameters, "AuthorizationRule") + _json = self._serialize.body(parameters, "HybridConnection") - request = build_create_or_update_authorization_rule_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, namespace_name=namespace_name, hybrid_connection_name=hybrid_connection_name, - authorization_rule_name=authorization_rule_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_authorization_rule.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("AuthorizationRule", pipeline_response) + deserialized = self._deserialize("HybridConnection", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - create_or_update_authorization_rule.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/hybridConnections/{hybridConnectionName}/authorizationRules/{authorizationRuleName}"} # type: ignore + return deserialized # type: ignore @distributed_trace - def delete_authorization_rule( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - namespace_name: str, - hybrid_connection_name: str, - authorization_rule_name: str, - **kwargs: Any + def delete( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, namespace_name: str, hybrid_connection_name: str, **kwargs: Any ) -> None: - """Deletes a hybrid connection authorization rule. + """Deletes a hybrid connection. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str @@ -717,14 +685,11 @@ def delete_authorization_rule( # pylint: disable=inconsistent-return-statements :type namespace_name: str :param hybrid_connection_name: The hybrid connection name. Required. :type hybrid_connection_name: str - :param authorization_rule_name: The authorization rule name. Required. - :type authorization_rule_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -735,51 +700,43 @@ def delete_authorization_rule( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - cls = kwargs.pop("cls", None) # type: ClsType[None] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_authorization_rule_request( + _request = build_delete_request( resource_group_name=resource_group_name, namespace_name=namespace_name, hybrid_connection_name=hybrid_connection_name, - authorization_rule_name=authorization_rule_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.delete_authorization_rule.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + 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_authorization_rule.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/hybridConnections/{hybridConnectionName}/authorizationRules/{authorizationRuleName}"} # type: ignore + return cls(pipeline_response, None, {}) # type: ignore @distributed_trace - def get_authorization_rule( - self, - resource_group_name: str, - namespace_name: str, - hybrid_connection_name: str, - authorization_rule_name: str, - **kwargs: Any - ) -> _models.AuthorizationRule: - """Hybrid connection authorization rule for a hybrid connection by name. + def get( + self, resource_group_name: str, namespace_name: str, hybrid_connection_name: str, **kwargs: Any + ) -> _models.HybridConnection: + """Returns the description for the specified hybrid connection. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str @@ -787,14 +744,11 @@ def get_authorization_rule( :type namespace_name: str :param hybrid_connection_name: The hybrid connection name. Required. :type hybrid_connection_name: str - :param authorization_rule_name: The authorization rule name. Required. - :type authorization_rule_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: AuthorizationRule or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.AuthorizationRule + :return: HybridConnection or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.HybridConnection :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -805,70 +759,65 @@ def get_authorization_rule( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - cls = kwargs.pop("cls", None) # type: ClsType[_models.AuthorizationRule] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.HybridConnection] = kwargs.pop("cls", None) - request = build_get_authorization_rule_request( + _request = build_get_request( resource_group_name=resource_group_name, namespace_name=namespace_name, hybrid_connection_name=hybrid_connection_name, - authorization_rule_name=authorization_rule_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get_authorization_rule.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("AuthorizationRule", pipeline_response) + deserialized = self._deserialize("HybridConnection", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get_authorization_rule.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/hybridConnections/{hybridConnectionName}/authorizationRules/{authorizationRuleName}"} # type: ignore + return deserialized # type: ignore @distributed_trace - def list_keys( - self, - resource_group_name: str, - namespace_name: str, - hybrid_connection_name: str, - authorization_rule_name: str, - **kwargs: Any - ) -> _models.AccessKeys: - """Primary and secondary connection strings to the hybrid connection. - + def list_authorization_rules( + self, resource_group_name: str, namespace_name: str, hybrid_connection_name: str, **kwargs: Any + ) -> ItemPaged["_models.AuthorizationRule"]: + """Authorization rules for a hybrid connection. + :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str :param namespace_name: The namespace name. Required. :type namespace_name: str :param hybrid_connection_name: The hybrid connection name. Required. :type hybrid_connection_name: str - :param authorization_rule_name: The authorization rule name. Required. - :type authorization_rule_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: AccessKeys or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.AccessKeys + :return: An iterator like instance of either AuthorizationRule or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.relay.models.AuthorizationRule] :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.AuthorizationRuleListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -876,61 +825,78 @@ def list_keys( } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessKeys] + def prepare_request(next_link=None): + if not next_link: - request = build_list_keys_request( - resource_group_name=resource_group_name, - namespace_name=namespace_name, - hybrid_connection_name=hybrid_connection_name, - authorization_rule_name=authorization_rule_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - template_url=self.list_keys.metadata["url"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request = build_list_authorization_rules_request( + resource_group_name=resource_group_name, + namespace_name=namespace_name, + hybrid_connection_name=hybrid_connection_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs - ) + 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.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request - response = pipeline_response.http_response + def extract_data(pipeline_response): + deserialized = self._deserialize("AuthorizationRuleListResult", 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) - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + def get_next(next_link=None): + _request = prepare_request(next_link) - deserialized = self._deserialize("AccessKeys", pipeline_response) + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response - if cls: - return cls(pipeline_response, deserialized, {}) + if response.status_code not in [200]: + map_error(status_code=response.status_code, 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 deserialized + return pipeline_response - list_keys.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/hybridConnections/{hybridConnectionName}/authorizationRules/{authorizationRuleName}/listKeys"} # type: ignore + return ItemPaged(get_next, extract_data) @overload - def regenerate_keys( + def create_or_update_authorization_rule( self, resource_group_name: str, namespace_name: str, hybrid_connection_name: str, authorization_rule_name: str, - parameters: _models.RegenerateAccessKeyParameters, + parameters: _models.AuthorizationRule, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.AccessKeys: - """Regenerates the primary or secondary connection strings to the hybrid connection. + ) -> _models.AuthorizationRule: + """Creates or updates an authorization rule for a hybrid connection. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str @@ -940,30 +906,29 @@ def regenerate_keys( :type hybrid_connection_name: str :param authorization_rule_name: The authorization rule name. Required. :type authorization_rule_name: str - :param parameters: Parameters supplied to regenerate authorization rule. Required. - :type parameters: ~azure.mgmt.relay.models.RegenerateAccessKeyParameters + :param parameters: The authorization rule parameters. Required. + :type parameters: ~azure.mgmt.relay.models.AuthorizationRule :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: AccessKeys or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.AccessKeys + :return: AuthorizationRule or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.AuthorizationRule :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def regenerate_keys( + def create_or_update_authorization_rule( self, resource_group_name: str, namespace_name: str, hybrid_connection_name: str, authorization_rule_name: str, - parameters: IO, + parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.AccessKeys: - """Regenerates the primary or secondary connection strings to the hybrid connection. + ) -> _models.AuthorizationRule: + """Creates or updates an authorization rule for a hybrid connection. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str @@ -973,28 +938,27 @@ def regenerate_keys( :type hybrid_connection_name: str :param authorization_rule_name: The authorization rule name. Required. :type authorization_rule_name: str - :param parameters: Parameters supplied to regenerate authorization rule. Required. - :type parameters: IO + :param parameters: The authorization rule parameters. Required. + :type parameters: IO[bytes] :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: AccessKeys or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.AccessKeys + :return: AuthorizationRule or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.AuthorizationRule :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace - def regenerate_keys( + def create_or_update_authorization_rule( self, resource_group_name: str, namespace_name: str, hybrid_connection_name: str, authorization_rule_name: str, - parameters: Union[_models.RegenerateAccessKeyParameters, IO], + parameters: Union[_models.AuthorizationRule, IO[bytes]], **kwargs: Any - ) -> _models.AccessKeys: - """Regenerates the primary or secondary connection strings to the hybrid connection. + ) -> _models.AuthorizationRule: + """Creates or updates an authorization rule for a hybrid connection. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str @@ -1004,18 +968,14 @@ def regenerate_keys( :type hybrid_connection_name: str :param authorization_rule_name: The authorization rule name. Required. :type authorization_rule_name: str - :param parameters: Parameters supplied to regenerate authorization rule. Is either a model type - or a IO type. Required. - :type parameters: ~azure.mgmt.relay.models.RegenerateAccessKeyParameters 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: AccessKeys or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.AccessKeys + :param parameters: The authorization rule parameters. Is either a AuthorizationRule type or a + IO[bytes] type. Required. + :type parameters: ~azure.mgmt.relay.models.AuthorizationRule or IO[bytes] + :return: AuthorizationRule or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.AuthorizationRule :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1026,21 +986,19 @@ def regenerate_keys( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessKeys] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.AuthorizationRule] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(parameters, (IO, bytes)): + if isinstance(parameters, (IOBase, bytes)): _content = parameters else: - _json = self._serialize.body(parameters, "RegenerateAccessKeyParameters") + _json = self._serialize.body(parameters, "AuthorizationRule") - request = build_regenerate_keys_request( + _request = build_create_or_update_authorization_rule_request( resource_group_name=resource_group_name, namespace_name=namespace_name, hybrid_connection_name=hybrid_connection_name, @@ -1050,57 +1008,57 @@ def regenerate_keys( content_type=content_type, json=_json, content=_content, - template_url=self.regenerate_keys.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("AccessKeys", pipeline_response) + deserialized = self._deserialize("AuthorizationRule", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - regenerate_keys.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/hybridConnections/{hybridConnectionName}/authorizationRules/{authorizationRuleName}/regenerateKeys"} # type: ignore + return deserialized # type: ignore @distributed_trace - def list_by_namespace( - self, resource_group_name: str, namespace_name: str, **kwargs: Any - ) -> Iterable["_models.HybridConnection"]: - """Lists the hybrid connection within the namespace. + def delete_authorization_rule( # pylint: disable=inconsistent-return-statements + self, + resource_group_name: str, + namespace_name: str, + hybrid_connection_name: str, + authorization_rule_name: str, + **kwargs: Any + ) -> None: + """Deletes a hybrid connection authorization rule. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str :param namespace_name: The namespace name. Required. :type namespace_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either HybridConnection or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.relay.models.HybridConnection] + :param hybrid_connection_name: The hybrid connection name. Required. + :type hybrid_connection_name: str + :param authorization_rule_name: The authorization rule name. Required. + :type authorization_rule_name: str + :return: None or the result of cls(response) + :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - cls = kwargs.pop("cls", None) # type: ClsType[_models.HybridConnectionListResult] - - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1108,135 +1066,52 @@ def list_by_namespace( } error_map.update(kwargs.pop("error_map", {}) or {}) - def prepare_request(next_link=None): - if not next_link: + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - request = build_list_by_namespace_request( - resource_group_name=resource_group_name, - namespace_name=namespace_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - template_url=self.list_by_namespace.metadata["url"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) - 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) # type: ignore - request.method = "GET" - return request + _request = build_delete_authorization_rule_request( + resource_group_name=resource_group_name, + namespace_name=namespace_name, + hybrid_connection_name=hybrid_connection_name, + authorization_rule_name=authorization_rule_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) - def extract_data(pipeline_response): - deserialized = self._deserialize("HybridConnectionListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) - return deserialized.next_link or None, iter(list_of_elem) + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) - def get_next(next_link=None): - request = prepare_request(next_link) + response = pipeline_response.http_response - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, 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_namespace.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/hybridConnections"} # type: ignore - - @overload - def create_or_update( - self, - resource_group_name: str, - namespace_name: str, - hybrid_connection_name: str, - parameters: _models.HybridConnection, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.HybridConnection: - """Creates or updates a service hybrid connection. This operation is idempotent. - - :param resource_group_name: Name of the Resource group within the Azure subscription. Required. - :type resource_group_name: str - :param namespace_name: The namespace name. Required. - :type namespace_name: str - :param hybrid_connection_name: The hybrid connection name. Required. - :type hybrid_connection_name: str - :param parameters: Parameters supplied to create a hybrid connection. Required. - :type parameters: ~azure.mgmt.relay.models.HybridConnection - :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: HybridConnection or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.HybridConnection - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_or_update( - self, - resource_group_name: str, - namespace_name: str, - hybrid_connection_name: str, - parameters: IO, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.HybridConnection: - """Creates or updates a service hybrid connection. This operation is idempotent. + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - :param resource_group_name: Name of the Resource group within the Azure subscription. Required. - :type resource_group_name: str - :param namespace_name: The namespace name. Required. - :type namespace_name: str - :param hybrid_connection_name: The hybrid connection name. Required. - :type hybrid_connection_name: str - :param parameters: Parameters supplied to create a hybrid connection. Required. - :type parameters: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: HybridConnection or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.HybridConnection - :raises ~azure.core.exceptions.HttpResponseError: - """ + if cls: + return cls(pipeline_response, None, {}) # type: ignore @distributed_trace - def create_or_update( + def get_authorization_rule( self, resource_group_name: str, namespace_name: str, hybrid_connection_name: str, - parameters: Union[_models.HybridConnection, IO], + authorization_rule_name: str, **kwargs: Any - ) -> _models.HybridConnection: - """Creates or updates a service hybrid connection. This operation is idempotent. + ) -> _models.AuthorizationRule: + """Hybrid connection authorization rule for a hybrid connection by name. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str @@ -1244,18 +1119,13 @@ def create_or_update( :type namespace_name: str :param hybrid_connection_name: The hybrid connection name. Required. :type hybrid_connection_name: str - :param parameters: Parameters supplied to create a hybrid connection. Is either a model type or - a IO type. Required. - :type parameters: ~azure.mgmt.relay.models.HybridConnection 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: HybridConnection or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.HybridConnection + :param authorization_rule_name: The authorization rule name. Required. + :type authorization_rule_name: str + :return: AuthorizationRule or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.AuthorizationRule :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1263,64 +1133,56 @@ def create_or_update( } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - cls = kwargs.pop("cls", None) # type: ClsType[_models.HybridConnection] - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IO, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "HybridConnection") + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.AuthorizationRule] = kwargs.pop("cls", None) - request = build_create_or_update_request( + _request = build_get_authorization_rule_request( resource_group_name=resource_group_name, namespace_name=namespace_name, hybrid_connection_name=hybrid_connection_name, + authorization_rule_name=authorization_rule_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.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("HybridConnection", pipeline_response) + deserialized = self._deserialize("AuthorizationRule", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/hybridConnections/{hybridConnectionName}"} # type: ignore + return deserialized # type: ignore @distributed_trace - def delete( # pylint: disable=inconsistent-return-statements - self, resource_group_name: str, namespace_name: str, hybrid_connection_name: str, **kwargs: Any - ) -> None: - """Deletes a hybrid connection. + def list_keys( + self, + resource_group_name: str, + namespace_name: str, + hybrid_connection_name: str, + authorization_rule_name: str, + **kwargs: Any + ) -> _models.AccessKeys: + """Primary and secondary connection strings to the hybrid connection. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str @@ -1328,12 +1190,13 @@ def delete( # pylint: disable=inconsistent-return-statements :type namespace_name: str :param hybrid_connection_name: The hybrid connection name. Required. :type hybrid_connection_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: None or the result of cls(response) - :rtype: None + :param authorization_rule_name: The authorization rule name. Required. + :type authorization_rule_name: str + :return: AccessKeys or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.AccessKeys :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1344,45 +1207,118 @@ def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - cls = kwargs.pop("cls", None) # type: ClsType[None] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.AccessKeys] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_list_keys_request( resource_group_name=resource_group_name, namespace_name=namespace_name, hybrid_connection_name=hybrid_connection_name, + authorization_rule_name=authorization_rule_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.delete.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response - if response.status_code not in [200, 204]: + if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + deserialized = self._deserialize("AccessKeys", pipeline_response.http_response) + if cls: - return cls(pipeline_response, None, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/hybridConnections/{hybridConnectionName}"} # type: ignore + return deserialized # type: ignore + + @overload + def regenerate_keys( + self, + resource_group_name: str, + namespace_name: str, + hybrid_connection_name: str, + authorization_rule_name: str, + parameters: _models.RegenerateAccessKeyParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.AccessKeys: + """Regenerates the primary or secondary connection strings to the hybrid connection. + + :param resource_group_name: Name of the Resource group within the Azure subscription. Required. + :type resource_group_name: str + :param namespace_name: The namespace name. Required. + :type namespace_name: str + :param hybrid_connection_name: The hybrid connection name. Required. + :type hybrid_connection_name: str + :param authorization_rule_name: The authorization rule name. Required. + :type authorization_rule_name: str + :param parameters: Parameters supplied to regenerate authorization rule. Required. + :type parameters: ~azure.mgmt.relay.models.RegenerateAccessKeyParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: AccessKeys or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.AccessKeys + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def regenerate_keys( + self, + resource_group_name: str, + namespace_name: str, + hybrid_connection_name: str, + authorization_rule_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.AccessKeys: + """Regenerates the primary or secondary connection strings to the hybrid connection. + + :param resource_group_name: Name of the Resource group within the Azure subscription. Required. + :type resource_group_name: str + :param namespace_name: The namespace name. Required. + :type namespace_name: str + :param hybrid_connection_name: The hybrid connection name. Required. + :type hybrid_connection_name: str + :param authorization_rule_name: The authorization rule name. Required. + :type authorization_rule_name: str + :param parameters: Parameters supplied to regenerate authorization rule. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: AccessKeys or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.AccessKeys + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace - def get( - self, resource_group_name: str, namespace_name: str, hybrid_connection_name: str, **kwargs: Any - ) -> _models.HybridConnection: - """Returns the description for the specified hybrid connection. + def regenerate_keys( + self, + resource_group_name: str, + namespace_name: str, + hybrid_connection_name: str, + authorization_rule_name: str, + parameters: Union[_models.RegenerateAccessKeyParameters, IO[bytes]], + **kwargs: Any + ) -> _models.AccessKeys: + """Regenerates the primary or secondary connection strings to the hybrid connection. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str @@ -1390,12 +1326,16 @@ def get( :type namespace_name: str :param hybrid_connection_name: The hybrid connection name. Required. :type hybrid_connection_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: HybridConnection or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.HybridConnection + :param authorization_rule_name: The authorization rule name. Required. + :type authorization_rule_name: str + :param parameters: Parameters supplied to regenerate authorization rule. Is either a + RegenerateAccessKeyParameters type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.relay.models.RegenerateAccessKeyParameters or IO[bytes] + :return: AccessKeys or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.AccessKeys :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1403,43 +1343,54 @@ def get( } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = kwargs.pop("headers", {}) or {} + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - cls = kwargs.pop("cls", None) # type: ClsType[_models.HybridConnection] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.AccessKeys] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "RegenerateAccessKeyParameters") - request = build_get_request( + _request = build_regenerate_keys_request( resource_group_name=resource_group_name, namespace_name=namespace_name, hybrid_connection_name=hybrid_connection_name, + authorization_rule_name=authorization_rule_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata["url"], + content_type=content_type, + json=_json, + content=_content, headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("HybridConnection", pipeline_response) + deserialized = self._deserialize("AccessKeys", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/hybridConnections/{hybridConnectionName}"} # type: ignore + return deserialized # type: ignore diff --git a/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/operations/_namespaces_operations.py b/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/operations/_namespaces_operations.py index 2155a69079f9..ffd97d622d98 100644 --- a/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/operations/_namespaces_operations.py +++ b/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/operations/_namespaces_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=line-too-long,useless-suppression,too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,141 +6,114 @@ # 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 +from collections.abc import MutableMapping +from io import IOBase +from typing import Any, Callable, IO, Iterator, Optional, TypeVar, Union, cast, overload import urllib.parse +from azure.core import PipelineClient from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, 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.rest import HttpRequest, HttpResponse 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 +from .._configuration import RelayAPIConfiguration +from .._utils.serialization import Deserializer, Serializer -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]] +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] +List = list _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_list_authorization_rules_request( - resource_group_name: str, namespace_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: +def build_check_name_availability_request(subscription_id: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-11-01")) # type: Literal["2021-11-01"] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/authorizationRules", - ) # pylint: disable=line-too-long + _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Relay/checkNameAvailability") path_format_arguments = { - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "namespaceName": _SERIALIZER.url("namespace_name", namespace_name, "str", max_length=50, min_length=6), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _url.format(**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="GET", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_create_or_update_authorization_rule_request( - resource_group_name: str, namespace_name: str, authorization_rule_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: +def build_list_request(subscription_id: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-11-01")) # type: Literal["2021-11-01"] - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-04-01")) accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/authorizationRules/{authorizationRuleName}", - ) # pylint: disable=line-too-long + _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Relay/namespaces") path_format_arguments = { - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "namespaceName": _SERIALIZER.url("namespace_name", namespace_name, "str", max_length=50, min_length=6), - "authorizationRuleName": _SERIALIZER.url( - "authorization_rule_name", authorization_rule_name, "str", min_length=1 - ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_delete_authorization_rule_request( - resource_group_name: str, namespace_name: str, authorization_rule_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: +def build_list_by_resource_group_request(resource_group_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-11-01")) # type: Literal["2021-11-01"] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-04-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/authorizationRules/{authorizationRuleName}", - ) # pylint: disable=line-too-long + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces", + ) path_format_arguments = { "resourceGroupName": _SERIALIZER.url( "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 ), - "namespaceName": _SERIALIZER.url("namespace_name", namespace_name, "str", max_length=50, min_length=6), - "authorizationRuleName": _SERIALIZER.url( - "authorization_rule_name", authorization_rule_name, "str", min_length=1 - ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -148,71 +121,68 @@ def build_delete_authorization_rule_request( # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_get_authorization_rule_request( - resource_group_name: str, namespace_name: str, authorization_rule_name: str, subscription_id: str, **kwargs: Any +def build_create_or_update_request( + resource_group_name: str, namespace_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-11-01")) # type: Literal["2021-11-01"] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/authorizationRules/{authorizationRuleName}", - ) # pylint: disable=line-too-long + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}", + ) path_format_arguments = { "resourceGroupName": _SERIALIZER.url( "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 ), "namespaceName": _SERIALIZER.url("namespace_name", namespace_name, "str", max_length=50, min_length=6), - "authorizationRuleName": _SERIALIZER.url( - "authorization_rule_name", authorization_rule_name, "str", min_length=1 - ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _url.format(**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="GET", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) -def build_list_keys_request( - resource_group_name: str, namespace_name: str, authorization_rule_name: str, subscription_id: str, **kwargs: Any +def build_delete_request( + resource_group_name: str, namespace_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-11-01")) # type: Literal["2021-11-01"] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-04-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/authorizationRules/{authorizationRuleName}/listKeys", - ) # pylint: disable=line-too-long + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}", + ) path_format_arguments = { "resourceGroupName": _SERIALIZER.url( "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 ), "namespaceName": _SERIALIZER.url("namespace_name", namespace_name, "str", max_length=50, min_length=6), - "authorizationRuleName": _SERIALIZER.url( - "authorization_rule_name", authorization_rule_name, "str", min_length=1 - ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -220,63 +190,66 @@ def build_list_keys_request( # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) -def build_regenerate_keys_request( - resource_group_name: str, namespace_name: str, authorization_rule_name: str, subscription_id: str, **kwargs: Any +def build_get_request( + resource_group_name: str, namespace_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-11-01")) # type: Literal["2021-11-01"] - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-04-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/authorizationRules/{authorizationRuleName}/regenerateKeys", - ) # pylint: disable=line-too-long + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}", + ) path_format_arguments = { "resourceGroupName": _SERIALIZER.url( "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 ), "namespaceName": _SERIALIZER.url("namespace_name", namespace_name, "str", max_length=50, min_length=6), - "authorizationRuleName": _SERIALIZER.url( - "authorization_rule_name", authorization_rule_name, "str", min_length=1 - ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _url.format(**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) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_check_name_availability_request(subscription_id: str, **kwargs: Any) -> HttpRequest: +def build_update_request( + resource_group_name: str, namespace_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-11-01")) # type: Literal["2021-11-01"] - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Relay/checkNameAvailability") + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}", + ) path_format_arguments = { + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "namespaceName": _SERIALIZER.url("namespace_name", namespace_name, "str", max_length=50, min_length=6), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -286,53 +259,32 @@ def build_check_name_availability_request(subscription_id: str, **kwargs: Any) - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_list_request(subscription_id: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-11-01")) # type: Literal["2021-11-01"] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Relay/namespaces") - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) -def build_list_by_resource_group_request(resource_group_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: +def build_list_authorization_rules_request( + resource_group_name: str, namespace_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-11-01")) # type: Literal["2021-11-01"] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-04-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces", - ) # pylint: disable=line-too-long + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/authorizationRules", + ) path_format_arguments = { "resourceGroupName": _SERIALIZER.url( "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 ), + "namespaceName": _SERIALIZER.url("namespace_name", namespace_name, "str", max_length=50, min_length=6), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -343,30 +295,33 @@ def build_list_by_resource_group_request(resource_group_name: str, subscription_ return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_create_or_update_request( - resource_group_name: str, namespace_name: str, subscription_id: str, **kwargs: Any +def build_create_or_update_authorization_rule_request( # pylint: disable=name-too-long + resource_group_name: str, namespace_name: str, authorization_rule_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-11-01")) # type: Literal["2021-11-01"] - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}", - ) # pylint: disable=line-too-long + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/authorizationRules/{authorizationRuleName}", + ) path_format_arguments = { "resourceGroupName": _SERIALIZER.url( "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 ), "namespaceName": _SERIALIZER.url("namespace_name", namespace_name, "str", max_length=50, min_length=6), + "authorizationRuleName": _SERIALIZER.url( + "authorization_rule_name", authorization_rule_name, "str", min_length=1 + ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -379,29 +334,32 @@ def build_create_or_update_request( return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) -def build_delete_request( - resource_group_name: str, namespace_name: str, subscription_id: str, **kwargs: Any +def build_delete_authorization_rule_request( + resource_group_name: str, namespace_name: str, authorization_rule_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-11-01")) # type: Literal["2021-11-01"] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-04-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}", - ) # pylint: disable=line-too-long + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/authorizationRules/{authorizationRuleName}", + ) path_format_arguments = { "resourceGroupName": _SERIALIZER.url( "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 ), "namespaceName": _SERIALIZER.url("namespace_name", namespace_name, "str", max_length=50, min_length=6), + "authorizationRuleName": _SERIALIZER.url( + "authorization_rule_name", authorization_rule_name, "str", min_length=1 + ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -412,29 +370,32 @@ def build_delete_request( return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) -def build_get_request( - resource_group_name: str, namespace_name: str, subscription_id: str, **kwargs: Any +def build_get_authorization_rule_request( + resource_group_name: str, namespace_name: str, authorization_rule_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-11-01")) # type: Literal["2021-11-01"] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-04-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}", - ) # pylint: disable=line-too-long + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/authorizationRules/{authorizationRuleName}", + ) path_format_arguments = { "resourceGroupName": _SERIALIZER.url( "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 ), "namespaceName": _SERIALIZER.url("namespace_name", namespace_name, "str", max_length=50, min_length=6), + "authorizationRuleName": _SERIALIZER.url( + "authorization_rule_name", authorization_rule_name, "str", min_length=1 + ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -445,66 +406,69 @@ def build_get_request( return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_update_request( - resource_group_name: str, namespace_name: str, subscription_id: str, **kwargs: Any +def build_list_keys_request( + resource_group_name: str, namespace_name: str, authorization_rule_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-11-01")) # type: Literal["2021-11-01"] - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-04-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}", - ) # pylint: disable=line-too-long + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/authorizationRules/{authorizationRuleName}/listKeys", + ) path_format_arguments = { "resourceGroupName": _SERIALIZER.url( "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 ), "namespaceName": _SERIALIZER.url("namespace_name", namespace_name, "str", max_length=50, min_length=6), + "authorizationRuleName": _SERIALIZER.url( + "authorization_rule_name", authorization_rule_name, "str", min_length=1 + ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_create_or_update_network_rule_set_request( - resource_group_name: str, namespace_name: str, subscription_id: str, **kwargs: Any +def build_regenerate_keys_request( + resource_group_name: str, namespace_name: str, authorization_rule_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-11-01")) # type: Literal["2021-11-01"] - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/networkRuleSets/default", - ) # pylint: disable=line-too-long + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/authorizationRules/{authorizationRuleName}/regenerateKeys", + ) path_format_arguments = { "resourceGroupName": _SERIALIZER.url( "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 ), "namespaceName": _SERIALIZER.url("namespace_name", namespace_name, "str", max_length=50, min_length=6), + "authorizationRuleName": _SERIALIZER.url( + "authorization_rule_name", authorization_rule_name, "str", min_length=1 + ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -514,40 +478,7 @@ def build_create_or_update_network_rule_set_request( _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_network_rule_set_request( - resource_group_name: str, namespace_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-11-01")) # type: Literal["2021-11-01"] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/networkRuleSets/default", - ) # pylint: disable=line-too-long - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "namespaceName": _SERIALIZER.url("namespace_name", namespace_name, "str", max_length=50, min_length=6), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) class NamespacesOperations: @@ -562,37 +493,59 @@ class NamespacesOperations: models = _models - def __init__(self, *args, **kwargs): + 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") + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: RelayAPIConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace - def list_authorization_rules( - self, resource_group_name: str, namespace_name: str, **kwargs: Any - ) -> Iterable["_models.AuthorizationRule"]: - """Authorization rules for a namespace. + @overload + def check_name_availability( + self, parameters: _models.CheckNameAvailability, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.CheckNameAvailabilityResult: + """Check the specified namespace name availability. - :param resource_group_name: Name of the Resource group within the Azure subscription. Required. - :type resource_group_name: str - :param namespace_name: The namespace name. Required. - :type namespace_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either AuthorizationRule or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.relay.models.AuthorizationRule] + :param parameters: Parameters to check availability of the specified namespace name. Required. + :type parameters: ~azure.mgmt.relay.models.CheckNameAvailability + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: CheckNameAvailabilityResult or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.CheckNameAvailabilityResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def check_name_availability( + self, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.CheckNameAvailabilityResult: + """Check the specified namespace name availability. + + :param parameters: Parameters to check availability of the specified namespace name. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: CheckNameAvailabilityResult or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.CheckNameAvailabilityResult :raises ~azure.core.exceptions.HttpResponseError: """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - cls = kwargs.pop("cls", None) # type: ClsType[_models.AuthorizationRuleListResult] + @distributed_trace + def check_name_availability( + self, parameters: Union[_models.CheckNameAvailability, IO[bytes]], **kwargs: Any + ) -> _models.CheckNameAvailabilityResult: + """Check the specified namespace name availability. - error_map = { + :param parameters: Parameters to check availability of the specified namespace name. Is either + a CheckNameAvailability type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.relay.models.CheckNameAvailability or IO[bytes] + :return: CheckNameAvailabilityResult or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.CheckNameAvailabilityResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -600,20 +553,86 @@ def list_authorization_rules( } error_map.update(kwargs.pop("error_map", {}) or {}) - def prepare_request(next_link=None): - if not next_link: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - request = build_list_authorization_rules_request( - resource_group_name=resource_group_name, - namespace_name=namespace_name, - subscription_id=self._config.subscription_id, + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.CheckNameAvailabilityResult] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "CheckNameAvailability") + + _request = build_check_name_availability_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("CheckNameAvailabilityResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list(self, **kwargs: Any) -> ItemPaged["_models.RelayNamespace"]: + """Lists all the available namespaces within the subscription regardless of the resourceGroups. + + :return: An iterator like instance of either RelayNamespace or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.relay.models.RelayNamespace] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.RelayNamespaceListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 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_authorization_rules.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -625,129 +644,130 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _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) # type: ignore - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): - deserialized = self._deserialize("AuthorizationRuleListResult", pipeline_response) + deserialized = self._deserialize("RelayNamespaceListResult", 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) + _request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + 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_authorization_rules.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/authorizationRules"} # type: ignore - - @overload - def create_or_update_authorization_rule( - self, - resource_group_name: str, - namespace_name: str, - authorization_rule_name: str, - parameters: _models.AuthorizationRule, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.AuthorizationRule: - """Creates or updates an authorization rule for a namespace. + @distributed_trace + def list_by_resource_group(self, resource_group_name: str, **kwargs: Any) -> ItemPaged["_models.RelayNamespace"]: + """Lists all the available namespaces within the ResourceGroup. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str - :param namespace_name: The namespace name. Required. - :type namespace_name: str - :param authorization_rule_name: The authorization rule name. Required. - :type authorization_rule_name: str - :param parameters: The authorization rule parameters. Required. - :type parameters: ~azure.mgmt.relay.models.AuthorizationRule - :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: AuthorizationRule or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.AuthorizationRule + :return: An iterator like instance of either RelayNamespace or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.relay.models.RelayNamespace] :raises ~azure.core.exceptions.HttpResponseError: """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - @overload - def create_or_update_authorization_rule( - self, - resource_group_name: str, - namespace_name: str, - authorization_rule_name: str, - parameters: IO, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.AuthorizationRule: - """Creates or updates an authorization rule for a namespace. + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.RelayNamespaceListResult] = kwargs.pop("cls", None) - :param resource_group_name: Name of the Resource group within the Azure subscription. Required. - :type resource_group_name: str - :param namespace_name: The namespace name. Required. - :type namespace_name: str - :param authorization_rule_name: The authorization rule name. Required. - :type authorization_rule_name: str - :param parameters: The authorization rule parameters. Required. - :type parameters: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: AuthorizationRule or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.AuthorizationRule - :raises ~azure.core.exceptions.HttpResponseError: - """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) - @distributed_trace - def create_or_update_authorization_rule( + 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, + headers=_headers, + params=_params, + ) + _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.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("RelayNamespaceListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + 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) + + def _create_or_update_initial( self, resource_group_name: str, namespace_name: str, - authorization_rule_name: str, - parameters: Union[_models.AuthorizationRule, IO], + parameters: Union[_models.RelayNamespace, IO[bytes]], **kwargs: Any - ) -> _models.AuthorizationRule: - """Creates or updates an authorization rule for a namespace. - - :param resource_group_name: Name of the Resource group within the Azure subscription. Required. - :type resource_group_name: str - :param namespace_name: The namespace name. Required. - :type namespace_name: str - :param authorization_rule_name: The authorization rule name. Required. - :type authorization_rule_name: str - :param parameters: The authorization rule parameters. Is either a model type or a IO type. - Required. - :type parameters: ~azure.mgmt.relay.models.AuthorizationRule 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: AuthorizationRule or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.AuthorizationRule - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map = { + ) -> Iterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -758,74 +778,183 @@ def create_or_update_authorization_rule( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - cls = kwargs.pop("cls", None) # type: ClsType[_models.AuthorizationRule] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(parameters, (IO, bytes)): + if isinstance(parameters, (IOBase, bytes)): _content = parameters else: - _json = self._serialize.body(parameters, "AuthorizationRule") + _json = self._serialize.body(parameters, "RelayNamespace") - request = build_create_or_update_authorization_rule_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, namespace_name=namespace_name, - authorization_rule_name=authorization_rule_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_authorization_rule.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response - if response.status_code not in [200]: + if response.status_code not in [200, 201]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("AuthorizationRule", pipeline_response) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + namespace_name: str, + parameters: _models.RelayNamespace, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.RelayNamespace]: + """Create Azure Relay namespace. - return deserialized + :param resource_group_name: Name of the Resource group within the Azure subscription. Required. + :type resource_group_name: str + :param namespace_name: The namespace name. Required. + :type namespace_name: str + :param parameters: Parameters supplied to create a namespace resource. Required. + :type parameters: ~azure.mgmt.relay.models.RelayNamespace + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either RelayNamespace or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.relay.models.RelayNamespace] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + namespace_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.RelayNamespace]: + """Create Azure Relay namespace. - create_or_update_authorization_rule.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/authorizationRules/{authorizationRuleName}"} # type: ignore + :param resource_group_name: Name of the Resource group within the Azure subscription. Required. + :type resource_group_name: str + :param namespace_name: The namespace name. Required. + :type namespace_name: str + :param parameters: Parameters supplied to create a namespace resource. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns either RelayNamespace or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.relay.models.RelayNamespace] + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace - def delete_authorization_rule( # pylint: disable=inconsistent-return-statements - self, resource_group_name: str, namespace_name: str, authorization_rule_name: str, **kwargs: Any - ) -> None: - """Deletes a namespace authorization rule. + def begin_create_or_update( + self, + resource_group_name: str, + namespace_name: str, + parameters: Union[_models.RelayNamespace, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.RelayNamespace]: + """Create Azure Relay namespace. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str :param namespace_name: The namespace name. Required. :type namespace_name: str - :param authorization_rule_name: The authorization rule name. Required. - :type authorization_rule_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: None or the result of cls(response) - :rtype: None + :param parameters: Parameters supplied to create a namespace resource. Is either a + RelayNamespace type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.relay.models.RelayNamespace or IO[bytes] + :return: An instance of LROPoller that returns either RelayNamespace or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.relay.models.RelayNamespace] :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.RelayNamespace] = 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, + namespace_name=namespace_name, + parameters=parameters, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + deserialized = self._deserialize("RelayNamespace", pipeline_response.http_response) + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + 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[_models.RelayNamespace].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.RelayNamespace]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + def _delete_initial(self, resource_group_name: str, namespace_name: str, **kwargs: Any) -> Iterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -836,124 +965,112 @@ def delete_authorization_rule( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - cls = kwargs.pop("cls", None) # type: ClsType[None] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - request = build_delete_authorization_rule_request( + _request = build_delete_request( resource_group_name=resource_group_name, namespace_name=namespace_name, - authorization_rule_name=authorization_rule_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.delete_authorization_rule.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response - if response.status_code not in [200, 204]: + if response.status_code not in [200, 202, 204]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) + if cls: - return cls(pipeline_response, None, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - delete_authorization_rule.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/authorizationRules/{authorizationRuleName}"} # type: ignore + return deserialized # type: ignore @distributed_trace - def get_authorization_rule( - self, resource_group_name: str, namespace_name: str, authorization_rule_name: str, **kwargs: Any - ) -> _models.AuthorizationRule: - """Authorization rule for a namespace by name. + def begin_delete(self, resource_group_name: str, namespace_name: str, **kwargs: Any) -> LROPoller[None]: + """Deletes an existing namespace. This operation also removes all associated resources under the + namespace. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str :param namespace_name: The namespace name. Required. :type namespace_name: str - :param authorization_rule_name: The authorization rule name. Required. - :type authorization_rule_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: AuthorizationRule or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.AuthorizationRule + :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: """ - error_map = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - cls = kwargs.pop("cls", None) # type: ClsType[_models.AuthorizationRule] - - request = build_get_authorization_rule_request( - resource_group_name=resource_group_name, - namespace_name=namespace_name, - authorization_rule_name=authorization_rule_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - template_url=self.get_authorization_rule.metadata["url"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore - - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("AuthorizationRule", pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._delete_initial( + resource_group_name=resource_group_name, + namespace_name=namespace_name, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) - return deserialized + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore - get_authorization_rule.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/authorizationRules/{authorizationRuleName}"} # type: ignore + 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[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore @distributed_trace - def list_keys( - self, resource_group_name: str, namespace_name: str, authorization_rule_name: str, **kwargs: Any - ) -> _models.AccessKeys: - """Primary and secondary connection strings to the namespace. + def get(self, resource_group_name: str, namespace_name: str, **kwargs: Any) -> _models.RelayNamespace: + """Returns the description for the specified namespace. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str :param namespace_name: The namespace name. Required. :type namespace_name: str - :param authorization_rule_name: The authorization rule name. Required. - :type authorization_rule_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: AccessKeys or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.AccessKeys + :return: RelayNamespace or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.RelayNamespace :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -964,245 +1081,118 @@ def list_keys( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessKeys] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.RelayNamespace] = kwargs.pop("cls", None) - request = build_list_keys_request( + _request = build_get_request( resource_group_name=resource_group_name, namespace_name=namespace_name, - authorization_rule_name=authorization_rule_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_keys.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("AccessKeys", pipeline_response) + deserialized = self._deserialize("RelayNamespace", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - list_keys.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/authorizationRules/{authorizationRuleName}/listKeys"} # type: ignore + return deserialized # type: ignore @overload - def regenerate_keys( + def update( self, resource_group_name: str, namespace_name: str, - authorization_rule_name: str, - parameters: _models.RegenerateAccessKeyParameters, + parameters: _models.RelayUpdateParameters, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.AccessKeys: - """Regenerates the primary or secondary connection strings to the namespace. + ) -> _models.RelayNamespace: + """Creates or updates a namespace. Once created, this namespace's resource manifest is immutable. + This operation is idempotent. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str :param namespace_name: The namespace name. Required. :type namespace_name: str - :param authorization_rule_name: The authorization rule name. Required. - :type authorization_rule_name: str - :param parameters: Parameters supplied to regenerate authorization rule. Required. - :type parameters: ~azure.mgmt.relay.models.RegenerateAccessKeyParameters + :param parameters: Parameters for updating a namespace resource. Required. + :type parameters: ~azure.mgmt.relay.models.RelayUpdateParameters :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: AccessKeys or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.AccessKeys + :return: RelayNamespace or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.RelayNamespace :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def regenerate_keys( + def update( self, resource_group_name: str, namespace_name: str, - authorization_rule_name: str, - parameters: IO, + parameters: IO[bytes], *, content_type: str = "application/json", - **kwargs: Any - ) -> _models.AccessKeys: - """Regenerates the primary or secondary connection strings to the namespace. - - :param resource_group_name: Name of the Resource group within the Azure subscription. Required. - :type resource_group_name: str - :param namespace_name: The namespace name. Required. - :type namespace_name: str - :param authorization_rule_name: The authorization rule name. Required. - :type authorization_rule_name: str - :param parameters: Parameters supplied to regenerate authorization rule. Required. - :type parameters: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: AccessKeys or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.AccessKeys - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def regenerate_keys( - self, - resource_group_name: str, - namespace_name: str, - authorization_rule_name: str, - parameters: Union[_models.RegenerateAccessKeyParameters, IO], - **kwargs: Any - ) -> _models.AccessKeys: - """Regenerates the primary or secondary connection strings to the namespace. - - :param resource_group_name: Name of the Resource group within the Azure subscription. Required. - :type resource_group_name: str - :param namespace_name: The namespace name. Required. - :type namespace_name: str - :param authorization_rule_name: The authorization rule name. Required. - :type authorization_rule_name: str - :param parameters: Parameters supplied to regenerate authorization rule. Is either a model type - or a IO type. Required. - :type parameters: ~azure.mgmt.relay.models.RegenerateAccessKeyParameters 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: AccessKeys or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.AccessKeys - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessKeys] - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IO, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "RegenerateAccessKeyParameters") - - request = build_regenerate_keys_request( - resource_group_name=resource_group_name, - namespace_name=namespace_name, - authorization_rule_name=authorization_rule_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - template_url=self.regenerate_keys.metadata["url"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore - - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("AccessKeys", pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - - regenerate_keys.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/authorizationRules/{authorizationRuleName}/regenerateKeys"} # type: ignore - - @overload - def check_name_availability( - self, parameters: _models.CheckNameAvailability, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.CheckNameAvailabilityResult: - """Check the specified namespace name availability. - - :param parameters: Parameters to check availability of the specified namespace name. Required. - :type parameters: ~azure.mgmt.relay.models.CheckNameAvailability - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: CheckNameAvailabilityResult or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.CheckNameAvailabilityResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def check_name_availability( - self, parameters: IO, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.CheckNameAvailabilityResult: - """Check the specified namespace name availability. + **kwargs: Any + ) -> _models.RelayNamespace: + """Creates or updates a namespace. Once created, this namespace's resource manifest is immutable. + This operation is idempotent. - :param parameters: Parameters to check availability of the specified namespace name. Required. - :type parameters: IO + :param resource_group_name: Name of the Resource group within the Azure subscription. Required. + :type resource_group_name: str + :param namespace_name: The namespace name. Required. + :type namespace_name: str + :param parameters: Parameters for updating a namespace resource. Required. + :type parameters: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: CheckNameAvailabilityResult or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.CheckNameAvailabilityResult + :return: RelayNamespace or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.RelayNamespace :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace - def check_name_availability( - self, parameters: Union[_models.CheckNameAvailability, IO], **kwargs: Any - ) -> _models.CheckNameAvailabilityResult: - """Check the specified namespace name availability. + def update( + self, + resource_group_name: str, + namespace_name: str, + parameters: Union[_models.RelayUpdateParameters, IO[bytes]], + **kwargs: Any + ) -> _models.RelayNamespace: + """Creates or updates a namespace. Once created, this namespace's resource manifest is immutable. + This operation is idempotent. - :param parameters: Parameters to check availability of the specified namespace name. Is either - a model type or a IO type. Required. - :type parameters: ~azure.mgmt.relay.models.CheckNameAvailability or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: CheckNameAvailabilityResult or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.CheckNameAvailabilityResult + :param resource_group_name: Name of the Resource group within the Azure subscription. Required. + :type resource_group_name: str + :param namespace_name: The namespace name. Required. + :type namespace_name: str + :param parameters: Parameters for updating a namespace resource. Is either a + RelayUpdateParameters type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.relay.models.RelayUpdateParameters or IO[bytes] + :return: RelayNamespace or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.RelayNamespace :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1213,155 +1203,74 @@ def check_name_availability( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - cls = kwargs.pop("cls", None) # type: ClsType[_models.CheckNameAvailabilityResult] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.RelayNamespace] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(parameters, (IO, bytes)): + if isinstance(parameters, (IOBase, bytes)): _content = parameters else: - _json = self._serialize.body(parameters, "CheckNameAvailability") + _json = self._serialize.body(parameters, "RelayUpdateParameters") - request = build_check_name_availability_request( + _request = build_update_request( + resource_group_name=resource_group_name, + namespace_name=namespace_name, subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, content=_content, - template_url=self.check_name_availability.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response - if response.status_code not in [200]: + 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) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("CheckNameAvailabilityResult", pipeline_response) + deserialized = self._deserialize("RelayNamespace", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - - check_name_availability.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Relay/checkNameAvailability"} # type: ignore - - @distributed_trace - def list(self, **kwargs: Any) -> Iterable["_models.RelayNamespace"]: - """Lists all the available namespaces within the subscription regardless of the resourceGroups. - - :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RelayNamespace or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.relay.models.RelayNamespace] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - cls = kwargs.pop("cls", None) # type: ClsType[_models.RelayNamespaceListResult] - - 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) # type: ignore - - 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) # type: ignore - request.method = "GET" - return request - - def extract_data(pipeline_response): - deserialized = self._deserialize("RelayNamespaceListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) - return deserialized.next_link or None, iter(list_of_elem) - - def get_next(next_link=None): - request = prepare_request(next_link) - - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) + return cls(pipeline_response, deserialized, {}) # type: ignore - list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Relay/namespaces"} # type: ignore + return deserialized # type: ignore @distributed_trace - def list_by_resource_group(self, resource_group_name: str, **kwargs: Any) -> Iterable["_models.RelayNamespace"]: - """Lists all the available namespaces within the ResourceGroup. + def list_authorization_rules( + self, resource_group_name: str, namespace_name: str, **kwargs: Any + ) -> ItemPaged["_models.AuthorizationRule"]: + """Authorization rules for a namespace. :param resource_group_name: Name of the Resource group within the Azure subscription. 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 RelayNamespace or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.relay.models.RelayNamespace] + :param namespace_name: The namespace name. Required. + :type namespace_name: str + :return: An iterator like instance of either AuthorizationRule or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.relay.models.AuthorizationRule] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - cls = kwargs.pop("cls", None) # type: ClsType[_models.RelayNamespaceListResult] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.AuthorizationRuleListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1372,16 +1281,15 @@ def list_by_resource_group(self, resource_group_name: str, **kwargs: Any) -> Ite def prepare_request(next_link=None): if not next_link: - request = build_list_by_resource_group_request( + _request = build_list_authorization_rules_request( resource_group_name=resource_group_name, + namespace_name=namespace_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) # type: ignore + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -1393,266 +1301,124 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _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) # type: ignore - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): - deserialized = self._deserialize("RelayNamespaceListResult", pipeline_response) + deserialized = self._deserialize("AuthorizationRuleListResult", 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) + _request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + 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.Relay/namespaces"} # type: ignore - - def _create_or_update_initial( - self, - resource_group_name: str, - namespace_name: str, - parameters: Union[_models.RelayNamespace, IO], - **kwargs: Any - ) -> _models.RelayNamespace: - error_map = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - cls = kwargs.pop("cls", None) # type: ClsType[_models.RelayNamespace] - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IO, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "RelayNamespace") - - request = build_create_or_update_request( - resource_group_name=resource_group_name, - namespace_name=namespace_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) # type: ignore - - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 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("RelayNamespace", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("RelayNamespace", pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - - _create_or_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}"} # type: ignore - @overload - def begin_create_or_update( + def create_or_update_authorization_rule( self, resource_group_name: str, namespace_name: str, - parameters: _models.RelayNamespace, + authorization_rule_name: str, + parameters: _models.AuthorizationRule, *, content_type: str = "application/json", **kwargs: Any - ) -> LROPoller[_models.RelayNamespace]: - """Create Azure Relay namespace. + ) -> _models.AuthorizationRule: + """Creates or updates an authorization rule for a namespace. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str :param namespace_name: The namespace name. Required. :type namespace_name: str - :param parameters: Parameters supplied to create a namespace resource. Required. - :type parameters: ~azure.mgmt.relay.models.RelayNamespace + :param authorization_rule_name: The authorization rule name. Required. + :type authorization_rule_name: str + :param parameters: The authorization rule parameters. Required. + :type parameters: ~azure.mgmt.relay.models.AuthorizationRule :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 RelayNamespace or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.relay.models.RelayNamespace] + :return: AuthorizationRule or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.AuthorizationRule :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def begin_create_or_update( + def create_or_update_authorization_rule( self, resource_group_name: str, namespace_name: str, - parameters: IO, + authorization_rule_name: str, + parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> LROPoller[_models.RelayNamespace]: - """Create Azure Relay namespace. + ) -> _models.AuthorizationRule: + """Creates or updates an authorization rule for a namespace. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str :param namespace_name: The namespace name. Required. :type namespace_name: str - :param parameters: Parameters supplied to create a namespace resource. Required. - :type parameters: IO + :param authorization_rule_name: The authorization rule name. Required. + :type authorization_rule_name: str + :param parameters: The authorization rule parameters. Required. + :type parameters: IO[bytes] :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 RelayNamespace or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.relay.models.RelayNamespace] + :return: AuthorizationRule or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.AuthorizationRule :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace - def begin_create_or_update( + def create_or_update_authorization_rule( self, resource_group_name: str, namespace_name: str, - parameters: Union[_models.RelayNamespace, IO], + authorization_rule_name: str, + parameters: Union[_models.AuthorizationRule, IO[bytes]], **kwargs: Any - ) -> LROPoller[_models.RelayNamespace]: - """Create Azure Relay namespace. + ) -> _models.AuthorizationRule: + """Creates or updates an authorization rule for a namespace. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str :param namespace_name: The namespace name. Required. :type namespace_name: str - :param parameters: Parameters supplied to create a namespace resource. Is either a model type - or a IO type. Required. - :type parameters: ~azure.mgmt.relay.models.RelayNamespace 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 RelayNamespace or the result of - cls(response) - :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.relay.models.RelayNamespace] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - cls = kwargs.pop("cls", None) # type: ClsType[_models.RelayNamespace] - polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] - if cont_token is None: - raw_result = self._create_or_update_initial( # type: ignore - resource_group_name=resource_group_name, - namespace_name=namespace_name, - parameters=parameters, - api_version=api_version, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - deserialized = self._deserialize("RelayNamespace", pipeline_response) - if cls: - return cls(pipeline_response, deserialized, {}) - return deserialized - - if polling is True: - polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller.from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - - begin_create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}"} # type: ignore - - def _delete_initial( # pylint: disable=inconsistent-return-statements - self, resource_group_name: str, namespace_name: str, **kwargs: Any - ) -> None: - error_map = { + :param authorization_rule_name: The authorization rule name. Required. + :type authorization_rule_name: str + :param parameters: The authorization rule parameters. Is either a AuthorizationRule type or a + IO[bytes] type. Required. + :type parameters: ~azure.mgmt.relay.models.AuthorizationRule or IO[bytes] + :return: AuthorizationRule or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.AuthorizationRule + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1660,120 +1426,133 @@ def _delete_initial( # pylint: disable=inconsistent-return-statements } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = kwargs.pop("headers", {}) or {} + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - cls = kwargs.pop("cls", None) # type: ClsType[None] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.AuthorizationRule] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "AuthorizationRule") - request = build_delete_request( + _request = build_create_or_update_authorization_rule_request( resource_group_name=resource_group_name, namespace_name=namespace_name, + authorization_rule_name=authorization_rule_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._delete_initial.metadata["url"], + content_type=content_type, + json=_json, + content=_content, headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response - if response.status_code not in [200, 202, 204]: + if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + deserialized = self._deserialize("AuthorizationRule", pipeline_response.http_response) + if cls: - return cls(pipeline_response, None, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}"} # type: ignore + return deserialized # type: ignore @distributed_trace - def begin_delete(self, resource_group_name: str, namespace_name: str, **kwargs: Any) -> LROPoller[None]: - """Deletes an existing namespace. This operation also removes all associated resources under the - namespace. + def delete_authorization_rule( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, namespace_name: str, authorization_rule_name: str, **kwargs: Any + ) -> None: + """Deletes a namespace authorization rule. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str :param namespace_name: The namespace name. Required. :type namespace_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] + :param authorization_rule_name: The authorization rule name. Required. + :type authorization_rule_name: str + :return: None or the result of cls(response) + :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - cls = kwargs.pop("cls", None) # type: ClsType[None] - polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] - if cont_token is None: - raw_result = self._delete_initial( # type: ignore - resource_group_name=resource_group_name, - namespace_name=namespace_name, - api_version=api_version, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - kwargs.pop("error_map", None) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) - def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements - if cls: - return cls(pipeline_response, None, {}) + _request = build_delete_authorization_rule_request( + resource_group_name=resource_group_name, + namespace_name=namespace_name, + authorization_rule_name=authorization_rule_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) - if polling is True: - polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller.from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}"} # type: ignore + if cls: + return cls(pipeline_response, None, {}) # type: ignore @distributed_trace - def get(self, resource_group_name: str, namespace_name: str, **kwargs: Any) -> _models.RelayNamespace: - """Returns the description for the specified namespace. + def get_authorization_rule( + self, resource_group_name: str, namespace_name: str, authorization_rule_name: str, **kwargs: Any + ) -> _models.AuthorizationRule: + """Authorization rule for a namespace by name. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str :param namespace_name: The namespace name. Required. :type namespace_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: RelayNamespace or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.RelayNamespace + :param authorization_rule_name: The authorization rule name. Required. + :type authorization_rule_name: str + :return: AuthorizationRule or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.AuthorizationRule :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1784,126 +1563,59 @@ def get(self, resource_group_name: str, namespace_name: str, **kwargs: Any) -> _ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - cls = kwargs.pop("cls", None) # type: ClsType[_models.RelayNamespace] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.AuthorizationRule] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_authorization_rule_request( resource_group_name=resource_group_name, namespace_name=namespace_name, + authorization_rule_name=authorization_rule_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("RelayNamespace", pipeline_response) + deserialized = self._deserialize("AuthorizationRule", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - - get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}"} # type: ignore - - @overload - def update( - self, - resource_group_name: str, - namespace_name: str, - parameters: _models.RelayUpdateParameters, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.RelayNamespace: - """Creates or updates a namespace. Once created, this namespace's resource manifest is immutable. - This operation is idempotent. - - :param resource_group_name: Name of the Resource group within the Azure subscription. Required. - :type resource_group_name: str - :param namespace_name: The namespace name. Required. - :type namespace_name: str - :param parameters: Parameters for updating a namespace resource. Required. - :type parameters: ~azure.mgmt.relay.models.RelayUpdateParameters - :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: RelayNamespace or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.RelayNamespace - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def update( - self, - resource_group_name: str, - namespace_name: str, - parameters: IO, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.RelayNamespace: - """Creates or updates a namespace. Once created, this namespace's resource manifest is immutable. - This operation is idempotent. + return cls(pipeline_response, deserialized, {}) # type: ignore - :param resource_group_name: Name of the Resource group within the Azure subscription. Required. - :type resource_group_name: str - :param namespace_name: The namespace name. Required. - :type namespace_name: str - :param parameters: Parameters for updating a namespace resource. Required. - :type parameters: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: RelayNamespace or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.RelayNamespace - :raises ~azure.core.exceptions.HttpResponseError: - """ + return deserialized # type: ignore @distributed_trace - def update( - self, - resource_group_name: str, - namespace_name: str, - parameters: Union[_models.RelayUpdateParameters, IO], - **kwargs: Any - ) -> _models.RelayNamespace: - """Creates or updates a namespace. Once created, this namespace's resource manifest is immutable. - This operation is idempotent. + def list_keys( + self, resource_group_name: str, namespace_name: str, authorization_rule_name: str, **kwargs: Any + ) -> _models.AccessKeys: + """Primary and secondary connection strings to the namespace. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str :param namespace_name: The namespace name. Required. :type namespace_name: str - :param parameters: Parameters for updating a namespace resource. Is either a model type or a IO - type. Required. - :type parameters: ~azure.mgmt.relay.models.RelayUpdateParameters 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: RelayNamespace or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.RelayNamespace + :param authorization_rule_name: The authorization rule name. Required. + :type authorization_rule_name: str + :return: AccessKeys or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.AccessKeys :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1911,141 +1623,128 @@ def update( } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - cls = kwargs.pop("cls", None) # type: ClsType[_models.RelayNamespace] - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IO, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "RelayUpdateParameters") + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.AccessKeys] = kwargs.pop("cls", None) - request = build_update_request( + _request = build_list_keys_request( resource_group_name=resource_group_name, namespace_name=namespace_name, + authorization_rule_name=authorization_rule_name, subscription_id=self._config.subscription_id, api_version=api_version, - content_type=content_type, - json=_json, - content=_content, - template_url=self.update.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response - if response.status_code not in [200, 201]: + if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + 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("RelayNamespace", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("RelayNamespace", pipeline_response) + deserialized = self._deserialize("AccessKeys", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}"} # type: ignore + return deserialized # type: ignore @overload - def create_or_update_network_rule_set( + def regenerate_keys( self, resource_group_name: str, namespace_name: str, - parameters: _models.NetworkRuleSet, + authorization_rule_name: str, + parameters: _models.RegenerateAccessKeyParameters, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.NetworkRuleSet: - """Create or update NetworkRuleSet for a Namespace. + ) -> _models.AccessKeys: + """Regenerates the primary or secondary connection strings to the namespace. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str :param namespace_name: The namespace name. Required. :type namespace_name: str - :param parameters: The Namespace IpFilterRule. Required. - :type parameters: ~azure.mgmt.relay.models.NetworkRuleSet + :param authorization_rule_name: The authorization rule name. Required. + :type authorization_rule_name: str + :param parameters: Parameters supplied to regenerate authorization rule. Required. + :type parameters: ~azure.mgmt.relay.models.RegenerateAccessKeyParameters :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: NetworkRuleSet or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.NetworkRuleSet + :return: AccessKeys or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.AccessKeys :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def create_or_update_network_rule_set( + def regenerate_keys( self, resource_group_name: str, namespace_name: str, - parameters: IO, + authorization_rule_name: str, + parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.NetworkRuleSet: - """Create or update NetworkRuleSet for a Namespace. + ) -> _models.AccessKeys: + """Regenerates the primary or secondary connection strings to the namespace. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str :param namespace_name: The namespace name. Required. :type namespace_name: str - :param parameters: The Namespace IpFilterRule. Required. - :type parameters: IO + :param authorization_rule_name: The authorization rule name. Required. + :type authorization_rule_name: str + :param parameters: Parameters supplied to regenerate authorization rule. Required. + :type parameters: IO[bytes] :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: NetworkRuleSet or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.NetworkRuleSet + :return: AccessKeys or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.AccessKeys :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace - def create_or_update_network_rule_set( + def regenerate_keys( self, resource_group_name: str, namespace_name: str, - parameters: Union[_models.NetworkRuleSet, IO], + authorization_rule_name: str, + parameters: Union[_models.RegenerateAccessKeyParameters, IO[bytes]], **kwargs: Any - ) -> _models.NetworkRuleSet: - """Create or update NetworkRuleSet for a Namespace. + ) -> _models.AccessKeys: + """Regenerates the primary or secondary connection strings to the namespace. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str :param namespace_name: The namespace name. Required. :type namespace_name: str - :param parameters: The Namespace IpFilterRule. Is either a model type or a IO type. Required. - :type parameters: ~azure.mgmt.relay.models.NetworkRuleSet 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: NetworkRuleSet or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.NetworkRuleSet + :param authorization_rule_name: The authorization rule name. Required. + :type authorization_rule_name: str + :param parameters: Parameters supplied to regenerate authorization rule. Is either a + RegenerateAccessKeyParameters type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.relay.models.RegenerateAccessKeyParameters or IO[bytes] + :return: AccessKeys or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.AccessKeys :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -2056,114 +1755,50 @@ def create_or_update_network_rule_set( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - cls = kwargs.pop("cls", None) # type: ClsType[_models.NetworkRuleSet] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.AccessKeys] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(parameters, (IO, bytes)): + if isinstance(parameters, (IOBase, bytes)): _content = parameters else: - _json = self._serialize.body(parameters, "NetworkRuleSet") + _json = self._serialize.body(parameters, "RegenerateAccessKeyParameters") - request = build_create_or_update_network_rule_set_request( + _request = build_regenerate_keys_request( resource_group_name=resource_group_name, namespace_name=namespace_name, + authorization_rule_name=authorization_rule_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_network_rule_set.metadata["url"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore - - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("NetworkRuleSet", pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - - create_or_update_network_rule_set.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/networkRuleSets/default"} # type: ignore - - @distributed_trace - def get_network_rule_set( - self, resource_group_name: str, namespace_name: str, **kwargs: Any - ) -> _models.NetworkRuleSet: - """Gets NetworkRuleSet for a Namespace. - - :param resource_group_name: Name of the Resource group within the Azure subscription. Required. - :type resource_group_name: str - :param namespace_name: The namespace name. Required. - :type namespace_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: NetworkRuleSet or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.NetworkRuleSet - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - cls = kwargs.pop("cls", None) # type: ClsType[_models.NetworkRuleSet] - - request = build_get_network_rule_set_request( - resource_group_name=resource_group_name, - namespace_name=namespace_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - template_url=self.get_network_rule_set.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("NetworkRuleSet", pipeline_response) + deserialized = self._deserialize("AccessKeys", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get_network_rule_set.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/networkRuleSets/default"} # type: ignore + return deserialized # type: ignore diff --git a/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/operations/_operations.py b/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/operations/_operations.py index 5266f9afb99f..6fe7642b9bf1 100644 --- a/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/operations/_operations.py +++ b/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/operations/_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,10 +5,11 @@ # 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 collections.abc import MutableMapping +from typing import Any, Callable, Optional, TypeVar import urllib.parse +from azure.core import PipelineClient from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, @@ -20,22 +20,18 @@ ) 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.rest import HttpRequest, HttpResponse 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 +from .._configuration import RelayAPIConfiguration +from .._utils.serialization import Deserializer, Serializer -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]] +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] +List = list _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False @@ -45,7 +41,7 @@ def build_list_request(**kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-11-01")) # type: Literal["2021-11-01"] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-04-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -72,18 +68,17 @@ class Operations: models = _models - def __init__(self, *args, **kwargs): + 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") + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: RelayAPIConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace - def list(self, **kwargs: Any) -> Iterable["_models.Operation"]: + def list(self, **kwargs: Any) -> ItemPaged["_models.Operation"]: """Lists all available Relay 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.relay.models.Operation] :raises ~azure.core.exceptions.HttpResponseError: @@ -91,12 +86,10 @@ def list(self, **kwargs: Any) -> Iterable["_models.Operation"]: _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - cls = kwargs.pop("cls", None) # type: ClsType[_models.OperationListResult] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -107,14 +100,12 @@ def list(self, **kwargs: Any) -> Iterable["_models.Operation"]: def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -126,36 +117,37 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _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) # type: ignore - request.method = "GET" - return 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) + 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) + _request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + 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.Relay/operations"} # type: ignore diff --git a/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/operations/_private_endpoint_connections_operations.py b/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/operations/_private_endpoint_connections_operations.py deleted file mode 100644 index c82575702e03..000000000000 --- a/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/operations/_private_endpoint_connections_operations.py +++ /dev/null @@ -1,651 +0,0 @@ -# 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, namespace_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-11-01")) # type: Literal["2021-11-01"] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/privateEndpointConnections", - ) # pylint: disable=line-too-long - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "namespaceName": _SERIALIZER.url("namespace_name", namespace_name, "str", max_length=50, min_length=6), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_create_or_update_request( - resource_group_name: str, - namespace_name: str, - private_endpoint_connection_name: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-11-01")) # type: Literal["2021-11-01"] - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/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 - ), - "namespaceName": _SERIALIZER.url("namespace_name", namespace_name, "str", max_length=50, min_length=6), - "privateEndpointConnectionName": _SERIALIZER.url( - "private_endpoint_connection_name", private_endpoint_connection_name, "str" - ), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_delete_request( - resource_group_name: str, - namespace_name: str, - private_endpoint_connection_name: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-11-01")) # type: Literal["2021-11-01"] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/privateEndpointConnections/{privateEndpointConnectionName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "namespaceName": _SERIALIZER.url("namespace_name", namespace_name, "str", max_length=50, min_length=6), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - "privateEndpointConnectionName": _SERIALIZER.url( - "private_endpoint_connection_name", private_endpoint_connection_name, "str" - ), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_request( - resource_group_name: str, - namespace_name: str, - private_endpoint_connection_name: str, - subscription_id: str, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-11-01")) # type: Literal["2021-11-01"] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/privateEndpointConnections/{privateEndpointConnectionName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "namespaceName": _SERIALIZER.url("namespace_name", namespace_name, "str", max_length=50, min_length=6), - "privateEndpointConnectionName": _SERIALIZER.url( - "private_endpoint_connection_name", private_endpoint_connection_name, "str" - ), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -class PrivateEndpointConnectionsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.relay.RelayAPI`'s - :attr:`private_endpoint_connections` 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, resource_group_name: str, namespace_name: str, **kwargs: Any - ) -> Iterable["_models.PrivateEndpointConnection"]: - """Gets the available PrivateEndpointConnections within a namespace. - - :param resource_group_name: Name of the Resource group within the Azure subscription. Required. - :type resource_group_name: str - :param namespace_name: The namespace name. Required. - :type namespace_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PrivateEndpointConnection or the result of - cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.relay.models.PrivateEndpointConnection] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - cls = kwargs.pop("cls", None) # type: ClsType[_models.PrivateEndpointConnectionListResult] - - 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, - namespace_name=namespace_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) # type: ignore - - 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) # type: ignore - request.method = "GET" - return request - - def extract_data(pipeline_response): - deserialized = self._deserialize("PrivateEndpointConnectionListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) - return deserialized.next_link or None, iter(list_of_elem) - - def get_next(next_link=None): - request = prepare_request(next_link) - - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - list.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/privateEndpointConnections"} # type: ignore - - @overload - def create_or_update( - self, - resource_group_name: str, - namespace_name: str, - private_endpoint_connection_name: str, - parameters: _models.PrivateEndpointConnection, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.PrivateEndpointConnection: - """Creates or updates PrivateEndpointConnections of service namespace. - - :param resource_group_name: Name of the Resource group within the Azure subscription. Required. - :type resource_group_name: str - :param namespace_name: The namespace name. Required. - :type namespace_name: str - :param private_endpoint_connection_name: The PrivateEndpointConnection name. Required. - :type private_endpoint_connection_name: str - :param parameters: Parameters supplied to update Status of PrivateEndPoint Connection to - namespace resource. Required. - :type parameters: ~azure.mgmt.relay.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 - :return: PrivateEndpointConnection or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.PrivateEndpointConnection - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_or_update( - self, - resource_group_name: str, - namespace_name: str, - private_endpoint_connection_name: str, - parameters: IO, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.PrivateEndpointConnection: - """Creates or updates PrivateEndpointConnections of service namespace. - - :param resource_group_name: Name of the Resource group within the Azure subscription. Required. - :type resource_group_name: str - :param namespace_name: The namespace name. Required. - :type namespace_name: str - :param private_endpoint_connection_name: The PrivateEndpointConnection name. Required. - :type private_endpoint_connection_name: str - :param parameters: Parameters supplied to update Status of PrivateEndPoint Connection to - namespace resource. Required. - :type parameters: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: PrivateEndpointConnection or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.PrivateEndpointConnection - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create_or_update( - self, - resource_group_name: str, - namespace_name: str, - private_endpoint_connection_name: str, - parameters: Union[_models.PrivateEndpointConnection, IO], - **kwargs: Any - ) -> _models.PrivateEndpointConnection: - """Creates or updates PrivateEndpointConnections of service namespace. - - :param resource_group_name: Name of the Resource group within the Azure subscription. Required. - :type resource_group_name: str - :param namespace_name: The namespace name. Required. - :type namespace_name: str - :param private_endpoint_connection_name: The PrivateEndpointConnection name. Required. - :type private_endpoint_connection_name: str - :param parameters: Parameters supplied to update Status of PrivateEndPoint Connection to - namespace resource. Is either a model type or a IO type. Required. - :type parameters: ~azure.mgmt.relay.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 - :return: PrivateEndpointConnection or the result of cls(response) - :rtype: ~azure.mgmt.relay.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 = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - cls = kwargs.pop("cls", None) # type: ClsType[_models.PrivateEndpointConnection] - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IO, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "PrivateEndpointConnection") - - request = build_create_or_update_request( - resource_group_name=resource_group_name, - namespace_name=namespace_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.metadata["url"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore - - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201, 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 == 201: - deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) - - if response.status_code == 202: - deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - - create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore - - def _delete_initial( # pylint: disable=inconsistent-return-statements - self, resource_group_name: str, namespace_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 = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - cls = kwargs.pop("cls", None) # type: ClsType[None] - - request = build_delete_request( - resource_group_name=resource_group_name, - namespace_name=namespace_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) # type: ignore - - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 202, 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.Relay/namespaces/{namespaceName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore - - @distributed_trace - def begin_delete( - self, resource_group_name: str, namespace_name: str, private_endpoint_connection_name: str, **kwargs: Any - ) -> LROPoller[None]: - """Deletes an existing namespace. This operation also removes all associated resources under the - namespace. - - :param resource_group_name: Name of the Resource group within the Azure subscription. Required. - :type resource_group_name: str - :param namespace_name: The namespace name. Required. - :type namespace_name: str - :param private_endpoint_connection_name: The PrivateEndpointConnection name. 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 = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - cls = kwargs.pop("cls", None) # type: ClsType[None] - polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] - if cont_token is None: - raw_result = self._delete_initial( # type: ignore - resource_group_name=resource_group_name, - namespace_name=namespace_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 = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller.from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - - begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore - - @distributed_trace - def get( - self, resource_group_name: str, namespace_name: str, private_endpoint_connection_name: str, **kwargs: Any - ) -> _models.PrivateEndpointConnection: - """Gets a description for the specified Private Endpoint Connection name. - - :param resource_group_name: Name of the Resource group within the Azure subscription. Required. - :type resource_group_name: str - :param namespace_name: The namespace name. Required. - :type namespace_name: str - :param private_endpoint_connection_name: The PrivateEndpointConnection name. 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.relay.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 = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - cls = kwargs.pop("cls", None) # type: ClsType[_models.PrivateEndpointConnection] - - request = build_get_request( - resource_group_name=resource_group_name, - namespace_name=namespace_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) # type: ignore - - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - - get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore diff --git a/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/operations/_private_link_resources_operations.py b/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/operations/_private_link_resources_operations.py deleted file mode 100644 index 5e43536a52e4..000000000000 --- a/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/operations/_private_link_resources_operations.py +++ /dev/null @@ -1,255 +0,0 @@ -# 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_get_request( - resource_group_name: str, namespace_name: str, private_link_resource_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-11-01")) # type: Literal["2021-11-01"] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/privateLinkResources/{privateLinkResourceName}", - ) # pylint: disable=line-too-long - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "namespaceName": _SERIALIZER.url("namespace_name", namespace_name, "str", max_length=50, min_length=6), - "privateLinkResourceName": _SERIALIZER.url("private_link_resource_name", private_link_resource_name, "str"), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_list_request( - resource_group_name: str, namespace_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-11-01")) # type: Literal["2021-11-01"] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/privateLinkResources", - ) # pylint: disable=line-too-long - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 - ), - "namespaceName": _SERIALIZER.url("namespace_name", namespace_name, "str", max_length=50, min_length=6), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -class PrivateLinkResourcesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.mgmt.relay.RelayAPI`'s - :attr:`private_link_resources` 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, namespace_name: str, private_link_resource_name: str, **kwargs: Any - ) -> _models.PrivateLinkResource: - """Gets a description for the specified Private Endpoint Connection name. - - :param resource_group_name: Name of the Resource group within the Azure subscription. Required. - :type resource_group_name: str - :param namespace_name: The namespace name. Required. - :type namespace_name: str - :param private_link_resource_name: The PrivateLinkResource name. Required. - :type private_link_resource_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: PrivateLinkResource or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.PrivateLinkResource - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - cls = kwargs.pop("cls", None) # type: ClsType[_models.PrivateLinkResource] - - request = build_get_request( - resource_group_name=resource_group_name, - namespace_name=namespace_name, - private_link_resource_name=private_link_resource_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - template_url=self.get.metadata["url"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore - - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PrivateLinkResource", pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - - get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/privateLinkResources/{privateLinkResourceName}"} # type: ignore - - @distributed_trace - def list( - self, resource_group_name: str, namespace_name: str, **kwargs: Any - ) -> _models.PrivateLinkResourcesListResult: - """Gets lists of resources that supports Privatelinks. - - :param resource_group_name: Name of the Resource group within the Azure subscription. Required. - :type resource_group_name: str - :param namespace_name: The namespace name. Required. - :type namespace_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: PrivateLinkResourcesListResult or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.PrivateLinkResourcesListResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - cls = kwargs.pop("cls", None) # type: ClsType[_models.PrivateLinkResourcesListResult] - - request = build_list_request( - resource_group_name=resource_group_name, - namespace_name=namespace_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) # type: ignore - - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - - deserialized = self._deserialize("PrivateLinkResourcesListResult", pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - - list.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/privateLinkResources"} # type: ignore diff --git a/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/operations/_wcf_relays_operations.py b/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/operations/_wcf_relays_operations.py index 80dfdd8af98b..5f175d60c660 100644 --- a/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/operations/_wcf_relays_operations.py +++ b/sdk/relay/azure-mgmt-relay/azure/mgmt/relay/operations/_wcf_relays_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=line-too-long,useless-suppression,too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,10 +6,12 @@ # 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, overload +from collections.abc import MutableMapping +from io import IOBase +from typing import Any, Callable, IO, Optional, TypeVar, Union, overload import urllib.parse +from azure.core import PipelineClient from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, @@ -20,51 +22,46 @@ ) 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.rest import HttpRequest, HttpResponse 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 +from .._configuration import RelayAPIConfiguration +from .._utils.serialization import Deserializer, Serializer -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]] +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] +List = list _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_list_authorization_rules_request( - resource_group_name: str, namespace_name: str, relay_name: str, subscription_id: str, **kwargs: Any +def build_list_by_namespace_request( + resource_group_name: str, namespace_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-11-01")) # type: Literal["2021-11-01"] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-04-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/wcfRelays/{relayName}/authorizationRules", - ) # pylint: disable=line-too-long + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/wcfRelays", + ) path_format_arguments = { "resourceGroupName": _SERIALIZER.url( "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 ), "namespaceName": _SERIALIZER.url("namespace_name", namespace_name, "str", max_length=50, min_length=6), - "relayName": _SERIALIZER.url("relay_name", relay_name, "str", min_length=1), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -75,39 +72,31 @@ def build_list_authorization_rules_request( return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_create_or_update_authorization_rule_request( - resource_group_name: str, - namespace_name: str, - relay_name: str, - authorization_rule_name: str, - subscription_id: str, - **kwargs: Any +def build_create_or_update_request( + resource_group_name: str, namespace_name: str, relay_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-11-01")) # type: Literal["2021-11-01"] - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/wcfRelays/{relayName}/authorizationRules/{authorizationRuleName}", - ) # pylint: disable=line-too-long + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/wcfRelays/{relayName}", + ) path_format_arguments = { "resourceGroupName": _SERIALIZER.url( "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 ), "namespaceName": _SERIALIZER.url("namespace_name", namespace_name, "str", max_length=50, min_length=6), "relayName": _SERIALIZER.url("relay_name", relay_name, "str", min_length=1), - "authorizationRuleName": _SERIALIZER.url( - "authorization_rule_name", authorization_rule_name, "str", min_length=1 - ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -120,38 +109,30 @@ def build_create_or_update_authorization_rule_request( return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) -def build_delete_authorization_rule_request( - resource_group_name: str, - namespace_name: str, - relay_name: str, - authorization_rule_name: str, - subscription_id: str, - **kwargs: Any +def build_delete_request( + resource_group_name: str, namespace_name: str, relay_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-11-01")) # type: Literal["2021-11-01"] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-04-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/wcfRelays/{relayName}/authorizationRules/{authorizationRuleName}", - ) # pylint: disable=line-too-long + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/wcfRelays/{relayName}", + ) path_format_arguments = { "resourceGroupName": _SERIALIZER.url( "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 ), "namespaceName": _SERIALIZER.url("namespace_name", namespace_name, "str", max_length=50, min_length=6), "relayName": _SERIALIZER.url("relay_name", relay_name, "str", min_length=1), - "authorizationRuleName": _SERIALIZER.url( - "authorization_rule_name", authorization_rule_name, "str", min_length=1 - ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -162,38 +143,30 @@ def build_delete_authorization_rule_request( return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) -def build_get_authorization_rule_request( - resource_group_name: str, - namespace_name: str, - relay_name: str, - authorization_rule_name: str, - subscription_id: str, - **kwargs: Any +def build_get_request( + resource_group_name: str, namespace_name: str, relay_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-11-01")) # type: Literal["2021-11-01"] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-04-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/wcfRelays/{relayName}/authorizationRules/{authorizationRuleName}", - ) # pylint: disable=line-too-long + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/wcfRelays/{relayName}", + ) path_format_arguments = { "resourceGroupName": _SERIALIZER.url( "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 ), "namespaceName": _SERIALIZER.url("namespace_name", namespace_name, "str", max_length=50, min_length=6), "relayName": _SERIALIZER.url("relay_name", relay_name, "str", min_length=1), - "authorizationRuleName": _SERIALIZER.url( - "authorization_rule_name", authorization_rule_name, "str", min_length=1 - ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -204,38 +177,30 @@ def build_get_authorization_rule_request( return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_list_keys_request( - resource_group_name: str, - namespace_name: str, - relay_name: str, - authorization_rule_name: str, - subscription_id: str, - **kwargs: Any +def build_list_authorization_rules_request( + resource_group_name: str, namespace_name: str, relay_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-11-01")) # type: Literal["2021-11-01"] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-04-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/wcfRelays/{relayName}/authorizationRules/{authorizationRuleName}/listKeys", - ) # pylint: disable=line-too-long + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/wcfRelays/{relayName}/authorizationRules", + ) path_format_arguments = { "resourceGroupName": _SERIALIZER.url( "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 ), "namespaceName": _SERIALIZER.url("namespace_name", namespace_name, "str", max_length=50, min_length=6), "relayName": _SERIALIZER.url("relay_name", relay_name, "str", min_length=1), - "authorizationRuleName": _SERIALIZER.url( - "authorization_rule_name", authorization_rule_name, "str", min_length=1 - ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -243,10 +208,10 @@ def build_list_keys_request( # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_regenerate_keys_request( +def build_create_or_update_authorization_rule_request( # pylint: disable=name-too-long resource_group_name: str, namespace_name: str, relay_name: str, @@ -257,15 +222,15 @@ def build_regenerate_keys_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-11-01")) # type: Literal["2021-11-01"] - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/wcfRelays/{relayName}/authorizationRules/{authorizationRuleName}/regenerateKeys", - ) # pylint: disable=line-too-long + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/wcfRelays/{relayName}/authorizationRules/{authorizationRuleName}", + ) path_format_arguments = { "resourceGroupName": _SERIALIZER.url( "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 @@ -278,7 +243,7 @@ def build_regenerate_keys_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -288,32 +253,41 @@ def build_regenerate_keys_request( _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) + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) -def build_list_by_namespace_request( - resource_group_name: str, namespace_name: str, subscription_id: str, **kwargs: Any +def build_delete_authorization_rule_request( + resource_group_name: str, + namespace_name: str, + relay_name: str, + authorization_rule_name: str, + subscription_id: str, + **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-11-01")) # type: Literal["2021-11-01"] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-04-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/wcfRelays", - ) # pylint: disable=line-too-long + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/wcfRelays/{relayName}/authorizationRules/{authorizationRuleName}", + ) path_format_arguments = { "resourceGroupName": _SERIALIZER.url( "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 ), "namespaceName": _SERIALIZER.url("namespace_name", namespace_name, "str", max_length=50, min_length=6), + "relayName": _SERIALIZER.url("relay_name", relay_name, "str", min_length=1), + "authorizationRuleName": _SERIALIZER.url( + "authorization_rule_name", authorization_rule_name, "str", min_length=1 + ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -321,70 +295,83 @@ def build_list_by_namespace_request( # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) -def build_create_or_update_request( - resource_group_name: str, namespace_name: str, relay_name: str, subscription_id: str, **kwargs: Any +def build_get_authorization_rule_request( + resource_group_name: str, + namespace_name: str, + relay_name: str, + authorization_rule_name: str, + subscription_id: str, + **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-11-01")) # type: Literal["2021-11-01"] - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-04-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/wcfRelays/{relayName}", - ) # pylint: disable=line-too-long + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/wcfRelays/{relayName}/authorizationRules/{authorizationRuleName}", + ) path_format_arguments = { "resourceGroupName": _SERIALIZER.url( "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 ), "namespaceName": _SERIALIZER.url("namespace_name", namespace_name, "str", max_length=50, min_length=6), "relayName": _SERIALIZER.url("relay_name", relay_name, "str", min_length=1), + "authorizationRuleName": _SERIALIZER.url( + "authorization_rule_name", authorization_rule_name, "str", min_length=1 + ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_delete_request( - resource_group_name: str, namespace_name: str, relay_name: str, subscription_id: str, **kwargs: Any +def build_list_keys_request( + resource_group_name: str, + namespace_name: str, + relay_name: str, + authorization_rule_name: str, + subscription_id: str, + **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-11-01")) # type: Literal["2021-11-01"] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-04-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/wcfRelays/{relayName}", - ) # pylint: disable=line-too-long + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/wcfRelays/{relayName}/authorizationRules/{authorizationRuleName}/listKeys", + ) path_format_arguments = { "resourceGroupName": _SERIALIZER.url( "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 ), "namespaceName": _SERIALIZER.url("namespace_name", namespace_name, "str", max_length=50, min_length=6), "relayName": _SERIALIZER.url("relay_name", relay_name, "str", min_length=1), + "authorizationRuleName": _SERIALIZER.url( + "authorization_rule_name", authorization_rule_name, "str", min_length=1 + ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -392,41 +379,52 @@ def build_delete_request( # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_get_request( - resource_group_name: str, namespace_name: str, relay_name: str, subscription_id: str, **kwargs: Any +def build_regenerate_keys_request( + resource_group_name: str, + namespace_name: str, + relay_name: str, + authorization_rule_name: str, + subscription_id: str, + **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-11-01")) # type: Literal["2021-11-01"] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-04-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/wcfRelays/{relayName}", - ) # pylint: disable=line-too-long + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/wcfRelays/{relayName}/authorizationRules/{authorizationRuleName}/regenerateKeys", + ) path_format_arguments = { "resourceGroupName": _SERIALIZER.url( "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 ), "namespaceName": _SERIALIZER.url("namespace_name", namespace_name, "str", max_length=50, min_length=6), "relayName": _SERIALIZER.url("relay_name", relay_name, "str", min_length=1), + "authorizationRuleName": _SERIALIZER.url( + "authorization_rule_name", authorization_rule_name, "str", min_length=1 + ), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _url.format(**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="GET", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) class WCFRelaysOperations: @@ -441,39 +439,34 @@ class WCFRelaysOperations: models = _models - def __init__(self, *args, **kwargs): + 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") + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: RelayAPIConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace - def list_authorization_rules( - self, resource_group_name: str, namespace_name: str, relay_name: str, **kwargs: Any - ) -> Iterable["_models.AuthorizationRule"]: - """Authorization rules for a WCF relay. + def list_by_namespace( + self, resource_group_name: str, namespace_name: str, **kwargs: Any + ) -> ItemPaged["_models.WcfRelay"]: + """Lists the WCF relays within the namespace. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str :param namespace_name: The namespace name. Required. :type namespace_name: str - :param relay_name: The relay name. Required. - :type relay_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either AuthorizationRule or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.relay.models.AuthorizationRule] + :return: An iterator like instance of either WcfRelay or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.relay.models.WcfRelay] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - cls = kwargs.pop("cls", None) # type: ClsType[_models.AuthorizationRuleListResult] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.WcfRelaysListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -484,18 +477,15 @@ def list_authorization_rules( def prepare_request(next_link=None): if not next_link: - request = build_list_authorization_rules_request( + _request = build_list_by_namespace_request( resource_group_name=resource_group_name, namespace_name=namespace_name, - relay_name=relay_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_authorization_rules.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -507,52 +497,53 @@ def prepare_request(next_link=None): } ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _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) # type: ignore - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): - deserialized = self._deserialize("AuthorizationRuleListResult", pipeline_response) + deserialized = self._deserialize("WcfRelaysListResult", 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) + _request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + 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_authorization_rules.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/wcfRelays/{relayName}/authorizationRules"} # type: ignore - @overload - def create_or_update_authorization_rule( + def create_or_update( self, resource_group_name: str, namespace_name: str, relay_name: str, - authorization_rule_name: str, - parameters: _models.AuthorizationRule, + parameters: _models.WcfRelay, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.AuthorizationRule: - """Creates or updates an authorization rule for a WCF relay. + ) -> _models.WcfRelay: + """Creates or updates a WCF relay. This operation is idempotent. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str @@ -560,32 +551,28 @@ def create_or_update_authorization_rule( :type namespace_name: str :param relay_name: The relay name. Required. :type relay_name: str - :param authorization_rule_name: The authorization rule name. Required. - :type authorization_rule_name: str - :param parameters: The authorization rule parameters. Required. - :type parameters: ~azure.mgmt.relay.models.AuthorizationRule + :param parameters: Parameters supplied to create a WCF relay. Required. + :type parameters: ~azure.mgmt.relay.models.WcfRelay :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: AuthorizationRule or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.AuthorizationRule + :return: WcfRelay or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.WcfRelay :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def create_or_update_authorization_rule( + def create_or_update( self, resource_group_name: str, namespace_name: str, relay_name: str, - authorization_rule_name: str, - parameters: IO, + parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.AuthorizationRule: - """Creates or updates an authorization rule for a WCF relay. + ) -> _models.WcfRelay: + """Creates or updates a WCF relay. This operation is idempotent. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str @@ -593,30 +580,26 @@ def create_or_update_authorization_rule( :type namespace_name: str :param relay_name: The relay name. Required. :type relay_name: str - :param authorization_rule_name: The authorization rule name. Required. - :type authorization_rule_name: str - :param parameters: The authorization rule parameters. Required. - :type parameters: IO + :param parameters: Parameters supplied to create a WCF relay. Required. + :type parameters: IO[bytes] :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: AuthorizationRule or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.AuthorizationRule + :return: WcfRelay or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.WcfRelay :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace - def create_or_update_authorization_rule( + def create_or_update( self, resource_group_name: str, namespace_name: str, relay_name: str, - authorization_rule_name: str, - parameters: Union[_models.AuthorizationRule, IO], + parameters: Union[_models.WcfRelay, IO[bytes]], **kwargs: Any - ) -> _models.AuthorizationRule: - """Creates or updates an authorization rule for a WCF relay. + ) -> _models.WcfRelay: + """Creates or updates a WCF relay. This operation is idempotent. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str @@ -624,20 +607,14 @@ def create_or_update_authorization_rule( :type namespace_name: str :param relay_name: The relay name. Required. :type relay_name: str - :param authorization_rule_name: The authorization rule name. Required. - :type authorization_rule_name: str - :param parameters: The authorization rule parameters. Is either a model type or a IO type. - Required. - :type parameters: ~azure.mgmt.relay.models.AuthorizationRule 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: AuthorizationRule or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.AuthorizationRule + :param parameters: Parameters supplied to create a WCF relay. Is either a WcfRelay type or a + IO[bytes] type. Required. + :type parameters: ~azure.mgmt.relay.models.WcfRelay or IO[bytes] + :return: WcfRelay or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.WcfRelay :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -648,67 +625,59 @@ def create_or_update_authorization_rule( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - cls = kwargs.pop("cls", None) # type: ClsType[_models.AuthorizationRule] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.WcfRelay] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(parameters, (IO, bytes)): + if isinstance(parameters, (IOBase, bytes)): _content = parameters else: - _json = self._serialize.body(parameters, "AuthorizationRule") + _json = self._serialize.body(parameters, "WcfRelay") - request = build_create_or_update_authorization_rule_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, namespace_name=namespace_name, relay_name=relay_name, - authorization_rule_name=authorization_rule_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_authorization_rule.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("AuthorizationRule", pipeline_response) + deserialized = self._deserialize("WcfRelay", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - create_or_update_authorization_rule.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/wcfRelays/{relayName}/authorizationRules/{authorizationRuleName}"} # type: ignore + return deserialized # type: ignore @distributed_trace - def delete_authorization_rule( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - namespace_name: str, - relay_name: str, - authorization_rule_name: str, - **kwargs: Any + def delete( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, namespace_name: str, relay_name: str, **kwargs: Any ) -> None: - """Deletes a WCF relay authorization rule. + """Deletes a WCF relay. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str @@ -716,14 +685,11 @@ def delete_authorization_rule( # pylint: disable=inconsistent-return-statements :type namespace_name: str :param relay_name: The relay name. Required. :type relay_name: str - :param authorization_rule_name: The authorization rule name. Required. - :type authorization_rule_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -734,51 +700,43 @@ def delete_authorization_rule( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - cls = kwargs.pop("cls", None) # type: ClsType[None] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_authorization_rule_request( + _request = build_delete_request( resource_group_name=resource_group_name, namespace_name=namespace_name, relay_name=relay_name, - authorization_rule_name=authorization_rule_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.delete_authorization_rule.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + 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_authorization_rule.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/wcfRelays/{relayName}/authorizationRules/{authorizationRuleName}"} # type: ignore + return cls(pipeline_response, None, {}) # type: ignore @distributed_trace - def get_authorization_rule( - self, - resource_group_name: str, - namespace_name: str, - relay_name: str, - authorization_rule_name: str, - **kwargs: Any - ) -> _models.AuthorizationRule: - """Get authorizationRule for a WCF relay by name. + def get( + self, resource_group_name: str, namespace_name: str, relay_name: str, **kwargs: Any + ) -> Optional[_models.WcfRelay]: + """Returns the description for the specified WCF relay. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str @@ -786,14 +744,11 @@ def get_authorization_rule( :type namespace_name: str :param relay_name: The relay name. Required. :type relay_name: str - :param authorization_rule_name: The authorization rule name. Required. - :type authorization_rule_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: AuthorizationRule or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.AuthorizationRule + :return: WcfRelay or None or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.WcfRelay or None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -804,55 +759,49 @@ def get_authorization_rule( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - cls = kwargs.pop("cls", None) # type: ClsType[_models.AuthorizationRule] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[Optional[_models.WcfRelay]] = kwargs.pop("cls", None) - request = build_get_authorization_rule_request( + _request = build_get_request( resource_group_name=resource_group_name, namespace_name=namespace_name, relay_name=relay_name, - authorization_rule_name=authorization_rule_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get_authorization_rule.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response - if response.status_code not in [200]: + if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("AuthorizationRule", pipeline_response) + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize("WcfRelay", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get_authorization_rule.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/wcfRelays/{relayName}/authorizationRules/{authorizationRuleName}"} # type: ignore + return deserialized # type: ignore @distributed_trace - def list_keys( - self, - resource_group_name: str, - namespace_name: str, - relay_name: str, - authorization_rule_name: str, - **kwargs: Any - ) -> _models.AccessKeys: - """Primary and secondary connection strings to the WCF relay. + def list_authorization_rules( + self, resource_group_name: str, namespace_name: str, relay_name: str, **kwargs: Any + ) -> ItemPaged["_models.AuthorizationRule"]: + """Authorization rules for a WCF relay. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str @@ -860,14 +809,17 @@ def list_keys( :type namespace_name: str :param relay_name: The relay name. Required. :type relay_name: str - :param authorization_rule_name: The authorization rule name. Required. - :type authorization_rule_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: AccessKeys or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.AccessKeys + :return: An iterator like instance of either AuthorizationRule or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.relay.models.AuthorizationRule] :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.AuthorizationRuleListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -875,61 +827,74 @@ def list_keys( } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessKeys] + def prepare_request(next_link=None): + if not next_link: - request = build_list_keys_request( - resource_group_name=resource_group_name, - namespace_name=namespace_name, - relay_name=relay_name, - authorization_rule_name=authorization_rule_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - template_url=self.list_keys.metadata["url"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request = build_list_authorization_rules_request( + resource_group_name=resource_group_name, + namespace_name=namespace_name, + relay_name=relay_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs - ) + 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.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request - response = pipeline_response.http_response + def extract_data(pipeline_response): + deserialized = self._deserialize("AuthorizationRuleListResult", 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) - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) - raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + def get_next(next_link=None): + _request = prepare_request(next_link) - deserialized = self._deserialize("AccessKeys", pipeline_response) + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response - if cls: - return cls(pipeline_response, deserialized, {}) + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response, error_format=ARMErrorFormat) - return deserialized + return pipeline_response - list_keys.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/wcfRelays/{relayName}/authorizationRules/{authorizationRuleName}/listKeys"} # type: ignore + return ItemPaged(get_next, extract_data) @overload - def regenerate_keys( + def create_or_update_authorization_rule( self, resource_group_name: str, namespace_name: str, relay_name: str, authorization_rule_name: str, - parameters: _models.RegenerateAccessKeyParameters, + parameters: _models.AuthorizationRule, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.AccessKeys: - """Regenerates the primary or secondary connection strings to the WCF relay. + ) -> _models.AuthorizationRule: + """Creates or updates an authorization rule for a WCF relay. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str @@ -939,30 +904,29 @@ def regenerate_keys( :type relay_name: str :param authorization_rule_name: The authorization rule name. Required. :type authorization_rule_name: str - :param parameters: Parameters supplied to regenerate authorization rule. Required. - :type parameters: ~azure.mgmt.relay.models.RegenerateAccessKeyParameters + :param parameters: The authorization rule parameters. Required. + :type parameters: ~azure.mgmt.relay.models.AuthorizationRule :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: AccessKeys or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.AccessKeys + :return: AuthorizationRule or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.AuthorizationRule :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def regenerate_keys( + def create_or_update_authorization_rule( self, resource_group_name: str, namespace_name: str, relay_name: str, authorization_rule_name: str, - parameters: IO, + parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.AccessKeys: - """Regenerates the primary or secondary connection strings to the WCF relay. + ) -> _models.AuthorizationRule: + """Creates or updates an authorization rule for a WCF relay. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str @@ -972,28 +936,27 @@ def regenerate_keys( :type relay_name: str :param authorization_rule_name: The authorization rule name. Required. :type authorization_rule_name: str - :param parameters: Parameters supplied to regenerate authorization rule. Required. - :type parameters: IO + :param parameters: The authorization rule parameters. Required. + :type parameters: IO[bytes] :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: AccessKeys or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.AccessKeys + :return: AuthorizationRule or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.AuthorizationRule :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace - def regenerate_keys( + def create_or_update_authorization_rule( self, resource_group_name: str, namespace_name: str, relay_name: str, authorization_rule_name: str, - parameters: Union[_models.RegenerateAccessKeyParameters, IO], + parameters: Union[_models.AuthorizationRule, IO[bytes]], **kwargs: Any - ) -> _models.AccessKeys: - """Regenerates the primary or secondary connection strings to the WCF relay. + ) -> _models.AuthorizationRule: + """Creates or updates an authorization rule for a WCF relay. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str @@ -1003,18 +966,14 @@ def regenerate_keys( :type relay_name: str :param authorization_rule_name: The authorization rule name. Required. :type authorization_rule_name: str - :param parameters: Parameters supplied to regenerate authorization rule. Is either a model type - or a IO type. Required. - :type parameters: ~azure.mgmt.relay.models.RegenerateAccessKeyParameters 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: AccessKeys or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.AccessKeys + :param parameters: The authorization rule parameters. Is either a AuthorizationRule type or a + IO[bytes] type. Required. + :type parameters: ~azure.mgmt.relay.models.AuthorizationRule or IO[bytes] + :return: AuthorizationRule or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.AuthorizationRule :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1025,21 +984,19 @@ def regenerate_keys( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - cls = kwargs.pop("cls", None) # type: ClsType[_models.AccessKeys] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.AuthorizationRule] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(parameters, (IO, bytes)): + if isinstance(parameters, (IOBase, bytes)): _content = parameters else: - _json = self._serialize.body(parameters, "RegenerateAccessKeyParameters") + _json = self._serialize.body(parameters, "AuthorizationRule") - request = build_regenerate_keys_request( + _request = build_create_or_update_authorization_rule_request( resource_group_name=resource_group_name, namespace_name=namespace_name, relay_name=relay_name, @@ -1049,57 +1006,57 @@ def regenerate_keys( content_type=content_type, json=_json, content=_content, - template_url=self.regenerate_keys.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("AccessKeys", pipeline_response) + deserialized = self._deserialize("AuthorizationRule", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - regenerate_keys.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/wcfRelays/{relayName}/authorizationRules/{authorizationRuleName}/regenerateKeys"} # type: ignore + return deserialized # type: ignore @distributed_trace - def list_by_namespace( - self, resource_group_name: str, namespace_name: str, **kwargs: Any - ) -> Iterable["_models.WcfRelay"]: - """Lists the WCF relays within the namespace. + def delete_authorization_rule( # pylint: disable=inconsistent-return-statements + self, + resource_group_name: str, + namespace_name: str, + relay_name: str, + authorization_rule_name: str, + **kwargs: Any + ) -> None: + """Deletes a WCF relay authorization rule. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str :param namespace_name: The namespace name. Required. :type namespace_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either WcfRelay or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.relay.models.WcfRelay] + :param relay_name: The relay name. Required. + :type relay_name: str + :param authorization_rule_name: The authorization rule name. Required. + :type authorization_rule_name: str + :return: None or the result of cls(response) + :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - cls = kwargs.pop("cls", None) # type: ClsType[_models.WcfRelaysListResult] - - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1107,135 +1064,52 @@ def list_by_namespace( } error_map.update(kwargs.pop("error_map", {}) or {}) - def prepare_request(next_link=None): - if not next_link: + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - request = build_list_by_namespace_request( - resource_group_name=resource_group_name, - namespace_name=namespace_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - template_url=self.list_by_namespace.metadata["url"], - headers=_headers, - params=_params, - ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[None] = kwargs.pop("cls", None) - 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) # type: ignore - request.method = "GET" - return request + _request = build_delete_authorization_rule_request( + resource_group_name=resource_group_name, + namespace_name=namespace_name, + relay_name=relay_name, + authorization_rule_name=authorization_rule_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) - def extract_data(pipeline_response): - deserialized = self._deserialize("WcfRelaysListResult", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) - return deserialized.next_link or None, iter(list_of_elem) + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) - def get_next(next_link=None): - request = prepare_request(next_link) + response = pipeline_response.http_response - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, 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_namespace.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/wcfRelays"} # type: ignore - - @overload - def create_or_update( - self, - resource_group_name: str, - namespace_name: str, - relay_name: str, - parameters: _models.WcfRelay, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.WcfRelay: - """Creates or updates a WCF relay. This operation is idempotent. - - :param resource_group_name: Name of the Resource group within the Azure subscription. Required. - :type resource_group_name: str - :param namespace_name: The namespace name. Required. - :type namespace_name: str - :param relay_name: The relay name. Required. - :type relay_name: str - :param parameters: Parameters supplied to create a WCF relay. Required. - :type parameters: ~azure.mgmt.relay.models.WcfRelay - :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: WcfRelay or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.WcfRelay - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_or_update( - self, - resource_group_name: str, - namespace_name: str, - relay_name: str, - parameters: IO, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.WcfRelay: - """Creates or updates a WCF relay. This operation is idempotent. + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - :param resource_group_name: Name of the Resource group within the Azure subscription. Required. - :type resource_group_name: str - :param namespace_name: The namespace name. Required. - :type namespace_name: str - :param relay_name: The relay name. Required. - :type relay_name: str - :param parameters: Parameters supplied to create a WCF relay. Required. - :type parameters: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: WcfRelay or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.WcfRelay - :raises ~azure.core.exceptions.HttpResponseError: - """ + if cls: + return cls(pipeline_response, None, {}) # type: ignore @distributed_trace - def create_or_update( + def get_authorization_rule( self, resource_group_name: str, namespace_name: str, relay_name: str, - parameters: Union[_models.WcfRelay, IO], + authorization_rule_name: str, **kwargs: Any - ) -> _models.WcfRelay: - """Creates or updates a WCF relay. This operation is idempotent. + ) -> _models.AuthorizationRule: + """Get authorizationRule for a WCF relay by name. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str @@ -1243,18 +1117,13 @@ def create_or_update( :type namespace_name: str :param relay_name: The relay name. Required. :type relay_name: str - :param parameters: Parameters supplied to create a WCF relay. Is either a model type or a IO - type. Required. - :type parameters: ~azure.mgmt.relay.models.WcfRelay 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: WcfRelay or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.WcfRelay + :param authorization_rule_name: The authorization rule name. Required. + :type authorization_rule_name: str + :return: AuthorizationRule or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.AuthorizationRule :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1262,64 +1131,56 @@ def create_or_update( } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - cls = kwargs.pop("cls", None) # type: ClsType[_models.WcfRelay] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.AuthorizationRule] = kwargs.pop("cls", None) - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(parameters, (IO, bytes)): - _content = parameters - else: - _json = self._serialize.body(parameters, "WcfRelay") - - request = build_create_or_update_request( + _request = build_get_authorization_rule_request( resource_group_name=resource_group_name, namespace_name=namespace_name, relay_name=relay_name, + authorization_rule_name=authorization_rule_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.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("WcfRelay", pipeline_response) + deserialized = self._deserialize("AuthorizationRule", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/wcfRelays/{relayName}"} # type: ignore + return deserialized # type: ignore @distributed_trace - def delete( # pylint: disable=inconsistent-return-statements - self, resource_group_name: str, namespace_name: str, relay_name: str, **kwargs: Any - ) -> None: - """Deletes a WCF relay. + def list_keys( + self, + resource_group_name: str, + namespace_name: str, + relay_name: str, + authorization_rule_name: str, + **kwargs: Any + ) -> _models.AccessKeys: + """Primary and secondary connection strings to the WCF relay. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str @@ -1327,12 +1188,13 @@ def delete( # pylint: disable=inconsistent-return-statements :type namespace_name: str :param relay_name: The relay name. Required. :type relay_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: None or the result of cls(response) - :rtype: None + :param authorization_rule_name: The authorization rule name. Required. + :type authorization_rule_name: str + :return: AccessKeys or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.AccessKeys :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1343,45 +1205,118 @@ def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - cls = kwargs.pop("cls", None) # type: ClsType[None] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + cls: ClsType[_models.AccessKeys] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_list_keys_request( resource_group_name=resource_group_name, namespace_name=namespace_name, relay_name=relay_name, + authorization_rule_name=authorization_rule_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.delete.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response - if response.status_code not in [200, 204]: + if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + error = self._deserialize.failsafe_deserialize( + _models.ErrorResponse, + pipeline_response, + ) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + deserialized = self._deserialize("AccessKeys", pipeline_response.http_response) + if cls: - return cls(pipeline_response, None, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/wcfRelays/{relayName}"} # type: ignore + return deserialized # type: ignore + + @overload + def regenerate_keys( + self, + resource_group_name: str, + namespace_name: str, + relay_name: str, + authorization_rule_name: str, + parameters: _models.RegenerateAccessKeyParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.AccessKeys: + """Regenerates the primary or secondary connection strings to the WCF relay. + + :param resource_group_name: Name of the Resource group within the Azure subscription. Required. + :type resource_group_name: str + :param namespace_name: The namespace name. Required. + :type namespace_name: str + :param relay_name: The relay name. Required. + :type relay_name: str + :param authorization_rule_name: The authorization rule name. Required. + :type authorization_rule_name: str + :param parameters: Parameters supplied to regenerate authorization rule. Required. + :type parameters: ~azure.mgmt.relay.models.RegenerateAccessKeyParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: AccessKeys or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.AccessKeys + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def regenerate_keys( + self, + resource_group_name: str, + namespace_name: str, + relay_name: str, + authorization_rule_name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.AccessKeys: + """Regenerates the primary or secondary connection strings to the WCF relay. + + :param resource_group_name: Name of the Resource group within the Azure subscription. Required. + :type resource_group_name: str + :param namespace_name: The namespace name. Required. + :type namespace_name: str + :param relay_name: The relay name. Required. + :type relay_name: str + :param authorization_rule_name: The authorization rule name. Required. + :type authorization_rule_name: str + :param parameters: Parameters supplied to regenerate authorization rule. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: AccessKeys or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.AccessKeys + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace - def get( - self, resource_group_name: str, namespace_name: str, relay_name: str, **kwargs: Any - ) -> Optional[_models.WcfRelay]: - """Returns the description for the specified WCF relay. + def regenerate_keys( + self, + resource_group_name: str, + namespace_name: str, + relay_name: str, + authorization_rule_name: str, + parameters: Union[_models.RegenerateAccessKeyParameters, IO[bytes]], + **kwargs: Any + ) -> _models.AccessKeys: + """Regenerates the primary or secondary connection strings to the WCF relay. :param resource_group_name: Name of the Resource group within the Azure subscription. Required. :type resource_group_name: str @@ -1389,12 +1324,16 @@ def get( :type namespace_name: str :param relay_name: The relay name. Required. :type relay_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: WcfRelay or None or the result of cls(response) - :rtype: ~azure.mgmt.relay.models.WcfRelay or None + :param authorization_rule_name: The authorization rule name. Required. + :type authorization_rule_name: str + :param parameters: Parameters supplied to regenerate authorization rule. Is either a + RegenerateAccessKeyParameters type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.relay.models.RegenerateAccessKeyParameters or IO[bytes] + :return: AccessKeys or the result of cls(response) + :rtype: ~azure.mgmt.relay.models.AccessKeys :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1402,45 +1341,54 @@ def get( } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = kwargs.pop("headers", {}) or {} + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop( - "api_version", _params.pop("api-version", self._config.api_version) - ) # type: Literal["2021-11-01"] - cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.WcfRelay]] + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.AccessKeys] = kwargs.pop("cls", None) - request = build_get_request( + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "RegenerateAccessKeyParameters") + + _request = build_regenerate_keys_request( resource_group_name=resource_group_name, namespace_name=namespace_name, relay_name=relay_name, + authorization_rule_name=authorization_rule_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata["url"], + content_type=content_type, + json=_json, + content=_content, headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) # type: ignore + _request.url = self._client.format_url(_request.url) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response - if response.status_code not in [200, 204]: + if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + 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("WcfRelay", pipeline_response) + deserialized = self._deserialize("AccessKeys", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/wcfRelays/{relayName}"} # type: ignore + return deserialized # type: ignore diff --git a/sdk/relay/azure-mgmt-relay/dev_requirements.txt b/sdk/relay/azure-mgmt-relay/dev_requirements.txt index f802d9f73053..d6181f7461db 100644 --- a/sdk/relay/azure-mgmt-relay/dev_requirements.txt +++ b/sdk/relay/azure-mgmt-relay/dev_requirements.txt @@ -1,3 +1,4 @@ -e ../../../eng/tools/azure-sdk-tools ../../resources/azure-mgmt-resource -../../identity/azure-identity \ No newline at end of file +../../identity/azure-identity +aiohttp diff --git a/sdk/relay/azure-mgmt-relay/generated_samples/relay_hybrid_connection_authorization_rule_create.py b/sdk/relay/azure-mgmt-relay/generated_samples/hybrid_connection/relay_hybrid_connection_authorization_rule_create.py similarity index 91% rename from sdk/relay/azure-mgmt-relay/generated_samples/relay_hybrid_connection_authorization_rule_create.py rename to sdk/relay/azure-mgmt-relay/generated_samples/hybrid_connection/relay_hybrid_connection_authorization_rule_create.py index 91aab45fb51c..dcdc156fc95e 100644 --- a/sdk/relay/azure-mgmt-relay/generated_samples/relay_hybrid_connection_authorization_rule_create.py +++ b/sdk/relay/azure-mgmt-relay/generated_samples/hybrid_connection/relay_hybrid_connection_authorization_rule_create.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.relay import RelayAPI """ @@ -39,6 +41,6 @@ def main(): print(response) -# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/stable/2021-11-01/examples/HybridConnection/RelayHybridConnectionAuthorizationRuleCreate.json +# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/Relay/stable/2017-04-01/examples/HybridConnection/RelayHybridConnectionAuthorizationRuleCreate.json if __name__ == "__main__": main() diff --git a/sdk/relay/azure-mgmt-relay/generated_samples/relay_hybrid_connection_authorization_rule_list_key.py b/sdk/relay/azure-mgmt-relay/generated_samples/hybrid_connection/relay_hybrid_connection_authorization_rule_list_key.py similarity index 90% rename from sdk/relay/azure-mgmt-relay/generated_samples/relay_hybrid_connection_authorization_rule_list_key.py rename to sdk/relay/azure-mgmt-relay/generated_samples/hybrid_connection/relay_hybrid_connection_authorization_rule_list_key.py index ef8e40e847fd..1ae52ee166ac 100644 --- a/sdk/relay/azure-mgmt-relay/generated_samples/relay_hybrid_connection_authorization_rule_list_key.py +++ b/sdk/relay/azure-mgmt-relay/generated_samples/hybrid_connection/relay_hybrid_connection_authorization_rule_list_key.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.relay import RelayAPI """ @@ -38,6 +40,6 @@ def main(): print(response) -# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/stable/2021-11-01/examples/HybridConnection/RelayHybridConnectionAuthorizationRuleListKey.json +# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/Relay/stable/2017-04-01/examples/HybridConnection/RelayHybridConnectionAuthorizationRuleListKey.json if __name__ == "__main__": main() diff --git a/sdk/relay/azure-mgmt-relay/generated_samples/relay_hybrid_connection_authorization_rule_regenerate_key.py b/sdk/relay/azure-mgmt-relay/generated_samples/hybrid_connection/relay_hybrid_connection_authorization_rule_regenrate_key.py similarity index 87% rename from sdk/relay/azure-mgmt-relay/generated_samples/relay_hybrid_connection_authorization_rule_regenerate_key.py rename to sdk/relay/azure-mgmt-relay/generated_samples/hybrid_connection/relay_hybrid_connection_authorization_rule_regenrate_key.py index 3f36d769cc69..9bf13abb5c68 100644 --- a/sdk/relay/azure-mgmt-relay/generated_samples/relay_hybrid_connection_authorization_rule_regenerate_key.py +++ b/sdk/relay/azure-mgmt-relay/generated_samples/hybrid_connection/relay_hybrid_connection_authorization_rule_regenrate_key.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.relay import RelayAPI """ @@ -14,7 +16,7 @@ pip install azure-identity pip install azure-mgmt-relay # USAGE - python relay_hybrid_connection_authorization_rule_regenerate_key.py + python relay_hybrid_connection_authorization_rule_regenrate_key.py Before run the sample, please set the values of the client ID, tenant ID and client secret of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, @@ -39,6 +41,6 @@ def main(): print(response) -# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/stable/2021-11-01/examples/HybridConnection/RelayHybridConnectionAuthorizationRuleRegenerateKey.json +# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/Relay/stable/2017-04-01/examples/HybridConnection/RelayHybridConnectionAuthorizationRuleRegenrateKey.json if __name__ == "__main__": main() diff --git a/sdk/relay/azure-mgmt-relay/generated_samples/relay_hybrid_connection_authorization_rule_delete.py b/sdk/relay/azure-mgmt-relay/generated_samples/hybrid_connection/relay_hybrid_connection_autorization_rule_delete.py similarity index 84% rename from sdk/relay/azure-mgmt-relay/generated_samples/relay_hybrid_connection_authorization_rule_delete.py rename to sdk/relay/azure-mgmt-relay/generated_samples/hybrid_connection/relay_hybrid_connection_autorization_rule_delete.py index 02e4f466c276..4b21be8f4e5b 100644 --- a/sdk/relay/azure-mgmt-relay/generated_samples/relay_hybrid_connection_authorization_rule_delete.py +++ b/sdk/relay/azure-mgmt-relay/generated_samples/hybrid_connection/relay_hybrid_connection_autorization_rule_delete.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.relay import RelayAPI """ @@ -14,7 +16,7 @@ pip install azure-identity pip install azure-mgmt-relay # USAGE - python relay_hybrid_connection_authorization_rule_delete.py + python relay_hybrid_connection_autorization_rule_delete.py Before run the sample, please set the values of the client ID, tenant ID and client secret of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, @@ -29,15 +31,14 @@ def main(): subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", ) - response = client.hybrid_connections.delete_authorization_rule( + client.hybrid_connections.delete_authorization_rule( resource_group_name="resourcegroup", namespace_name="example-RelayNamespace-01", hybrid_connection_name="example-Relay-Hybrid-01", authorization_rule_name="example-RelayAuthRules-01", ) - print(response) -# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/stable/2021-11-01/examples/HybridConnection/RelayHybridConnectionAuthorizationRuleDelete.json +# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/Relay/stable/2017-04-01/examples/HybridConnection/RelayHybridConnectionAutorizationRuleDelete.json if __name__ == "__main__": main() diff --git a/sdk/relay/azure-mgmt-relay/generated_samples/relay_hybrid_connection_authorization_rule_get.py b/sdk/relay/azure-mgmt-relay/generated_samples/hybrid_connection/relay_hybrid_connection_autorization_rule_get.py similarity index 87% rename from sdk/relay/azure-mgmt-relay/generated_samples/relay_hybrid_connection_authorization_rule_get.py rename to sdk/relay/azure-mgmt-relay/generated_samples/hybrid_connection/relay_hybrid_connection_autorization_rule_get.py index 195344678da9..ed6cb8dc9fad 100644 --- a/sdk/relay/azure-mgmt-relay/generated_samples/relay_hybrid_connection_authorization_rule_get.py +++ b/sdk/relay/azure-mgmt-relay/generated_samples/hybrid_connection/relay_hybrid_connection_autorization_rule_get.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.relay import RelayAPI """ @@ -14,7 +16,7 @@ pip install azure-identity pip install azure-mgmt-relay # USAGE - python relay_hybrid_connection_authorization_rule_get.py + python relay_hybrid_connection_autorization_rule_get.py Before run the sample, please set the values of the client ID, tenant ID and client secret of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, @@ -38,6 +40,6 @@ def main(): print(response) -# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/stable/2021-11-01/examples/HybridConnection/RelayHybridConnectionAuthorizationRuleGet.json +# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/Relay/stable/2017-04-01/examples/HybridConnection/RelayHybridConnectionAutorizationRuleGet.json if __name__ == "__main__": main() diff --git a/sdk/relay/azure-mgmt-relay/generated_samples/relay_hybrid_connection_authorization_rule_list_all.py b/sdk/relay/azure-mgmt-relay/generated_samples/hybrid_connection/relay_hybrid_connection_autorization_rule_list_all.py similarity index 87% rename from sdk/relay/azure-mgmt-relay/generated_samples/relay_hybrid_connection_authorization_rule_list_all.py rename to sdk/relay/azure-mgmt-relay/generated_samples/hybrid_connection/relay_hybrid_connection_autorization_rule_list_all.py index cc270cc22504..361b832a922e 100644 --- a/sdk/relay/azure-mgmt-relay/generated_samples/relay_hybrid_connection_authorization_rule_list_all.py +++ b/sdk/relay/azure-mgmt-relay/generated_samples/hybrid_connection/relay_hybrid_connection_autorization_rule_list_all.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.relay import RelayAPI """ @@ -14,7 +16,7 @@ pip install azure-identity pip install azure-mgmt-relay # USAGE - python relay_hybrid_connection_authorization_rule_list_all.py + python relay_hybrid_connection_autorization_rule_list_all.py Before run the sample, please set the values of the client ID, tenant ID and client secret of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, @@ -38,6 +40,6 @@ def main(): print(item) -# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/stable/2021-11-01/examples/HybridConnection/RelayHybridConnectionAuthorizationRuleListAll.json +# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/Relay/stable/2017-04-01/examples/HybridConnection/RelayHybridConnectionAutorizationRuleListAll.json if __name__ == "__main__": main() diff --git a/sdk/relay/azure-mgmt-relay/generated_samples/relay_hybrid_connection_create.py b/sdk/relay/azure-mgmt-relay/generated_samples/hybrid_connection/relay_hybrid_connection_create.py similarity index 91% rename from sdk/relay/azure-mgmt-relay/generated_samples/relay_hybrid_connection_create.py rename to sdk/relay/azure-mgmt-relay/generated_samples/hybrid_connection/relay_hybrid_connection_create.py index 022783caa3f3..70151ebfc09e 100644 --- a/sdk/relay/azure-mgmt-relay/generated_samples/relay_hybrid_connection_create.py +++ b/sdk/relay/azure-mgmt-relay/generated_samples/hybrid_connection/relay_hybrid_connection_create.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.relay import RelayAPI """ @@ -38,6 +40,6 @@ def main(): print(response) -# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/stable/2021-11-01/examples/HybridConnection/RelayHybridConnectionCreate.json +# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/Relay/stable/2017-04-01/examples/HybridConnection/RelayHybridConnectionCreate.json if __name__ == "__main__": main() diff --git a/sdk/relay/azure-mgmt-relay/generated_samples/relay_hybrid_connection_get.py b/sdk/relay/azure-mgmt-relay/generated_samples/hybrid_connection/relay_hybrid_connection_get.py similarity index 91% rename from sdk/relay/azure-mgmt-relay/generated_samples/relay_hybrid_connection_get.py rename to sdk/relay/azure-mgmt-relay/generated_samples/hybrid_connection/relay_hybrid_connection_get.py index 40319ae05b70..a06258218fe4 100644 --- a/sdk/relay/azure-mgmt-relay/generated_samples/relay_hybrid_connection_get.py +++ b/sdk/relay/azure-mgmt-relay/generated_samples/hybrid_connection/relay_hybrid_connection_get.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.relay import RelayAPI """ @@ -37,6 +39,6 @@ def main(): print(response) -# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/stable/2021-11-01/examples/HybridConnection/RelayHybridConnectionGet.json +# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/Relay/stable/2017-04-01/examples/HybridConnection/RelayHybridConnectionGet.json if __name__ == "__main__": main() diff --git a/sdk/relay/azure-mgmt-relay/generated_samples/relay_hybrid_connection_list_all.py b/sdk/relay/azure-mgmt-relay/generated_samples/hybrid_connection/relay_hybrid_connection_list_all.py similarity index 91% rename from sdk/relay/azure-mgmt-relay/generated_samples/relay_hybrid_connection_list_all.py rename to sdk/relay/azure-mgmt-relay/generated_samples/hybrid_connection/relay_hybrid_connection_list_all.py index 9e285d3b9443..5b5dac04710a 100644 --- a/sdk/relay/azure-mgmt-relay/generated_samples/relay_hybrid_connection_list_all.py +++ b/sdk/relay/azure-mgmt-relay/generated_samples/hybrid_connection/relay_hybrid_connection_list_all.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.relay import RelayAPI """ @@ -37,6 +39,6 @@ def main(): print(item) -# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/stable/2021-11-01/examples/HybridConnection/RelayHybridConnectionListAll.json +# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/Relay/stable/2017-04-01/examples/HybridConnection/RelayHybridConnectionListAll.json if __name__ == "__main__": main() diff --git a/sdk/relay/azure-mgmt-relay/generated_samples/relay_hybridconnection_delete.py b/sdk/relay/azure-mgmt-relay/generated_samples/hybrid_connection/relay_hybridconnection_delete.py similarity index 88% rename from sdk/relay/azure-mgmt-relay/generated_samples/relay_hybridconnection_delete.py rename to sdk/relay/azure-mgmt-relay/generated_samples/hybrid_connection/relay_hybridconnection_delete.py index cfbe40c2b182..3534a1f02c81 100644 --- a/sdk/relay/azure-mgmt-relay/generated_samples/relay_hybridconnection_delete.py +++ b/sdk/relay/azure-mgmt-relay/generated_samples/hybrid_connection/relay_hybridconnection_delete.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.relay import RelayAPI """ @@ -29,14 +31,13 @@ def main(): subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", ) - response = client.hybrid_connections.delete( + client.hybrid_connections.delete( resource_group_name="resourcegroup", namespace_name="example-RelayNamespace-01", hybrid_connection_name="example-Relay-Hybrid-01", ) - print(response) -# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/stable/2021-11-01/examples/HybridConnection/RelayHybridconnectionDelete.json +# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/Relay/stable/2017-04-01/examples/HybridConnection/RelayHybridconnectionDelete.json if __name__ == "__main__": main() diff --git a/sdk/relay/azure-mgmt-relay/generated_samples/name_space_network_rule_set_create.py b/sdk/relay/azure-mgmt-relay/generated_samples/name_space_network_rule_set_create.py deleted file mode 100644 index cc170b4cb588..000000000000 --- a/sdk/relay/azure-mgmt-relay/generated_samples/name_space_network_rule_set_create.py +++ /dev/null @@ -1,53 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential -from azure.mgmt.relay import RelayAPI - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-relay -# USAGE - python name_space_network_rule_set_create.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = RelayAPI( - credential=DefaultAzureCredential(), - subscription_id="Subscription", - ) - - response = client.namespaces.create_or_update_network_rule_set( - resource_group_name="ResourceGroup", - namespace_name="example-RelayNamespace-6019", - parameters={ - "properties": { - "defaultAction": "Deny", - "ipRules": [ - {"action": "Allow", "ipMask": "1.1.1.1"}, - {"action": "Allow", "ipMask": "1.1.1.2"}, - {"action": "Allow", "ipMask": "1.1.1.3"}, - {"action": "Allow", "ipMask": "1.1.1.4"}, - {"action": "Allow", "ipMask": "1.1.1.5"}, - ], - } - }, - ) - print(response) - - -# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/stable/2021-11-01/examples/VirtualNetworkRules/RelayNetworkRuleSetCreate.json -if __name__ == "__main__": - main() diff --git a/sdk/relay/azure-mgmt-relay/generated_samples/name_space_network_rule_set_get.py b/sdk/relay/azure-mgmt-relay/generated_samples/name_space_network_rule_set_get.py deleted file mode 100644 index 9151244887b1..000000000000 --- a/sdk/relay/azure-mgmt-relay/generated_samples/name_space_network_rule_set_get.py +++ /dev/null @@ -1,41 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential -from azure.mgmt.relay import RelayAPI - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-relay -# USAGE - python name_space_network_rule_set_get.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = RelayAPI( - credential=DefaultAzureCredential(), - subscription_id="Subscription", - ) - - response = client.namespaces.get_network_rule_set( - resource_group_name="ResourceGroup", - namespace_name="example-RelayNamespace-6019", - ) - print(response) - - -# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/stable/2021-11-01/examples/VirtualNetworkRules/RelayNetworkRuleSetGet.json -if __name__ == "__main__": - main() diff --git a/sdk/relay/azure-mgmt-relay/generated_samples/name_space_private_end_point_connection_create.py b/sdk/relay/azure-mgmt-relay/generated_samples/name_space_private_end_point_connection_create.py deleted file mode 100644 index bb447c7ba7e3..000000000000 --- a/sdk/relay/azure-mgmt-relay/generated_samples/name_space_private_end_point_connection_create.py +++ /dev/null @@ -1,50 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential -from azure.mgmt.relay import RelayAPI - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-relay -# USAGE - python name_space_private_end_point_connection_create.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = RelayAPI( - credential=DefaultAzureCredential(), - subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", - ) - - response = client.private_endpoint_connections.create_or_update( - resource_group_name="resourcegroup", - namespace_name="example-RelayNamespace-5849", - private_endpoint_connection_name="{privateEndpointConnection name}", - parameters={ - "properties": { - "privateEndpoint": { - "id": "/subscriptions/ffffffff-ffff-ffff-ffff-ffffffffffff/resourceGroups/resourcegroup/providers/Microsoft.Network/privateEndpoints/ali-relay-pve-1" - }, - "privateLinkServiceConnectionState": {"description": "You may pass", "status": "Approved"}, - } - }, - ) - print(response) - - -# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/stable/2021-11-01/examples/PrivateEndpointConnections/PrivateEndpointConnectionsCreate.json -if __name__ == "__main__": - main() diff --git a/sdk/relay/azure-mgmt-relay/generated_samples/name_space_private_end_point_connection_delete.py b/sdk/relay/azure-mgmt-relay/generated_samples/name_space_private_end_point_connection_delete.py deleted file mode 100644 index 94d9d3726d2b..000000000000 --- a/sdk/relay/azure-mgmt-relay/generated_samples/name_space_private_end_point_connection_delete.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential -from azure.mgmt.relay import RelayAPI - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-relay -# USAGE - python name_space_private_end_point_connection_delete.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = RelayAPI( - credential=DefaultAzureCredential(), - subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", - ) - - response = client.private_endpoint_connections.begin_delete( - resource_group_name="myResourceGroup", - namespace_name="example-RelayNamespace-5849", - private_endpoint_connection_name="{privateEndpointConnection name}", - ).result() - print(response) - - -# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/stable/2021-11-01/examples/PrivateEndpointConnections/PrivateEndpointConnectionsDelete.json -if __name__ == "__main__": - main() diff --git a/sdk/relay/azure-mgmt-relay/generated_samples/name_space_private_end_point_connection_get.py b/sdk/relay/azure-mgmt-relay/generated_samples/name_space_private_end_point_connection_get.py deleted file mode 100644 index ea78c2c68db8..000000000000 --- a/sdk/relay/azure-mgmt-relay/generated_samples/name_space_private_end_point_connection_get.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential -from azure.mgmt.relay import RelayAPI - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-relay -# USAGE - python name_space_private_end_point_connection_get.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = RelayAPI( - credential=DefaultAzureCredential(), - subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", - ) - - response = client.private_endpoint_connections.get( - resource_group_name="myResourceGroup", - namespace_name="example-RelayNamespace-5849", - private_endpoint_connection_name="{privateEndpointConnection name}", - ) - print(response) - - -# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/stable/2021-11-01/examples/PrivateEndpointConnections/PrivateEndpointConnectionsGet.json -if __name__ == "__main__": - main() diff --git a/sdk/relay/azure-mgmt-relay/generated_samples/name_space_private_link_resources_get.py b/sdk/relay/azure-mgmt-relay/generated_samples/name_space_private_link_resources_get.py deleted file mode 100644 index 6339cd4aa77c..000000000000 --- a/sdk/relay/azure-mgmt-relay/generated_samples/name_space_private_link_resources_get.py +++ /dev/null @@ -1,41 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential -from azure.mgmt.relay import RelayAPI - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-relay -# USAGE - python name_space_private_link_resources_get.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = RelayAPI( - credential=DefaultAzureCredential(), - subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", - ) - - response = client.private_link_resources.list( - resource_group_name="resourcegroup", - namespace_name="example-RelayNamespace-5849", - ) - print(response) - - -# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/stable/2021-11-01/examples/PrivateEndpointConnections/PrivateLinkResourcesList.json -if __name__ == "__main__": - main() diff --git a/sdk/relay/azure-mgmt-relay/generated_samples/relay_name_space_authorization_rule_create.py b/sdk/relay/azure-mgmt-relay/generated_samples/name_spaces/relay_name_space_authorization_rule_create.py similarity index 91% rename from sdk/relay/azure-mgmt-relay/generated_samples/relay_name_space_authorization_rule_create.py rename to sdk/relay/azure-mgmt-relay/generated_samples/name_spaces/relay_name_space_authorization_rule_create.py index 94032c87dbfc..5ce222073b66 100644 --- a/sdk/relay/azure-mgmt-relay/generated_samples/relay_name_space_authorization_rule_create.py +++ b/sdk/relay/azure-mgmt-relay/generated_samples/name_spaces/relay_name_space_authorization_rule_create.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.relay import RelayAPI """ @@ -38,6 +40,6 @@ def main(): print(response) -# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/stable/2021-11-01/examples/NameSpaces/RelayNameSpaceAuthorizationRuleCreate.json +# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/Relay/stable/2017-04-01/examples/NameSpaces/RelayNameSpaceAuthorizationRuleCreate.json if __name__ == "__main__": main() diff --git a/sdk/relay/azure-mgmt-relay/generated_samples/relay_name_space_authorization_rule_list_key.py b/sdk/relay/azure-mgmt-relay/generated_samples/name_spaces/relay_name_space_authorization_rule_list_key.py similarity index 91% rename from sdk/relay/azure-mgmt-relay/generated_samples/relay_name_space_authorization_rule_list_key.py rename to sdk/relay/azure-mgmt-relay/generated_samples/name_spaces/relay_name_space_authorization_rule_list_key.py index 847169b0d5e6..f434c0e89d16 100644 --- a/sdk/relay/azure-mgmt-relay/generated_samples/relay_name_space_authorization_rule_list_key.py +++ b/sdk/relay/azure-mgmt-relay/generated_samples/name_spaces/relay_name_space_authorization_rule_list_key.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.relay import RelayAPI """ @@ -37,6 +39,6 @@ def main(): print(response) -# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/stable/2021-11-01/examples/NameSpaces/RelayNameSpaceAuthorizationRuleListKey.json +# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/Relay/stable/2017-04-01/examples/NameSpaces/RelayNameSpaceAuthorizationRuleListKey.json if __name__ == "__main__": main() diff --git a/sdk/relay/azure-mgmt-relay/generated_samples/relay_name_space_authorization_rule_regenerate_key.py b/sdk/relay/azure-mgmt-relay/generated_samples/name_spaces/relay_name_space_authorization_rule_regenrate_key.py similarity index 87% rename from sdk/relay/azure-mgmt-relay/generated_samples/relay_name_space_authorization_rule_regenerate_key.py rename to sdk/relay/azure-mgmt-relay/generated_samples/name_spaces/relay_name_space_authorization_rule_regenrate_key.py index b0c32288d2aa..aead49513fba 100644 --- a/sdk/relay/azure-mgmt-relay/generated_samples/relay_name_space_authorization_rule_regenerate_key.py +++ b/sdk/relay/azure-mgmt-relay/generated_samples/name_spaces/relay_name_space_authorization_rule_regenrate_key.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.relay import RelayAPI """ @@ -14,7 +16,7 @@ pip install azure-identity pip install azure-mgmt-relay # USAGE - python relay_name_space_authorization_rule_regenerate_key.py + python relay_name_space_authorization_rule_regenrate_key.py Before run the sample, please set the values of the client ID, tenant ID and client secret of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, @@ -38,6 +40,6 @@ def main(): print(response) -# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/stable/2021-11-01/examples/NameSpaces/RelayNameSpaceAuthorizationRuleRegenerateKey.json +# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/Relay/stable/2017-04-01/examples/NameSpaces/RelayNameSpaceAuthorizationRuleRegenrateKey.json if __name__ == "__main__": main() diff --git a/sdk/relay/azure-mgmt-relay/generated_samples/relay_name_space_authorization_rule_delete.py b/sdk/relay/azure-mgmt-relay/generated_samples/name_spaces/relay_name_space_autorization_rule_delete.py similarity index 84% rename from sdk/relay/azure-mgmt-relay/generated_samples/relay_name_space_authorization_rule_delete.py rename to sdk/relay/azure-mgmt-relay/generated_samples/name_spaces/relay_name_space_autorization_rule_delete.py index 1c22b39d19da..98a652d309e7 100644 --- a/sdk/relay/azure-mgmt-relay/generated_samples/relay_name_space_authorization_rule_delete.py +++ b/sdk/relay/azure-mgmt-relay/generated_samples/name_spaces/relay_name_space_autorization_rule_delete.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.relay import RelayAPI """ @@ -14,7 +16,7 @@ pip install azure-identity pip install azure-mgmt-relay # USAGE - python relay_name_space_authorization_rule_delete.py + python relay_name_space_autorization_rule_delete.py Before run the sample, please set the values of the client ID, tenant ID and client secret of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, @@ -29,14 +31,13 @@ def main(): subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", ) - response = client.namespaces.delete_authorization_rule( + client.namespaces.delete_authorization_rule( resource_group_name="resourcegroup", namespace_name="example-RelayNamespace-01", authorization_rule_name="example-RelayAuthRules-01", ) - print(response) -# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/stable/2021-11-01/examples/NameSpaces/RelayNameSpaceAuthorizationRuleDelete.json +# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/Relay/stable/2017-04-01/examples/NameSpaces/RelayNameSpaceAutorizationRuleDelete.json if __name__ == "__main__": main() diff --git a/sdk/relay/azure-mgmt-relay/generated_samples/relay_name_space_authorization_rule_get.py b/sdk/relay/azure-mgmt-relay/generated_samples/name_spaces/relay_name_space_autorization_rule_get.py similarity index 88% rename from sdk/relay/azure-mgmt-relay/generated_samples/relay_name_space_authorization_rule_get.py rename to sdk/relay/azure-mgmt-relay/generated_samples/name_spaces/relay_name_space_autorization_rule_get.py index cf8060e11861..844e28619cdb 100644 --- a/sdk/relay/azure-mgmt-relay/generated_samples/relay_name_space_authorization_rule_get.py +++ b/sdk/relay/azure-mgmt-relay/generated_samples/name_spaces/relay_name_space_autorization_rule_get.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.relay import RelayAPI """ @@ -14,7 +16,7 @@ pip install azure-identity pip install azure-mgmt-relay # USAGE - python relay_name_space_authorization_rule_get.py + python relay_name_space_autorization_rule_get.py Before run the sample, please set the values of the client ID, tenant ID and client secret of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, @@ -37,6 +39,6 @@ def main(): print(response) -# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/stable/2021-11-01/examples/NameSpaces/RelayNameSpaceAuthorizationRuleGet.json +# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/Relay/stable/2017-04-01/examples/NameSpaces/RelayNameSpaceAutorizationRuleGet.json if __name__ == "__main__": main() diff --git a/sdk/relay/azure-mgmt-relay/generated_samples/relay_name_space_authorization_rule_list_all.py b/sdk/relay/azure-mgmt-relay/generated_samples/name_spaces/relay_name_space_autorization_rule_list_all.py similarity index 87% rename from sdk/relay/azure-mgmt-relay/generated_samples/relay_name_space_authorization_rule_list_all.py rename to sdk/relay/azure-mgmt-relay/generated_samples/name_spaces/relay_name_space_autorization_rule_list_all.py index e3797aaae681..da29b415cdd7 100644 --- a/sdk/relay/azure-mgmt-relay/generated_samples/relay_name_space_authorization_rule_list_all.py +++ b/sdk/relay/azure-mgmt-relay/generated_samples/name_spaces/relay_name_space_autorization_rule_list_all.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.relay import RelayAPI """ @@ -14,7 +16,7 @@ pip install azure-identity pip install azure-mgmt-relay # USAGE - python relay_name_space_authorization_rule_list_all.py + python relay_name_space_autorization_rule_list_all.py Before run the sample, please set the values of the client ID, tenant ID and client secret of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, @@ -37,6 +39,6 @@ def main(): print(item) -# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/stable/2021-11-01/examples/NameSpaces/RelayNameSpaceAuthorizationRuleListAll.json +# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/Relay/stable/2017-04-01/examples/NameSpaces/RelayNameSpaceAutorizationRuleListAll.json if __name__ == "__main__": main() diff --git a/sdk/relay/azure-mgmt-relay/generated_samples/relay_check_name_availability.py b/sdk/relay/azure-mgmt-relay/generated_samples/name_spaces/relay_name_space_check_name_availability.py similarity index 84% rename from sdk/relay/azure-mgmt-relay/generated_samples/relay_check_name_availability.py rename to sdk/relay/azure-mgmt-relay/generated_samples/name_spaces/relay_name_space_check_name_availability.py index 90083423dd53..94b83c03e923 100644 --- a/sdk/relay/azure-mgmt-relay/generated_samples/relay_check_name_availability.py +++ b/sdk/relay/azure-mgmt-relay/generated_samples/name_spaces/relay_name_space_check_name_availability.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.relay import RelayAPI """ @@ -14,7 +16,7 @@ pip install azure-identity pip install azure-mgmt-relay # USAGE - python relay_check_name_availability.py + python relay_name_space_check_name_availability.py Before run the sample, please set the values of the client ID, tenant ID and client secret of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, @@ -30,11 +32,11 @@ def main(): ) response = client.namespaces.check_name_availability( - parameters={"name": "example-RelayNamespace1321"}, + parameters={"name": "sdk-Namespace1321"}, ) print(response) -# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/stable/2021-11-01/examples/NameSpaces/RelayNameSpaceCheckNameAvailability.json +# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/Relay/stable/2017-04-01/examples/NameSpaces/RelayNameSpaceCheckNameAvailability.json if __name__ == "__main__": main() diff --git a/sdk/relay/azure-mgmt-relay/generated_samples/relay_namespace_create.py b/sdk/relay/azure-mgmt-relay/generated_samples/name_spaces/relay_name_space_create.py similarity index 85% rename from sdk/relay/azure-mgmt-relay/generated_samples/relay_namespace_create.py rename to sdk/relay/azure-mgmt-relay/generated_samples/name_spaces/relay_name_space_create.py index 85d8bc0eeff3..1965b5dab6a3 100644 --- a/sdk/relay/azure-mgmt-relay/generated_samples/relay_namespace_create.py +++ b/sdk/relay/azure-mgmt-relay/generated_samples/name_spaces/relay_name_space_create.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.relay import RelayAPI """ @@ -14,7 +16,7 @@ pip install azure-identity pip install azure-mgmt-relay # USAGE - python relay_namespace_create.py + python relay_name_space_create.py Before run the sample, please set the values of the client ID, tenant ID and client secret of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, @@ -31,9 +33,9 @@ def main(): response = client.namespaces.begin_create_or_update( resource_group_name="resourcegroup", - namespace_name="example-RelayNamespace-5849", + namespace_name="example-RelayNamespace-01", parameters={ - "location": "South Central US", + "location": "West US", "sku": {"name": "Standard", "tier": "Standard"}, "tags": {"tag1": "value1", "tag2": "value2"}, }, @@ -41,6 +43,6 @@ def main(): print(response) -# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/stable/2021-11-01/examples/NameSpaces/RelayNameSpaceCreate.json +# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/Relay/stable/2017-04-01/examples/NameSpaces/RelayNameSpaceCreate.json if __name__ == "__main__": main() diff --git a/sdk/relay/azure-mgmt-relay/generated_samples/relay_name_space_delete.py b/sdk/relay/azure-mgmt-relay/generated_samples/name_spaces/relay_name_space_delete.py similarity index 83% rename from sdk/relay/azure-mgmt-relay/generated_samples/relay_name_space_delete.py rename to sdk/relay/azure-mgmt-relay/generated_samples/name_spaces/relay_name_space_delete.py index b482aad2f505..c38de2875de9 100644 --- a/sdk/relay/azure-mgmt-relay/generated_samples/relay_name_space_delete.py +++ b/sdk/relay/azure-mgmt-relay/generated_samples/name_spaces/relay_name_space_delete.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.relay import RelayAPI """ @@ -29,13 +31,12 @@ def main(): subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", ) - response = client.namespaces.begin_delete( - resource_group_name="SouthCentralUS", - namespace_name="example-RelayNamespace-5849", + client.namespaces.begin_delete( + resource_group_name="resourcegroup", + namespace_name="example-RelayNamespace-01", ).result() - print(response) -# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/stable/2021-11-01/examples/NameSpaces/RelayNameSpaceDelete.json +# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/Relay/stable/2017-04-01/examples/NameSpaces/RelayNameSpaceDelete.json if __name__ == "__main__": main() diff --git a/sdk/relay/azure-mgmt-relay/generated_samples/relay_name_space_get.py b/sdk/relay/azure-mgmt-relay/generated_samples/name_spaces/relay_name_space_get.py similarity index 85% rename from sdk/relay/azure-mgmt-relay/generated_samples/relay_name_space_get.py rename to sdk/relay/azure-mgmt-relay/generated_samples/name_spaces/relay_name_space_get.py index 9e5f9e79b78e..5a2cbbb0527e 100644 --- a/sdk/relay/azure-mgmt-relay/generated_samples/relay_name_space_get.py +++ b/sdk/relay/azure-mgmt-relay/generated_samples/name_spaces/relay_name_space_get.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.relay import RelayAPI """ @@ -30,12 +32,12 @@ def main(): ) response = client.namespaces.get( - resource_group_name="RG-eg", - namespace_name="example-RelayRelayNamespace-01", + resource_group_name="resourcegroup", + namespace_name="example-RelayNamespace-01", ) print(response) -# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/stable/2021-11-01/examples/NameSpaces/RelayNameSpaceGet.json +# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/Relay/stable/2017-04-01/examples/NameSpaces/RelayNameSpaceGet.json if __name__ == "__main__": main() diff --git a/sdk/relay/azure-mgmt-relay/generated_samples/relay_name_space_list_by_resource_group.py b/sdk/relay/azure-mgmt-relay/generated_samples/name_spaces/relay_name_space_list_by_resource_group.py similarity index 90% rename from sdk/relay/azure-mgmt-relay/generated_samples/relay_name_space_list_by_resource_group.py rename to sdk/relay/azure-mgmt-relay/generated_samples/name_spaces/relay_name_space_list_by_resource_group.py index dd41cdc0eb27..85f25be2cfa5 100644 --- a/sdk/relay/azure-mgmt-relay/generated_samples/relay_name_space_list_by_resource_group.py +++ b/sdk/relay/azure-mgmt-relay/generated_samples/name_spaces/relay_name_space_list_by_resource_group.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.relay import RelayAPI """ @@ -36,6 +38,6 @@ def main(): print(item) -# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/stable/2021-11-01/examples/NameSpaces/RelayNameSpaceListByResourceGroup.json +# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/Relay/stable/2017-04-01/examples/NameSpaces/RelayNameSpaceListByResourceGroup.json if __name__ == "__main__": main() diff --git a/sdk/relay/azure-mgmt-relay/generated_samples/relay_name_space_list_by_subscription.py b/sdk/relay/azure-mgmt-relay/generated_samples/name_spaces/relay_name_space_list_by_subscription.py similarity index 90% rename from sdk/relay/azure-mgmt-relay/generated_samples/relay_name_space_list_by_subscription.py rename to sdk/relay/azure-mgmt-relay/generated_samples/name_spaces/relay_name_space_list_by_subscription.py index 9032c17f939e..b55ed0c6ddd6 100644 --- a/sdk/relay/azure-mgmt-relay/generated_samples/relay_name_space_list_by_subscription.py +++ b/sdk/relay/azure-mgmt-relay/generated_samples/name_spaces/relay_name_space_list_by_subscription.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.relay import RelayAPI """ @@ -34,6 +36,6 @@ def main(): print(item) -# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/stable/2021-11-01/examples/NameSpaces/RelayNameSpaceListBySubscription.json +# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/Relay/stable/2017-04-01/examples/NameSpaces/RelayNameSpaceListBySubscription.json if __name__ == "__main__": main() diff --git a/sdk/relay/azure-mgmt-relay/generated_samples/relay_name_space_update.py b/sdk/relay/azure-mgmt-relay/generated_samples/name_spaces/relay_name_space_update.py similarity index 86% rename from sdk/relay/azure-mgmt-relay/generated_samples/relay_name_space_update.py rename to sdk/relay/azure-mgmt-relay/generated_samples/name_spaces/relay_name_space_update.py index 75f4905e1a08..43866e3e7b36 100644 --- a/sdk/relay/azure-mgmt-relay/generated_samples/relay_name_space_update.py +++ b/sdk/relay/azure-mgmt-relay/generated_samples/name_spaces/relay_name_space_update.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.relay import RelayAPI """ @@ -30,13 +32,13 @@ def main(): ) response = client.namespaces.update( - resource_group_name="RG-eg", - namespace_name="example-RelayRelayNamespace-01", + resource_group_name="resourcegroup", + namespace_name="example-RelayNamespace-01", parameters={"tags": {"tag3": "value3", "tag4": "value4", "tag5": "value5", "tag6": "value6"}}, ) print(response) -# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/stable/2021-11-01/examples/NameSpaces/RelayNameSpaceUpdate.json +# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/Relay/stable/2017-04-01/examples/NameSpaces/RelayNameSpaceUpdate.json if __name__ == "__main__": main() diff --git a/sdk/relay/azure-mgmt-relay/generated_samples/private_endpoint_connections_list.py b/sdk/relay/azure-mgmt-relay/generated_samples/private_endpoint_connections_list.py deleted file mode 100644 index 03ece2a0e507..000000000000 --- a/sdk/relay/azure-mgmt-relay/generated_samples/private_endpoint_connections_list.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.identity import DefaultAzureCredential -from azure.mgmt.relay import RelayAPI - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-mgmt-relay -# USAGE - python private_endpoint_connections_list.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = RelayAPI( - credential=DefaultAzureCredential(), - subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", - ) - - response = client.private_endpoint_connections.list( - resource_group_name="myResourceGroup", - namespace_name="example-RelayNamespace-5849", - ) - for item in response: - print(item) - - -# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/stable/2021-11-01/examples/PrivateEndpointConnections/PrivateEndpointConnectionsList.json -if __name__ == "__main__": - main() diff --git a/sdk/relay/azure-mgmt-relay/generated_samples/relay_authorization_rule_create.py b/sdk/relay/azure-mgmt-relay/generated_samples/relay/relay_authorization_rule_create.py similarity index 92% rename from sdk/relay/azure-mgmt-relay/generated_samples/relay_authorization_rule_create.py rename to sdk/relay/azure-mgmt-relay/generated_samples/relay/relay_authorization_rule_create.py index f44335f252df..36123daf1178 100644 --- a/sdk/relay/azure-mgmt-relay/generated_samples/relay_authorization_rule_create.py +++ b/sdk/relay/azure-mgmt-relay/generated_samples/relay/relay_authorization_rule_create.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.relay import RelayAPI """ @@ -39,6 +41,6 @@ def main(): print(response) -# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/stable/2021-11-01/examples/Relay/RelayAuthorizationRuleCreate.json +# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/Relay/stable/2017-04-01/examples/Relay/RelayAuthorizationRuleCreate.json if __name__ == "__main__": main() diff --git a/sdk/relay/azure-mgmt-relay/generated_samples/relay_authorization_rule_list_key.json.py b/sdk/relay/azure-mgmt-relay/generated_samples/relay/relay_authorization_rule_list_key.py similarity index 89% rename from sdk/relay/azure-mgmt-relay/generated_samples/relay_authorization_rule_list_key.json.py rename to sdk/relay/azure-mgmt-relay/generated_samples/relay/relay_authorization_rule_list_key.py index f5c3273506e9..83b5e35b445f 100644 --- a/sdk/relay/azure-mgmt-relay/generated_samples/relay_authorization_rule_list_key.json.py +++ b/sdk/relay/azure-mgmt-relay/generated_samples/relay/relay_authorization_rule_list_key.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.relay import RelayAPI """ @@ -14,7 +16,7 @@ pip install azure-identity pip install azure-mgmt-relay # USAGE - python relay_authorization_rule_list_key.json.py + python relay_authorization_rule_list_key.py Before run the sample, please set the values of the client ID, tenant ID and client secret of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, @@ -38,6 +40,6 @@ def main(): print(response) -# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/stable/2021-11-01/examples/Relay/RelayAuthorizationRuleListKey.json +# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/Relay/stable/2017-04-01/examples/Relay/RelayAuthorizationRuleListKey.json if __name__ == "__main__": main() diff --git a/sdk/relay/azure-mgmt-relay/generated_samples/relay_authorization_rule_regenerate_key.json.py b/sdk/relay/azure-mgmt-relay/generated_samples/relay/relay_authorization_rule_regenrate_key.py similarity index 89% rename from sdk/relay/azure-mgmt-relay/generated_samples/relay_authorization_rule_regenerate_key.json.py rename to sdk/relay/azure-mgmt-relay/generated_samples/relay/relay_authorization_rule_regenrate_key.py index 190138f64934..e3faa32a1163 100644 --- a/sdk/relay/azure-mgmt-relay/generated_samples/relay_authorization_rule_regenerate_key.json.py +++ b/sdk/relay/azure-mgmt-relay/generated_samples/relay/relay_authorization_rule_regenrate_key.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.relay import RelayAPI """ @@ -14,7 +16,7 @@ pip install azure-identity pip install azure-mgmt-relay # USAGE - python relay_authorization_rule_regenerate_key.json.py + python relay_authorization_rule_regenrate_key.py Before run the sample, please set the values of the client ID, tenant ID and client secret of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, @@ -39,6 +41,6 @@ def main(): print(response) -# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/stable/2021-11-01/examples/Relay/RelayAuthorizationRuleRegenerateKey.json +# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/Relay/stable/2017-04-01/examples/Relay/RelayAuthorizationRuleRegenrateKey.json if __name__ == "__main__": main() diff --git a/sdk/relay/azure-mgmt-relay/generated_samples/relay_authorization_rule_delete.py b/sdk/relay/azure-mgmt-relay/generated_samples/relay/relay_autorization_rule_delete.py similarity index 86% rename from sdk/relay/azure-mgmt-relay/generated_samples/relay_authorization_rule_delete.py rename to sdk/relay/azure-mgmt-relay/generated_samples/relay/relay_autorization_rule_delete.py index e72c2c60355e..7bbf61ed84d5 100644 --- a/sdk/relay/azure-mgmt-relay/generated_samples/relay_authorization_rule_delete.py +++ b/sdk/relay/azure-mgmt-relay/generated_samples/relay/relay_autorization_rule_delete.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.relay import RelayAPI """ @@ -14,7 +16,7 @@ pip install azure-identity pip install azure-mgmt-relay # USAGE - python relay_authorization_rule_delete.py + python relay_autorization_rule_delete.py Before run the sample, please set the values of the client ID, tenant ID and client secret of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, @@ -29,15 +31,14 @@ def main(): subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", ) - response = client.wcf_relays.delete_authorization_rule( + client.wcf_relays.delete_authorization_rule( resource_group_name="resourcegroup", namespace_name="example-RelayNamespace-01", relay_name="example-Relay-wcf-01", authorization_rule_name="example-RelayAuthRules-01", ) - print(response) -# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/stable/2021-11-01/examples/Relay/RelayAuthorizationRuleDelete.json +# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/Relay/stable/2017-04-01/examples/Relay/RelayAutorizationRuleDelete.json if __name__ == "__main__": main() diff --git a/sdk/relay/azure-mgmt-relay/generated_samples/relay_authorization_rule_get.py b/sdk/relay/azure-mgmt-relay/generated_samples/relay/relay_autorization_rule_get.py similarity index 89% rename from sdk/relay/azure-mgmt-relay/generated_samples/relay_authorization_rule_get.py rename to sdk/relay/azure-mgmt-relay/generated_samples/relay/relay_autorization_rule_get.py index 386bd833fd6e..92a969488ce3 100644 --- a/sdk/relay/azure-mgmt-relay/generated_samples/relay_authorization_rule_get.py +++ b/sdk/relay/azure-mgmt-relay/generated_samples/relay/relay_autorization_rule_get.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.relay import RelayAPI """ @@ -14,7 +16,7 @@ pip install azure-identity pip install azure-mgmt-relay # USAGE - python relay_authorization_rule_get.py + python relay_autorization_rule_get.py Before run the sample, please set the values of the client ID, tenant ID and client secret of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, @@ -38,6 +40,6 @@ def main(): print(response) -# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/stable/2021-11-01/examples/Relay/RelayAuthorizationRuleGet.json +# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/Relay/stable/2017-04-01/examples/Relay/RelayAutorizationRuleGet.json if __name__ == "__main__": main() diff --git a/sdk/relay/azure-mgmt-relay/generated_samples/relay_authorization_rule_list_all.py b/sdk/relay/azure-mgmt-relay/generated_samples/relay/relay_autorization_rule_list_all.py similarity index 89% rename from sdk/relay/azure-mgmt-relay/generated_samples/relay_authorization_rule_list_all.py rename to sdk/relay/azure-mgmt-relay/generated_samples/relay/relay_autorization_rule_list_all.py index 35cf182fbfad..bd5ea8292b9b 100644 --- a/sdk/relay/azure-mgmt-relay/generated_samples/relay_authorization_rule_list_all.py +++ b/sdk/relay/azure-mgmt-relay/generated_samples/relay/relay_autorization_rule_list_all.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.relay import RelayAPI """ @@ -14,7 +16,7 @@ pip install azure-identity pip install azure-mgmt-relay # USAGE - python relay_authorization_rule_list_all.py + python relay_autorization_rule_list_all.py Before run the sample, please set the values of the client ID, tenant ID and client secret of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, @@ -38,6 +40,6 @@ def main(): print(item) -# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/stable/2021-11-01/examples/Relay/RelayAuthorizationRuleListAll.json +# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/Relay/stable/2017-04-01/examples/Relay/RelayAutorizationRuleListAll.json if __name__ == "__main__": main() diff --git a/sdk/relay/azure-mgmt-relay/generated_samples/relay_create.py b/sdk/relay/azure-mgmt-relay/generated_samples/relay/relay_create.py similarity index 93% rename from sdk/relay/azure-mgmt-relay/generated_samples/relay_create.py rename to sdk/relay/azure-mgmt-relay/generated_samples/relay/relay_create.py index 76d91ec44acb..015d40957577 100644 --- a/sdk/relay/azure-mgmt-relay/generated_samples/relay_create.py +++ b/sdk/relay/azure-mgmt-relay/generated_samples/relay/relay_create.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.relay import RelayAPI """ @@ -44,6 +46,6 @@ def main(): print(response) -# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/stable/2021-11-01/examples/Relay/RelayCreate.json +# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/Relay/stable/2017-04-01/examples/Relay/RelayCreate.json if __name__ == "__main__": main() diff --git a/sdk/relay/azure-mgmt-relay/generated_samples/relay_delete.py b/sdk/relay/azure-mgmt-relay/generated_samples/relay/relay_delete.py similarity index 90% rename from sdk/relay/azure-mgmt-relay/generated_samples/relay_delete.py rename to sdk/relay/azure-mgmt-relay/generated_samples/relay/relay_delete.py index 2c7d854ce72d..81fc5e3b3fb3 100644 --- a/sdk/relay/azure-mgmt-relay/generated_samples/relay_delete.py +++ b/sdk/relay/azure-mgmt-relay/generated_samples/relay/relay_delete.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.relay import RelayAPI """ @@ -29,14 +31,13 @@ def main(): subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", ) - response = client.wcf_relays.delete( + client.wcf_relays.delete( resource_group_name="resourcegroup", namespace_name="example-RelayNamespace-01", relay_name="example-Relay-wcf-01", ) - print(response) -# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/stable/2021-11-01/examples/Relay/RelayDelete.json +# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/Relay/stable/2017-04-01/examples/Relay/RelayDelete.json if __name__ == "__main__": main() diff --git a/sdk/relay/azure-mgmt-relay/generated_samples/relay_get.py b/sdk/relay/azure-mgmt-relay/generated_samples/relay/relay_get.py similarity index 92% rename from sdk/relay/azure-mgmt-relay/generated_samples/relay_get.py rename to sdk/relay/azure-mgmt-relay/generated_samples/relay/relay_get.py index 398124e1de7b..d5caee3f1b41 100644 --- a/sdk/relay/azure-mgmt-relay/generated_samples/relay_get.py +++ b/sdk/relay/azure-mgmt-relay/generated_samples/relay/relay_get.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.relay import RelayAPI """ @@ -37,6 +39,6 @@ def main(): print(response) -# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/stable/2021-11-01/examples/Relay/RelayGet.json +# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/Relay/stable/2017-04-01/examples/Relay/RelayGet.json if __name__ == "__main__": main() diff --git a/sdk/relay/azure-mgmt-relay/generated_samples/relay_list_all.py b/sdk/relay/azure-mgmt-relay/generated_samples/relay/relay_list_all.py similarity index 92% rename from sdk/relay/azure-mgmt-relay/generated_samples/relay_list_all.py rename to sdk/relay/azure-mgmt-relay/generated_samples/relay/relay_list_all.py index 3a079bba9865..80f46ee094ef 100644 --- a/sdk/relay/azure-mgmt-relay/generated_samples/relay_list_all.py +++ b/sdk/relay/azure-mgmt-relay/generated_samples/relay/relay_list_all.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.relay import RelayAPI """ @@ -37,6 +39,6 @@ def main(): print(item) -# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/stable/2021-11-01/examples/Relay/RelayListAll.json +# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/Relay/stable/2017-04-01/examples/Relay/RelayListAll.json if __name__ == "__main__": main() diff --git a/sdk/relay/azure-mgmt-relay/generated_samples/relay_operations_list.py b/sdk/relay/azure-mgmt-relay/generated_samples/relay_operations_list.py index 1c2bb9d2fe02..cbe1463c1233 100644 --- a/sdk/relay/azure-mgmt-relay/generated_samples/relay_operations_list.py +++ b/sdk/relay/azure-mgmt-relay/generated_samples/relay_operations_list.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.relay import RelayAPI """ @@ -34,6 +36,6 @@ def main(): print(item) -# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/stable/2021-11-01/examples/RelayOperations_List.json +# x-ms-original-file: specification/relay/resource-manager/Microsoft.Relay/Relay/stable/2017-04-01/examples/RelayOperations_List.json if __name__ == "__main__": main() diff --git a/sdk/relay/azure-mgmt-relay/generated_tests/conftest.py b/sdk/relay/azure-mgmt-relay/generated_tests/conftest.py new file mode 100644 index 000000000000..4b28a5917465 --- /dev/null +++ b/sdk/relay/azure-mgmt-relay/generated_tests/conftest.py @@ -0,0 +1,35 @@ +# 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 os +import pytest +from dotenv import load_dotenv +from devtools_testutils import ( + test_proxy, + add_general_regex_sanitizer, + add_body_key_sanitizer, + add_header_regex_sanitizer, +) + +load_dotenv() + + +# For security, please avoid record sensitive identity information in recordings +@pytest.fixture(scope="session", autouse=True) +def add_sanitizers(test_proxy): + relayapi_subscription_id = os.environ.get("AZURE_SUBSCRIPTION_ID", "00000000-0000-0000-0000-000000000000") + relayapi_tenant_id = os.environ.get("AZURE_TENANT_ID", "00000000-0000-0000-0000-000000000000") + relayapi_client_id = os.environ.get("AZURE_CLIENT_ID", "00000000-0000-0000-0000-000000000000") + relayapi_client_secret = os.environ.get("AZURE_CLIENT_SECRET", "00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=relayapi_subscription_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=relayapi_tenant_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=relayapi_client_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=relayapi_client_secret, value="00000000-0000-0000-0000-000000000000") + + add_header_regex_sanitizer(key="Set-Cookie", value="[set-cookie;]") + add_header_regex_sanitizer(key="Cookie", value="cookie;") + add_body_key_sanitizer(json_path="$..access_token", value="access_token") diff --git a/sdk/relay/azure-mgmt-relay/generated_tests/test_relay_api_hybrid_connections_operations.py b/sdk/relay/azure-mgmt-relay/generated_tests/test_relay_api_hybrid_connections_operations.py new file mode 100644 index 000000000000..b8317a790bb1 --- /dev/null +++ b/sdk/relay/azure-mgmt-relay/generated_tests/test_relay_api_hybrid_connections_operations.py @@ -0,0 +1,165 @@ +# 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 pytest +from azure.mgmt.relay import RelayAPI + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestRelayAPIHybridConnectionsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(RelayAPI) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_hybrid_connections_list_by_namespace(self, resource_group): + response = self.client.hybrid_connections.list_by_namespace( + resource_group_name=resource_group.name, + namespace_name="str", + api_version="2017-04-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_hybrid_connections_create_or_update(self, resource_group): + response = self.client.hybrid_connections.create_or_update( + resource_group_name=resource_group.name, + namespace_name="str", + hybrid_connection_name="str", + parameters={ + "createdAt": "2020-02-20 00:00:00", + "id": "str", + "listenerCount": 0, + "name": "str", + "requiresClientAuthorization": bool, + "type": "str", + "updatedAt": "2020-02-20 00:00:00", + "userMetadata": "str", + }, + api_version="2017-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_hybrid_connections_delete(self, resource_group): + response = self.client.hybrid_connections.delete( + resource_group_name=resource_group.name, + namespace_name="str", + hybrid_connection_name="str", + api_version="2017-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_hybrid_connections_get(self, resource_group): + response = self.client.hybrid_connections.get( + resource_group_name=resource_group.name, + namespace_name="str", + hybrid_connection_name="str", + api_version="2017-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_hybrid_connections_list_authorization_rules(self, resource_group): + response = self.client.hybrid_connections.list_authorization_rules( + resource_group_name=resource_group.name, + namespace_name="str", + hybrid_connection_name="str", + api_version="2017-04-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_hybrid_connections_create_or_update_authorization_rule(self, resource_group): + response = self.client.hybrid_connections.create_or_update_authorization_rule( + resource_group_name=resource_group.name, + namespace_name="str", + hybrid_connection_name="str", + authorization_rule_name="str", + parameters={"rights": ["str"], "id": "str", "name": "str", "type": "str"}, + api_version="2017-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_hybrid_connections_delete_authorization_rule(self, resource_group): + response = self.client.hybrid_connections.delete_authorization_rule( + resource_group_name=resource_group.name, + namespace_name="str", + hybrid_connection_name="str", + authorization_rule_name="str", + api_version="2017-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_hybrid_connections_get_authorization_rule(self, resource_group): + response = self.client.hybrid_connections.get_authorization_rule( + resource_group_name=resource_group.name, + namespace_name="str", + hybrid_connection_name="str", + authorization_rule_name="str", + api_version="2017-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_hybrid_connections_list_keys(self, resource_group): + response = self.client.hybrid_connections.list_keys( + resource_group_name=resource_group.name, + namespace_name="str", + hybrid_connection_name="str", + authorization_rule_name="str", + api_version="2017-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_hybrid_connections_regenerate_keys(self, resource_group): + response = self.client.hybrid_connections.regenerate_keys( + resource_group_name=resource_group.name, + namespace_name="str", + hybrid_connection_name="str", + authorization_rule_name="str", + parameters={"keyType": "str", "key": "str"}, + api_version="2017-04-01", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/relay/azure-mgmt-relay/generated_tests/test_relay_api_hybrid_connections_operations_async.py b/sdk/relay/azure-mgmt-relay/generated_tests/test_relay_api_hybrid_connections_operations_async.py new file mode 100644 index 000000000000..9b2f2521fba4 --- /dev/null +++ b/sdk/relay/azure-mgmt-relay/generated_tests/test_relay_api_hybrid_connections_operations_async.py @@ -0,0 +1,166 @@ +# 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 pytest +from azure.mgmt.relay.aio import RelayAPI + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestRelayAPIHybridConnectionsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(RelayAPI, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_hybrid_connections_list_by_namespace(self, resource_group): + response = self.client.hybrid_connections.list_by_namespace( + resource_group_name=resource_group.name, + namespace_name="str", + api_version="2017-04-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_hybrid_connections_create_or_update(self, resource_group): + response = await self.client.hybrid_connections.create_or_update( + resource_group_name=resource_group.name, + namespace_name="str", + hybrid_connection_name="str", + parameters={ + "createdAt": "2020-02-20 00:00:00", + "id": "str", + "listenerCount": 0, + "name": "str", + "requiresClientAuthorization": bool, + "type": "str", + "updatedAt": "2020-02-20 00:00:00", + "userMetadata": "str", + }, + api_version="2017-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_hybrid_connections_delete(self, resource_group): + response = await self.client.hybrid_connections.delete( + resource_group_name=resource_group.name, + namespace_name="str", + hybrid_connection_name="str", + api_version="2017-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_hybrid_connections_get(self, resource_group): + response = await self.client.hybrid_connections.get( + resource_group_name=resource_group.name, + namespace_name="str", + hybrid_connection_name="str", + api_version="2017-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_hybrid_connections_list_authorization_rules(self, resource_group): + response = self.client.hybrid_connections.list_authorization_rules( + resource_group_name=resource_group.name, + namespace_name="str", + hybrid_connection_name="str", + api_version="2017-04-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_hybrid_connections_create_or_update_authorization_rule(self, resource_group): + response = await self.client.hybrid_connections.create_or_update_authorization_rule( + resource_group_name=resource_group.name, + namespace_name="str", + hybrid_connection_name="str", + authorization_rule_name="str", + parameters={"rights": ["str"], "id": "str", "name": "str", "type": "str"}, + api_version="2017-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_hybrid_connections_delete_authorization_rule(self, resource_group): + response = await self.client.hybrid_connections.delete_authorization_rule( + resource_group_name=resource_group.name, + namespace_name="str", + hybrid_connection_name="str", + authorization_rule_name="str", + api_version="2017-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_hybrid_connections_get_authorization_rule(self, resource_group): + response = await self.client.hybrid_connections.get_authorization_rule( + resource_group_name=resource_group.name, + namespace_name="str", + hybrid_connection_name="str", + authorization_rule_name="str", + api_version="2017-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_hybrid_connections_list_keys(self, resource_group): + response = await self.client.hybrid_connections.list_keys( + resource_group_name=resource_group.name, + namespace_name="str", + hybrid_connection_name="str", + authorization_rule_name="str", + api_version="2017-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_hybrid_connections_regenerate_keys(self, resource_group): + response = await self.client.hybrid_connections.regenerate_keys( + resource_group_name=resource_group.name, + namespace_name="str", + hybrid_connection_name="str", + authorization_rule_name="str", + parameters={"keyType": "str", "key": "str"}, + api_version="2017-04-01", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/relay/azure-mgmt-relay/generated_tests/test_relay_api_namespaces_operations.py b/sdk/relay/azure-mgmt-relay/generated_tests/test_relay_api_namespaces_operations.py new file mode 100644 index 000000000000..e0a0f6293e36 --- /dev/null +++ b/sdk/relay/azure-mgmt-relay/generated_tests/test_relay_api_namespaces_operations.py @@ -0,0 +1,203 @@ +# 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 pytest +from azure.mgmt.relay import RelayAPI + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestRelayAPINamespacesOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(RelayAPI) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_namespaces_check_name_availability(self, resource_group): + response = self.client.namespaces.check_name_availability( + parameters={"name": "str"}, + api_version="2017-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_namespaces_list(self, resource_group): + response = self.client.namespaces.list( + api_version="2017-04-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_namespaces_list_by_resource_group(self, resource_group): + response = self.client.namespaces.list_by_resource_group( + resource_group_name=resource_group.name, + api_version="2017-04-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_namespaces_begin_create_or_update(self, resource_group): + response = self.client.namespaces.begin_create_or_update( + resource_group_name=resource_group.name, + namespace_name="str", + parameters={ + "location": "str", + "createdAt": "2020-02-20 00:00:00", + "id": "str", + "metricId": "str", + "name": "str", + "provisioningState": "str", + "serviceBusEndpoint": "str", + "sku": {"name": "Standard", "tier": "Standard"}, + "tags": {"str": "str"}, + "type": "str", + "updatedAt": "2020-02-20 00:00:00", + }, + api_version="2017-04-01", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_namespaces_begin_delete(self, resource_group): + response = self.client.namespaces.begin_delete( + resource_group_name=resource_group.name, + namespace_name="str", + api_version="2017-04-01", + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_namespaces_get(self, resource_group): + response = self.client.namespaces.get( + resource_group_name=resource_group.name, + namespace_name="str", + api_version="2017-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_namespaces_update(self, resource_group): + response = self.client.namespaces.update( + resource_group_name=resource_group.name, + namespace_name="str", + parameters={ + "createdAt": "2020-02-20 00:00:00", + "id": "str", + "metricId": "str", + "name": "str", + "provisioningState": "str", + "serviceBusEndpoint": "str", + "sku": {"name": "Standard", "tier": "Standard"}, + "tags": {"str": "str"}, + "type": "str", + "updatedAt": "2020-02-20 00:00:00", + }, + api_version="2017-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_namespaces_list_authorization_rules(self, resource_group): + response = self.client.namespaces.list_authorization_rules( + resource_group_name=resource_group.name, + namespace_name="str", + api_version="2017-04-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_namespaces_create_or_update_authorization_rule(self, resource_group): + response = self.client.namespaces.create_or_update_authorization_rule( + resource_group_name=resource_group.name, + namespace_name="str", + authorization_rule_name="str", + parameters={"rights": ["str"], "id": "str", "name": "str", "type": "str"}, + api_version="2017-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_namespaces_delete_authorization_rule(self, resource_group): + response = self.client.namespaces.delete_authorization_rule( + resource_group_name=resource_group.name, + namespace_name="str", + authorization_rule_name="str", + api_version="2017-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_namespaces_get_authorization_rule(self, resource_group): + response = self.client.namespaces.get_authorization_rule( + resource_group_name=resource_group.name, + namespace_name="str", + authorization_rule_name="str", + api_version="2017-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_namespaces_list_keys(self, resource_group): + response = self.client.namespaces.list_keys( + resource_group_name=resource_group.name, + namespace_name="str", + authorization_rule_name="str", + api_version="2017-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_namespaces_regenerate_keys(self, resource_group): + response = self.client.namespaces.regenerate_keys( + resource_group_name=resource_group.name, + namespace_name="str", + authorization_rule_name="str", + parameters={"keyType": "str", "key": "str"}, + api_version="2017-04-01", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/relay/azure-mgmt-relay/generated_tests/test_relay_api_namespaces_operations_async.py b/sdk/relay/azure-mgmt-relay/generated_tests/test_relay_api_namespaces_operations_async.py new file mode 100644 index 000000000000..51ab873684a9 --- /dev/null +++ b/sdk/relay/azure-mgmt-relay/generated_tests/test_relay_api_namespaces_operations_async.py @@ -0,0 +1,208 @@ +# 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 pytest +from azure.mgmt.relay.aio import RelayAPI + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestRelayAPINamespacesOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(RelayAPI, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_namespaces_check_name_availability(self, resource_group): + response = await self.client.namespaces.check_name_availability( + parameters={"name": "str"}, + api_version="2017-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_namespaces_list(self, resource_group): + response = self.client.namespaces.list( + api_version="2017-04-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_namespaces_list_by_resource_group(self, resource_group): + response = self.client.namespaces.list_by_resource_group( + resource_group_name=resource_group.name, + api_version="2017-04-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_namespaces_begin_create_or_update(self, resource_group): + response = await ( + await self.client.namespaces.begin_create_or_update( + resource_group_name=resource_group.name, + namespace_name="str", + parameters={ + "location": "str", + "createdAt": "2020-02-20 00:00:00", + "id": "str", + "metricId": "str", + "name": "str", + "provisioningState": "str", + "serviceBusEndpoint": "str", + "sku": {"name": "Standard", "tier": "Standard"}, + "tags": {"str": "str"}, + "type": "str", + "updatedAt": "2020-02-20 00:00:00", + }, + api_version="2017-04-01", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_namespaces_begin_delete(self, resource_group): + response = await ( + await self.client.namespaces.begin_delete( + resource_group_name=resource_group.name, + namespace_name="str", + api_version="2017-04-01", + ) + ).result() # call '.result()' to poll until service return final result + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_namespaces_get(self, resource_group): + response = await self.client.namespaces.get( + resource_group_name=resource_group.name, + namespace_name="str", + api_version="2017-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_namespaces_update(self, resource_group): + response = await self.client.namespaces.update( + resource_group_name=resource_group.name, + namespace_name="str", + parameters={ + "createdAt": "2020-02-20 00:00:00", + "id": "str", + "metricId": "str", + "name": "str", + "provisioningState": "str", + "serviceBusEndpoint": "str", + "sku": {"name": "Standard", "tier": "Standard"}, + "tags": {"str": "str"}, + "type": "str", + "updatedAt": "2020-02-20 00:00:00", + }, + api_version="2017-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_namespaces_list_authorization_rules(self, resource_group): + response = self.client.namespaces.list_authorization_rules( + resource_group_name=resource_group.name, + namespace_name="str", + api_version="2017-04-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_namespaces_create_or_update_authorization_rule(self, resource_group): + response = await self.client.namespaces.create_or_update_authorization_rule( + resource_group_name=resource_group.name, + namespace_name="str", + authorization_rule_name="str", + parameters={"rights": ["str"], "id": "str", "name": "str", "type": "str"}, + api_version="2017-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_namespaces_delete_authorization_rule(self, resource_group): + response = await self.client.namespaces.delete_authorization_rule( + resource_group_name=resource_group.name, + namespace_name="str", + authorization_rule_name="str", + api_version="2017-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_namespaces_get_authorization_rule(self, resource_group): + response = await self.client.namespaces.get_authorization_rule( + resource_group_name=resource_group.name, + namespace_name="str", + authorization_rule_name="str", + api_version="2017-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_namespaces_list_keys(self, resource_group): + response = await self.client.namespaces.list_keys( + resource_group_name=resource_group.name, + namespace_name="str", + authorization_rule_name="str", + api_version="2017-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_namespaces_regenerate_keys(self, resource_group): + response = await self.client.namespaces.regenerate_keys( + resource_group_name=resource_group.name, + namespace_name="str", + authorization_rule_name="str", + parameters={"keyType": "str", "key": "str"}, + api_version="2017-04-01", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/relay/azure-mgmt-relay/generated_tests/test_relay_api_operations.py b/sdk/relay/azure-mgmt-relay/generated_tests/test_relay_api_operations.py new file mode 100644 index 000000000000..d586df412f00 --- /dev/null +++ b/sdk/relay/azure-mgmt-relay/generated_tests/test_relay_api_operations.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. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.relay import RelayAPI + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestRelayAPIOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(RelayAPI) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_operations_list(self, resource_group): + response = self.client.operations.list( + api_version="2017-04-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/relay/azure-mgmt-relay/generated_tests/test_relay_api_operations_async.py b/sdk/relay/azure-mgmt-relay/generated_tests/test_relay_api_operations_async.py new file mode 100644 index 000000000000..14f73d5f4467 --- /dev/null +++ b/sdk/relay/azure-mgmt-relay/generated_tests/test_relay_api_operations_async.py @@ -0,0 +1,30 @@ +# 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 pytest +from azure.mgmt.relay.aio import RelayAPI + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestRelayAPIOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(RelayAPI, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_operations_list(self, resource_group): + response = self.client.operations.list( + api_version="2017-04-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/relay/azure-mgmt-relay/generated_tests/test_relay_apiwcf_relays_operations.py b/sdk/relay/azure-mgmt-relay/generated_tests/test_relay_apiwcf_relays_operations.py new file mode 100644 index 000000000000..604dd058e3ff --- /dev/null +++ b/sdk/relay/azure-mgmt-relay/generated_tests/test_relay_apiwcf_relays_operations.py @@ -0,0 +1,168 @@ +# 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 pytest +from azure.mgmt.relay import RelayAPI + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestRelayAPIWCFRelaysOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(RelayAPI) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_wcf_relays_list_by_namespace(self, resource_group): + response = self.client.wcf_relays.list_by_namespace( + resource_group_name=resource_group.name, + namespace_name="str", + api_version="2017-04-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_wcf_relays_create_or_update(self, resource_group): + response = self.client.wcf_relays.create_or_update( + resource_group_name=resource_group.name, + namespace_name="str", + relay_name="str", + parameters={ + "createdAt": "2020-02-20 00:00:00", + "id": "str", + "isDynamic": bool, + "listenerCount": 0, + "name": "str", + "relayType": "str", + "requiresClientAuthorization": bool, + "requiresTransportSecurity": bool, + "type": "str", + "updatedAt": "2020-02-20 00:00:00", + "userMetadata": "str", + }, + api_version="2017-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_wcf_relays_delete(self, resource_group): + response = self.client.wcf_relays.delete( + resource_group_name=resource_group.name, + namespace_name="str", + relay_name="str", + api_version="2017-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_wcf_relays_get(self, resource_group): + response = self.client.wcf_relays.get( + resource_group_name=resource_group.name, + namespace_name="str", + relay_name="str", + api_version="2017-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_wcf_relays_list_authorization_rules(self, resource_group): + response = self.client.wcf_relays.list_authorization_rules( + resource_group_name=resource_group.name, + namespace_name="str", + relay_name="str", + api_version="2017-04-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_wcf_relays_create_or_update_authorization_rule(self, resource_group): + response = self.client.wcf_relays.create_or_update_authorization_rule( + resource_group_name=resource_group.name, + namespace_name="str", + relay_name="str", + authorization_rule_name="str", + parameters={"rights": ["str"], "id": "str", "name": "str", "type": "str"}, + api_version="2017-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_wcf_relays_delete_authorization_rule(self, resource_group): + response = self.client.wcf_relays.delete_authorization_rule( + resource_group_name=resource_group.name, + namespace_name="str", + relay_name="str", + authorization_rule_name="str", + api_version="2017-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_wcf_relays_get_authorization_rule(self, resource_group): + response = self.client.wcf_relays.get_authorization_rule( + resource_group_name=resource_group.name, + namespace_name="str", + relay_name="str", + authorization_rule_name="str", + api_version="2017-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_wcf_relays_list_keys(self, resource_group): + response = self.client.wcf_relays.list_keys( + resource_group_name=resource_group.name, + namespace_name="str", + relay_name="str", + authorization_rule_name="str", + api_version="2017-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_wcf_relays_regenerate_keys(self, resource_group): + response = self.client.wcf_relays.regenerate_keys( + resource_group_name=resource_group.name, + namespace_name="str", + relay_name="str", + authorization_rule_name="str", + parameters={"keyType": "str", "key": "str"}, + api_version="2017-04-01", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/relay/azure-mgmt-relay/generated_tests/test_relay_apiwcf_relays_operations_async.py b/sdk/relay/azure-mgmt-relay/generated_tests/test_relay_apiwcf_relays_operations_async.py new file mode 100644 index 000000000000..f3b43857616c --- /dev/null +++ b/sdk/relay/azure-mgmt-relay/generated_tests/test_relay_apiwcf_relays_operations_async.py @@ -0,0 +1,169 @@ +# 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 pytest +from azure.mgmt.relay.aio import RelayAPI + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestRelayAPIWCFRelaysOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(RelayAPI, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_wcf_relays_list_by_namespace(self, resource_group): + response = self.client.wcf_relays.list_by_namespace( + resource_group_name=resource_group.name, + namespace_name="str", + api_version="2017-04-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_wcf_relays_create_or_update(self, resource_group): + response = await self.client.wcf_relays.create_or_update( + resource_group_name=resource_group.name, + namespace_name="str", + relay_name="str", + parameters={ + "createdAt": "2020-02-20 00:00:00", + "id": "str", + "isDynamic": bool, + "listenerCount": 0, + "name": "str", + "relayType": "str", + "requiresClientAuthorization": bool, + "requiresTransportSecurity": bool, + "type": "str", + "updatedAt": "2020-02-20 00:00:00", + "userMetadata": "str", + }, + api_version="2017-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_wcf_relays_delete(self, resource_group): + response = await self.client.wcf_relays.delete( + resource_group_name=resource_group.name, + namespace_name="str", + relay_name="str", + api_version="2017-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_wcf_relays_get(self, resource_group): + response = await self.client.wcf_relays.get( + resource_group_name=resource_group.name, + namespace_name="str", + relay_name="str", + api_version="2017-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_wcf_relays_list_authorization_rules(self, resource_group): + response = self.client.wcf_relays.list_authorization_rules( + resource_group_name=resource_group.name, + namespace_name="str", + relay_name="str", + api_version="2017-04-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_wcf_relays_create_or_update_authorization_rule(self, resource_group): + response = await self.client.wcf_relays.create_or_update_authorization_rule( + resource_group_name=resource_group.name, + namespace_name="str", + relay_name="str", + authorization_rule_name="str", + parameters={"rights": ["str"], "id": "str", "name": "str", "type": "str"}, + api_version="2017-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_wcf_relays_delete_authorization_rule(self, resource_group): + response = await self.client.wcf_relays.delete_authorization_rule( + resource_group_name=resource_group.name, + namespace_name="str", + relay_name="str", + authorization_rule_name="str", + api_version="2017-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_wcf_relays_get_authorization_rule(self, resource_group): + response = await self.client.wcf_relays.get_authorization_rule( + resource_group_name=resource_group.name, + namespace_name="str", + relay_name="str", + authorization_rule_name="str", + api_version="2017-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_wcf_relays_list_keys(self, resource_group): + response = await self.client.wcf_relays.list_keys( + resource_group_name=resource_group.name, + namespace_name="str", + relay_name="str", + authorization_rule_name="str", + api_version="2017-04-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_wcf_relays_regenerate_keys(self, resource_group): + response = await self.client.wcf_relays.regenerate_keys( + resource_group_name=resource_group.name, + namespace_name="str", + relay_name="str", + authorization_rule_name="str", + parameters={"keyType": "str", "key": "str"}, + api_version="2017-04-01", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/relay/azure-mgmt-relay/pyproject.toml b/sdk/relay/azure-mgmt-relay/pyproject.toml index 540da07d41af..0f11ca28ceb0 100644 --- a/sdk/relay/azure-mgmt-relay/pyproject.toml +++ b/sdk/relay/azure-mgmt-relay/pyproject.toml @@ -1,6 +1,88 @@ +[build-system] +requires = [ + "setuptools>=77.0.3", + "wheel", +] +build-backend = "setuptools.build_meta" + +[project] +name = "azure-mgmt-relay" +authors = [ + { name = "Microsoft Corporation", email = "azpysdkhelp@microsoft.com" }, +] +description = "Microsoft Azure Relay Management Client Library for Python" +license = "MIT" +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Programming Language :: Python", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", +] +requires-python = ">=3.9" +keywords = [ + "azure", + "azure sdk", +] +dependencies = [ + "isodate>=0.6.1", + "azure-mgmt-core>=1.6.0", + "typing-extensions>=4.6.0", +] +dynamic = [ + "version", + "readme", +] + +[project.urls] +repository = "https://github.com/Azure/azure-sdk-for-python" + +[tool.setuptools.dynamic.version] +attr = "azure.mgmt.relay._version.VERSION" + +[tool.setuptools.dynamic.readme] +file = [ + "README.md", + "CHANGELOG.md", +] +content-type = "text/markdown" + +[tool.setuptools.packages.find] +exclude = [ + "tests*", + "generated_tests*", + "samples*", + "generated_samples*", + "doc*", + "azure", + "azure.mgmt", +] + +[tool.setuptools.package-data] +pytyped = [ + "py.typed", +] + [tool.azure-sdk-build] breaking = false mypy = false pyright = false type_check_samples = false verifytypes = false + +[packaging] +package_name = "azure-mgmt-relay" +package_nspkg = "azure-mgmt-nspkg" +package_pprint_name = "Relay" +package_doc_id = "relay" +is_stable = true +is_arm = true +sample_link = "" +title = "RelayAPI" +need_msrestazure = false +need_azuremgmtcore = true +exclude_folders = "" diff --git a/sdk/relay/azure-mgmt-relay/sdk_packaging.toml b/sdk/relay/azure-mgmt-relay/sdk_packaging.toml deleted file mode 100644 index be016444e116..000000000000 --- a/sdk/relay/azure-mgmt-relay/sdk_packaging.toml +++ /dev/null @@ -1,9 +0,0 @@ -[packaging] -package_name = "azure-mgmt-relay" -package_nspkg = "azure-mgmt-nspkg" -package_pprint_name = "Relay" -package_doc_id = "relay" -is_stable = false -is_arm = true -sample_link = "" -title = "RelayAPI" diff --git a/sdk/relay/azure-mgmt-relay/setup.py b/sdk/relay/azure-mgmt-relay/setup.py deleted file mode 100644 index 389416686962..000000000000 --- a/sdk/relay/azure-mgmt-relay/setup.py +++ /dev/null @@ -1,79 +0,0 @@ -#!/usr/bin/env python - -#------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -#-------------------------------------------------------------------------- - -import re -import os.path -from io import open -from setuptools import find_packages, setup - -# Change the PACKAGE_NAME only to change folder and different name -PACKAGE_NAME = "azure-mgmt-relay" -PACKAGE_PPRINT_NAME = "Relay" - -# a-b-c => a/b/c -package_folder_path = PACKAGE_NAME.replace('-', '/') -# a-b-c => a.b.c -namespace_name = PACKAGE_NAME.replace('-', '.') - -# Version extraction inspired from 'requests' -with open(os.path.join(package_folder_path, 'version.py') - if os.path.exists(os.path.join(package_folder_path, 'version.py')) - else os.path.join(package_folder_path, '_version.py'), 'r') as fd: - version = re.search(r'^VERSION\s*=\s*[\'"]([^\'"]*)[\'"]', - fd.read(), re.MULTILINE).group(1) - -if not version: - raise RuntimeError('Cannot find version information') - -with open('README.md', encoding='utf-8') as f: - readme = f.read() -with open('CHANGELOG.md', encoding='utf-8') as f: - changelog = f.read() - -setup( - name=PACKAGE_NAME, - version=version, - description='Microsoft Azure {} Client Library for Python'.format(PACKAGE_PPRINT_NAME), - long_description=readme + '\n\n' + changelog, - long_description_content_type='text/markdown', - license='MIT License', - author='Microsoft Corporation', - author_email='azpysdkhelp@microsoft.com', - url='https://github.com/Azure/azure-sdk-for-python', - keywords="azure, azure sdk", # update with search keywords relevant to the azure service / product - classifiers=[ - 'Development Status :: 4 - Beta', - 'Programming Language :: Python', - 'Programming Language :: Python :: 3 :: Only', - 'Programming Language :: Python :: 3', - 'Programming Language :: Python :: 3.7', - 'Programming Language :: Python :: 3.8', - 'Programming Language :: Python :: 3.9', - 'Programming Language :: Python :: 3.10', - 'Programming Language :: Python :: 3.11', - 'License :: OSI Approved :: MIT License', - ], - zip_safe=False, - packages=find_packages(exclude=[ - 'tests', - # Exclude packages that will be covered by PEP420 or nspkg - 'azure', - 'azure.mgmt', - ]), - include_package_data=True, - package_data={ - 'pytyped': ['py.typed'], - }, - install_requires=[ - "msrest>=0.7.1", - "azure-common~=1.1", - "azure-mgmt-core>=1.3.2,<2.0.0", - "typing-extensions>=4.3.0; python_version<'3.8.0'", - ], - python_requires=">=3.7" -) diff --git a/sdk/relay/azure-mgmt-relay/tests/conftest.py b/sdk/relay/azure-mgmt-relay/tests/conftest.py deleted file mode 100644 index 87acda807946..000000000000 --- a/sdk/relay/azure-mgmt-relay/tests/conftest.py +++ /dev/null @@ -1,58 +0,0 @@ -# -------------------------------------------------------------------------- -# -# 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. -# -# -------------------------------------------------------------------------- -import os -import platform -import pytest -import sys - -from dotenv import load_dotenv - -from devtools_testutils import test_proxy, add_general_regex_sanitizer -from devtools_testutils import add_header_regex_sanitizer, add_body_key_sanitizer - -# Ignore async tests for Python < 3.5 -collect_ignore_glob = [] -if sys.version_info < (3, 5) or platform.python_implementation() == "PyPy": - collect_ignore_glob.append("*_async.py") - -load_dotenv() - -@pytest.fixture(scope="session", autouse=True) -def add_sanitizers(test_proxy): - subscription_id = os.environ.get("AZURE_SUBSCRIPTION_ID", "00000000-0000-0000-0000-000000000000") - tenant_id = os.environ.get("AZURE_TENANT_ID", "00000000-0000-0000-0000-000000000000") - client_id = os.environ.get("AZURE_CLIENT_ID", "00000000-0000-0000-0000-000000000000") - client_secret = os.environ.get("AZURE_CLIENT_SECRET", "00000000-0000-0000-0000-000000000000") - add_general_regex_sanitizer(regex=subscription_id, value="00000000-0000-0000-0000-000000000000") - add_general_regex_sanitizer(regex=tenant_id, value="00000000-0000-0000-0000-000000000000") - add_general_regex_sanitizer(regex=client_id, value="00000000-0000-0000-0000-000000000000") - add_general_regex_sanitizer(regex=client_secret, value="00000000-0000-0000-0000-000000000000") - add_header_regex_sanitizer(key="Set-Cookie", value="[set-cookie;]") - add_header_regex_sanitizer(key="Cookie", value="cookie;") - add_body_key_sanitizer(json_path="$..access_token", value="access_token") - add_body_key_sanitizer(json_path="$..primaryKey", value="primaryKey") - add_body_key_sanitizer(json_path="$..secondaryKey", value="secondaryKey") - add_body_key_sanitizer(json_path="$..secondaryConnectionString", value="secondaryConnectionString") \ No newline at end of file diff --git a/sdk/relay/azure-mgmt-relay/tests/disable_test_azure_mgmt_hybridconnection.py b/sdk/relay/azure-mgmt-relay/tests/disable_test_azure_mgmt_hybridconnection.py deleted file mode 100644 index d0e440512c65..000000000000 --- a/sdk/relay/azure-mgmt-relay/tests/disable_test_azure_mgmt_hybridconnection.py +++ /dev/null @@ -1,122 +0,0 @@ -# coding: utf-8 - -#------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -#-------------------------------------------------------------------------- -import unittest -import time - -import azure.mgmt.relay.models -from azure.mgmt.relay.models import RelayNamespace, Sku, AccessRights -from devtools_testutils import AzureMgmtRecordedTestCase, ResourceGroupPreparer, recorded_by_proxy - - -class TestMgmtHybridConnection(AzureMgmtRecordedTestCase): - - def setup_method(self, method): - - self.relay_client = self.create_mgmt_client( - azure.mgmt.relay.RelayAPI - ) - - @ResourceGroupPreparer() - @recorded_by_proxy - def test_hybridconnetion_curd(self, resource_group, location): - - resource_group_name = resource_group.name - - #Create a Namespace - namespace_name = "testingpythontestcasenamespacehybridconnection" - - namespaceparameter = RelayNamespace(location=location, tags={'tag1': 'value1', 'tag2': 'value2'}, sku=Sku(tier="standard")) - creatednamespace = self.relay_client.namespaces.begin_create_or_update(resource_group_name, namespace_name, namespaceparameter).result() - assert creatednamespace.name == namespace_name - - # - # # Get created Namespace - # - getnamespaceresponse = self.relay_client.namespaces.get(resource_group_name, namespace_name) - assert getnamespaceresponse.name == namespace_name - - # Create a HybridConnection - hybridconnection_name = "testingpythontestcasehybridconnection" - - createdhybridconnectionresponse = self.relay_client.hybrid_connections.create_or_update(resource_group_name, namespace_name, hybridconnection_name, { - "requires_client_authorization": True, - "user_metadata": "User data for HybridConnection" - }) - - assert createdhybridconnectionresponse.name == hybridconnection_name - assert createdhybridconnectionresponse.requires_client_authorization == True - - #Get the created Hybridconnection - gethybridconnectionresponse = self.relay_client.hybrid_connections.get(resource_group_name, namespace_name, hybridconnection_name) - assert gethybridconnectionresponse.name == hybridconnection_name - assert gethybridconnectionresponse.user_metadata == "User data for HybridConnection" - - #Get the List of Hybridconnection by namespaces - getlistbynamespacehybridconnectionresponse = list(self.relay_client.hybrid_connections.list_by_namespace(resource_group_name, namespace_name)) - assert len(getlistbynamespacehybridconnectionresponse) > 0 - - updatehybridconnectionresponse = self.relay_client.hybrid_connections.create_or_update(resource_group_name, namespace_name, hybridconnection_name, { - "user_metadata": "User data for HybridConnection updated" - }) - - assert updatehybridconnectionresponse.name == hybridconnection_name - assert updatehybridconnectionresponse.requires_client_authorization == True - assert updatehybridconnectionresponse.user_metadata == "User data for HybridConnection updated" - - # Create a new authorizationrule - authoRule_name = "testingauthrulepy" - createhybridconnectionauthorule = self.relay_client.hybrid_connections.create_or_update_authorization_rule(resource_group_name, namespace_name, hybridconnection_name, authoRule_name,{ - "rights": [AccessRights('Send'),AccessRights('Listen')] - }) - assert createhybridconnectionauthorule.name, authoRule_name == "Authorization rule name not as created - create_or_update_authorization_rule " - assert len(createhybridconnectionauthorule.rights) == 2 - - # Get the created authorizationrule - gethybridconnectionauthorule = self.relay_client.hybrid_connections.get_authorization_rule(resource_group_name, namespace_name, hybridconnection_name, authoRule_name) - assert gethybridconnectionauthorule.name, authoRule_name == "Authorization rule name not as passed as parameter - get_authorization_rule " - assert len(gethybridconnectionauthorule.rights), 2 == "Access rights mis match as created - get_authorization_rule " - - # update the rights of the authorizatiorule - gethybridconnectionauthorule.rights.append('Manage') - updatehybridconnectionauthorule = self.relay_client.hybrid_connections.create_or_update_authorization_rule(resource_group_name, namespace_name, hybridconnection_name, authoRule_name, gethybridconnectionauthorule) - assert updatehybridconnectionauthorule.name, authoRule_name == "Authorization rule name not as passed as parameter for update call - create_or_update_authorization_rule " - assert len(updatehybridconnectionauthorule.rights), 3 == "Access rights mis match as updated - create_or_update_authorization_rule " - - #list all the authorization ruels for the given namespace - hybridconnectionauthorulelist = list(self.relay_client.hybrid_connections.list_authorization_rules(resource_group_name, namespace_name, hybridconnection_name)) - assert len(hybridconnectionauthorulelist), 1 == "number of authorization rule mismatch with the created + default = 2 - list_authorization_rules" - - #List keys for the authorization rule - listkeysauthorizationrule = self.relay_client.hybrid_connections.list_keys(resource_group_name, namespace_name, hybridconnection_name, authoRule_name) - assert listkeysauthorizationrule is not None - - # regenerate Keys for authorizationrule - Primary - regenratePrimarykeyauthorizationrule = self.relay_client.hybrid_connections.regenerate_keys(resource_group_name, namespace_name, hybridconnection_name, authoRule_name, { - "key_type": 'PrimaryKey' - }) - assert listkeysauthorizationrule.primary_key !=regenratePrimarykeyauthorizationrule.primary_key - - # regenerate Keys for authorizationrule - Primary - regenrateSecondarykeyauthorizationrule = self.relay_client.hybrid_connections.regenerate_keys(resource_group_name,namespace_name, hybridconnection_name, authoRule_name, { - "key_type": 'SecondaryKey' - }) - assert listkeysauthorizationrule.secondary_key != regenrateSecondarykeyauthorizationrule.secondary_key - - # delete the authorizationrule - self.relay_client.hybrid_connections.delete_authorization_rule(resource_group_name, namespace_name, hybridconnection_name, authoRule_name) - - # Delete the created HybridConnection - gethybridconnectionresponse = self.relay_client.hybrid_connections.delete(resource_group_name, namespace_name, hybridconnection_name) - - # Delete the create namespace - self.relay_client.namespaces.begin_delete(resource_group_name, namespace_name).result() - - -# ------------------------------------------------------------------------------ -if __name__ == '__main__': - unittest.main() diff --git a/sdk/relay/azure-mgmt-relay/tests/disable_test_azure_mgmt_operations.py b/sdk/relay/azure-mgmt-relay/tests/disable_test_azure_mgmt_operations.py deleted file mode 100644 index 9ae17d3f2e13..000000000000 --- a/sdk/relay/azure-mgmt-relay/tests/disable_test_azure_mgmt_operations.py +++ /dev/null @@ -1,29 +0,0 @@ -# coding: utf-8 - -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- -import unittest -import azure.mgmt.relay -from devtools_testutils import AzureMgmtRecordedTestCase, ResourceGroupPreparer, recorded_by_proxy - - -class TestMgmtRelay(AzureMgmtRecordedTestCase): - - def setup_method(self, method): - - self.relay_client = self.create_mgmt_client( - azure.mgmt.relay.RelayAPI - ) - - @recorded_by_proxy - def test_operations_list(self): - # Check the namespace availability - result = self.relay_client.operations.list() - - -# ------------------------------------------------------------------------------ -if __name__ == '__main__': - unittest.main() \ No newline at end of file diff --git a/sdk/relay/azure-mgmt-relay/tests/disable_test_azure_mgmt_relay_check_name_availability.py b/sdk/relay/azure-mgmt-relay/tests/disable_test_azure_mgmt_relay_check_name_availability.py deleted file mode 100644 index a085517cf674..000000000000 --- a/sdk/relay/azure-mgmt-relay/tests/disable_test_azure_mgmt_relay_check_name_availability.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding: utf-8 - -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- -import unittest -import azure.mgmt.relay -from devtools_testutils import AzureMgmtRecordedTestCase, ResourceGroupPreparer, recorded_by_proxy - - -class TestMgmtRelay(AzureMgmtRecordedTestCase): - - def setup_method(self, method): - - self.relay_client = self.create_mgmt_client( - azure.mgmt.relay.RelayAPI - ) - - def process(self, result): - pass - - @recorded_by_proxy - def test_eh_namespace_available(self): - # Check the namespace availability - availabilityresult = self.relay_client.namespaces.check_name_availability({ - "name": "Testingehnamespaceavailabilityforpython" - }) - assert availabilityresult.name_available == True - - -# ------------------------------------------------------------------------------ -if __name__ == '__main__': - unittest.main() diff --git a/sdk/relay/azure-mgmt-relay/tests/disable_test_azure_mgmt_relay_namespace.py b/sdk/relay/azure-mgmt-relay/tests/disable_test_azure_mgmt_relay_namespace.py deleted file mode 100644 index 5f321f48829b..000000000000 --- a/sdk/relay/azure-mgmt-relay/tests/disable_test_azure_mgmt_relay_namespace.py +++ /dev/null @@ -1,111 +0,0 @@ -# coding: utf-8 - -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- -import unittest -import azure.mgmt.relay -from azure.mgmt.relay.models import RelayNamespace, Sku, AccessRights - -from devtools_testutils import AzureMgmtRecordedTestCase, ResourceGroupPreparer, recorded_by_proxy - - -class TestMgmtRelayNamespace(AzureMgmtRecordedTestCase): - - def setup_method(self, method): - - self.relay_client = self.create_mgmt_client( - azure.mgmt.relay.RelayAPI - ) - - @ResourceGroupPreparer() - @recorded_by_proxy - def test_relay_namespace_curd(self, resource_group, location): - - resource_group_name = resource_group.name - - # Create a Namespace - namespace_name = "testingpythontestcasenamespace" - namespaceparameter=RelayNamespace(location=location, tags={'tag1':'value1', 'tag2':'value2'}, sku=Sku(tier="standard")) - creatednamespace = self.relay_client.namespaces.begin_create_or_update(resource_group_name, namespace_name, namespaceparameter).result() - assert creatednamespace.name == namespace_name - # - # # Get created Namespace - # - getnamespaceresponse = self.relay_client.namespaces.get(resource_group_name, namespace_name) - assert getnamespaceresponse.name == namespace_name - - # Update a Namespace - namespaceparameter={'tags': {'tag1':'value1', 'tag2':'value2'}} - updatenamespace = self.relay_client.namespaces.update(resource_group_name, namespace_name, namespaceparameter) - - # Get the List of Namespaces under the resourceGroup - list_by_resource_group - listbyresourcegroupresponse = list(self.relay_client.namespaces.list_by_resource_group(resource_group_name)) - assert len(listbyresourcegroupresponse) > 0, "No Namespace returned > List is empty" - assert listbyresourcegroupresponse[0].name == namespace_name, "Created namespace not found - ListByResourgroup" - - # Get the List of namespace under the subscription - list - listbysubscriptionresponse = list(self.relay_client.namespaces.list()) - assert len(listbysubscriptionresponse) > 0, "No Namespace returned > List is empty" - # get the default authorizationrule - defaultauthorule_name = "RootManageSharedAccessKey" - defaultamespaceauthorule = self.relay_client.namespaces.get_authorization_rule(resource_group_name, namespace_name, defaultauthorule_name) - assert defaultamespaceauthorule.name == defaultauthorule_name, "Default Authorization rule not returned - RootManageSharedAccessKey" - assert len(defaultamespaceauthorule.rights) == 3, "rights for deafult not as required - send == listen and manage " - - # Create a new authorizationrule - authoRule_name = "testingauthrulepy" - createnamespaceauthorule = self.relay_client.namespaces.create_or_update_authorization_rule(resource_group_name,namespace_name,authoRule_name, { - "rights": [AccessRights('Send'),AccessRights('Listen')] - }) - assert createnamespaceauthorule.name,authoRule_name == "Authorization rule name not as created - create_or_update_authorization_rule " - assert len(createnamespaceauthorule.rights) ==2 - - # Get the created authorizationrule - getnamespaceauthorule = self.relay_client.namespaces.get_authorization_rule(resource_group_name, namespace_name, authoRule_name) - assert getnamespaceauthorule.name, authoRule_name == "Authorization rule name not as passed as parameter - get_authorization_rule " - assert len(getnamespaceauthorule.rights), 2 == "Access rights mis match as created - get_authorization_rule " - - # update the rights of the authorizatiorule - getnamespaceauthorule.rights.append('Manage') - updatenamespaceauthorule = self.relay_client.namespaces.create_or_update_authorization_rule(resource_group_name, namespace_name, authoRule_name, getnamespaceauthorule) - assert updatenamespaceauthorule.name, authoRule_name == "Authorization rule name not as passed as parameter for update call - create_or_update_authorization_rule " - assert len(updatenamespaceauthorule.rights), 3 == "Access rights mis match as updated - create_or_update_authorization_rule " - - # list all the authorization ruels for the given namespace - createnamespaceauthorule = list(self.relay_client.namespaces.list_authorization_rules(resource_group_name, namespace_name)) - assert len(createnamespaceauthorule),2 == "number of authorization rule mismatch with the created + default = 2 - list_authorization_rules" - - # List keys for the authorization rule - listkeysauthorizationrule = self.relay_client.namespaces.list_keys(resource_group_name, namespace_name, authoRule_name) - assert listkeysauthorizationrule is not None - - # regenerate Keys for authorizationrule - Primary - regenratePrimarykeyauthorizationrule = self.relay_client.namespaces.regenerate_keys(resource_group_name, namespace_name,authoRule_name,{ - "key_type": 'PrimaryKey' - }) - assert listkeysauthorizationrule.primary_key !=regenratePrimarykeyauthorizationrule.primary_key - - # regenerate Keys for authorizationrule - Primary - regenrateSecondarykeyauthorizationrule = self.relay_client.namespaces.regenerate_keys(resource_group_name,namespace_name,authoRule_name, { - "key_type": 'SecondaryKey' - }) - assert listkeysauthorizationrule.secondary_key != regenrateSecondarykeyauthorizationrule.secondary_key - - # delete the authorizationrule - self.relay_client.namespaces.delete_authorization_rule(resource_group_name, namespace_name, authoRule_name) - - # list all the authorization ruels for the given namespace - createnamespaceauthorule = list(self.relay_client.namespaces.list_authorization_rules(resource_group_name, namespace_name)) - assert len(createnamespaceauthorule) == 1 - assert createnamespaceauthorule[0].name == defaultauthorule_name - - # Delete the create namespace - deletenamespace = self.relay_client.namespaces.begin_delete(resource_group_name, namespace_name).result() - - -# ------------------------------------------------------------------------------ -if __name__ == '__main__': - unittest.main() diff --git a/sdk/relay/azure-mgmt-relay/tests/disable_test_azure_mgmt_wcfrelay.py b/sdk/relay/azure-mgmt-relay/tests/disable_test_azure_mgmt_wcfrelay.py deleted file mode 100644 index 88033eca56f0..000000000000 --- a/sdk/relay/azure-mgmt-relay/tests/disable_test_azure_mgmt_wcfrelay.py +++ /dev/null @@ -1,134 +0,0 @@ -# coding: utf-8 - -#------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -#-------------------------------------------------------------------------- -import unittest -import time - -import azure.mgmt.relay.models -from azure.mgmt.relay.models import RelayNamespace, Sku, Relaytype, AuthorizationRule, AccessRights, AccessKeys, WcfRelay, ErrorResponse -from devtools_testutils import AzureMgmtRecordedTestCase, ResourceGroupPreparer, recorded_by_proxy - - -class TestMgmtWcfRelay(AzureMgmtRecordedTestCase): - - def setup_method(self, method): - - self.relay_client = self.create_mgmt_client( - azure.mgmt.relay.RelayAPI - ) - - @ResourceGroupPreparer() - @recorded_by_proxy - def test_wcfrelay_curd(self, resource_group, location): - - resource_group_name = resource_group.name - - #Create a Namespace - namespace_name = "testingpythontestcaseeventhubnamespaceEventhub" - - namespaceparameter = RelayNamespace(location=location, tags={'tag1': 'value1', 'tag2': 'value2'}, sku=Sku(tier="standard")) - creatednamespace = self.relay_client.namespaces.begin_create_or_update(resource_group_name, namespace_name, namespaceparameter).result() - assert creatednamespace.name == namespace_name - - # - # # Get created Namespace - # - getnamespaceresponse = self.relay_client.namespaces.get(resource_group_name, namespace_name) - assert getnamespaceresponse.name == namespace_name - - # Create a WcfRelay - wcfrelay_name = "testingpythontestcasewcfrelay" - wcfrelayparameter = WcfRelay( - relay_type=Relaytype.net_tcp, - requires_client_authorization=True, - requires_transport_security=True, - user_metadata="User data for WcfRelay" - ) - - createdwcfrelayresponse = self.relay_client.wcf_relays.create_or_update(resource_group_name, namespace_name, wcfrelay_name, wcfrelayparameter) - - assert createdwcfrelayresponse.name == wcfrelay_name - assert createdwcfrelayresponse.requires_client_authorization == True - - #Get the created wcfRelay - geteventhubresponse = self.relay_client.wcf_relays.get(resource_group_name, namespace_name, wcfrelay_name) - assert geteventhubresponse.name == wcfrelay_name - assert geteventhubresponse.requires_transport_security == True - assert geteventhubresponse.user_metadata == "User data for WcfRelay" - - #Get the List of wcfRealy by namespaces - getlistbynamespacewcfrelayresponse = list(self.relay_client.wcf_relays.list_by_namespace(resource_group_name, namespace_name)) - assert len(getlistbynamespacewcfrelayresponse) > 0 - - # update the Created eventhub - wcfrelayupdateparameter = WcfRelay( - relay_type=Relaytype.net_tcp, - user_metadata="User data for WcfRelay updated" - ) - updatewcfrelayresponse = self.relay_client.wcf_relays.create_or_update( - resource_group_name, - namespace_name, - wcfrelay_name, - wcfrelayupdateparameter - ) - assert updatewcfrelayresponse.name == wcfrelay_name - assert updatewcfrelayresponse.requires_transport_security == True - assert updatewcfrelayresponse.requires_client_authorization == True - assert updatewcfrelayresponse.user_metadata == "User data for WcfRelay updated" - - # Create a new authorizationrule - authoRule_name = "testingauthrulepy" - createwcfrelayauthorule = self.relay_client.wcf_relays.create_or_update_authorization_rule(resource_group_name, namespace_name, wcfrelay_name, authoRule_name, { - "rights": [AccessRights('Send'),AccessRights('Listen')] - }) - assert createwcfrelayauthorule.name, authoRule_name == "Authorization rule name not as created - create_or_update_authorization_rule " - assert len(createwcfrelayauthorule.rights) == 2 - - # Get the created authorizationrule - getwcfrelayauthorule = self.relay_client.wcf_relays.get_authorization_rule(resource_group_name, namespace_name, wcfrelay_name, authoRule_name) - assert getwcfrelayauthorule.name, authoRule_name == "Authorization rule name not as passed as parameter - get_authorization_rule " - assert len(getwcfrelayauthorule.rights), 2 == "Access rights mis match as created - get_authorization_rule " - - # update the rights of the authorizatiorule - getwcfrelayauthorule.rights.append('Manage') - updatewcfrelayauthorule = self.relay_client.wcf_relays.create_or_update_authorization_rule(resource_group_name, namespace_name, wcfrelay_name, authoRule_name, getwcfrelayauthorule) - assert updatewcfrelayauthorule.name, authoRule_name == "Authorization rule name not as passed as parameter for update call - create_or_update_authorization_rule " - assert len(updatewcfrelayauthorule.rights), 3 == "Access rights mis match as updated - create_or_update_authorization_rule " - - #list all the authorization ruels for the given namespace - wcfrelayauthorulelist = list(self.relay_client.wcf_relays.list_authorization_rules(resource_group_name, namespace_name, wcfrelay_name)) - assert len(wcfrelayauthorulelist), 1 == "number of authorization rule mismatch with the created + default = 2 - list_authorization_rules" - - #List keys for the authorization rule - listkeysauthorizationrule = self.relay_client.wcf_relays.list_keys(resource_group_name, namespace_name, wcfrelay_name, authoRule_name) - assert listkeysauthorizationrule is not None - - # regenerate Keys for authorizationrule - Primary - regenratePrimarykeyauthorizationrule = self.relay_client.wcf_relays.regenerate_keys(resource_group_name, namespace_name, wcfrelay_name, authoRule_name, { - "key_type": 'PrimaryKey' - }) - assert listkeysauthorizationrule.primary_key !=regenratePrimarykeyauthorizationrule.primary_key - - # regenerate Keys for authorizationrule - Primary - regenrateSecondarykeyauthorizationrule = self.relay_client.wcf_relays.regenerate_keys(resource_group_name,namespace_name, wcfrelay_name, authoRule_name, { - "key_type": 'SecondaryKey' - }) - assert listkeysauthorizationrule.secondary_key != regenrateSecondarykeyauthorizationrule.secondary_key - - # delete the authorizationrule - self.relay_client.wcf_relays.delete_authorization_rule(resource_group_name, namespace_name, wcfrelay_name, authoRule_name) - - # Delete the created WcfRelay - getwcfrelayresponse = self.relay_client.wcf_relays.delete(resource_group_name, namespace_name, wcfrelay_name) - - # Delete the create namespace - self.relay_client.namespaces.begin_delete(resource_group_name, namespace_name).result() - - -# ------------------------------------------------------------------------------ -if __name__ == '__main__': - unittest.main()