diff --git a/sdk/monitor/azure-mgmt-monitor/README.md b/sdk/monitor/azure-mgmt-monitor/README.md index b092cdfbcf5f..1599538f3bac 100644 --- a/sdk/monitor/azure-mgmt-monitor/README.md +++ b/sdk/monitor/azure-mgmt-monitor/README.md @@ -1,7 +1,7 @@ # Microsoft Azure SDK for Python This is the Microsoft Azure Monitor Client Library. -This package has been tested with Python 3.7+. +This package has been tested with Python 3.8+. For a more complete view of Azure libraries, see the [azure sdk python release](https://aka.ms/azsdk/python/all). ## _Disclaimer_ @@ -12,7 +12,7 @@ _Azure SDK Python packages support for Python 2.7 has ended 01 January 2022. For ### Prerequisites -- Python 3.7+ is required to use this package. +- Python 3.8+ is required to use this package. - [Azure subscription](https://azure.microsoft.com/free/) ### Install the package @@ -59,6 +59,3 @@ Code samples for this package can be found at: 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. - - -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-python%2Fazure-mgmt-monitor%2FREADME.png) diff --git a/sdk/monitor/azure-mgmt-monitor/_meta.json b/sdk/monitor/azure-mgmt-monitor/_meta.json index bf9e7afe9383..a7820a7b2195 100644 --- a/sdk/monitor/azure-mgmt-monitor/_meta.json +++ b/sdk/monitor/azure-mgmt-monitor/_meta.json @@ -1,11 +1,11 @@ { - "commit": "817e7cea0b7e3194868825cbef6d4e62a7895951", + "commit": "af880e8e40fc17c20811d586542ff4e444692154", "repository_url": "https://github.com/Azure/azure-rest-api-specs", - "autorest": "3.9.2", + "autorest": "3.10.2", "use": [ - "@autorest/python@6.4.8", - "@autorest/modelerfour@4.24.3" + "@autorest/python@6.26.4", + "@autorest/modelerfour@4.27.0" ], - "autorest_command": "autorest specification/monitor/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.4.8 --use=@autorest/modelerfour@4.24.3 --version=3.9.2 --version-tolerant=False", + "autorest_command": "autorest specification/monitor/resource-manager/readme.md --generate-sample=True --generate-test=True --include-x-ms-examples-original-file=True --python --python-sdks-folder=/mnt/vss/_work/1/s/azure-sdk-for-python/sdk --use=@autorest/python@6.26.4 --use=@autorest/modelerfour@4.27.0 --version=3.10.2 --version-tolerant=False", "readme": "specification/monitor/resource-manager/readme.md" } \ No newline at end of file diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/_configuration.py index 358c17303bd9..6388a632149c 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/_configuration.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/_configuration.py @@ -10,7 +10,6 @@ # -------------------------------------------------------------------------- from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy @@ -20,7 +19,7 @@ # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MonitorManagementClientConfiguration(Configuration): +class MonitorManagementClientConfiguration: """Configuration for MonitorManagementClient. Note that all parameters used to create this instance are saved as instance @@ -42,12 +41,12 @@ def __init__( raise ValueError("Parameter 'credential' must not be None.") if subscription_id is None: raise ValueError("Parameter 'subscription_id' must not be None.") - super(MonitorManagementClientConfiguration, self).__init__(**kwargs) self.credential = credential self.subscription_id = subscription_id self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) kwargs.setdefault('sdk_moniker', 'azure-mgmt-monitor/{}'.format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure( diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/_monitor_management_client.py index a452e1c39107..3fb4b487b77f 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/_monitor_management_client.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/_monitor_management_client.py @@ -10,8 +10,11 @@ # -------------------------------------------------------------------------- from typing import Any, Optional, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.mgmt.core import ARMPipelineClient +from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy from azure.profiles import KnownProfiles, ProfileDefinition from azure.profiles.multiapiclient import MultiApiClientMixin @@ -106,8 +109,28 @@ def __init__( profile: KnownProfiles=KnownProfiles.default, **kwargs: Any ): + if api_version: + kwargs.setdefault('api_version', api_version) self._config = MonitorManagementClientConfiguration(credential, subscription_id, **kwargs) - self._client = ARMPipelineClient(base_url=base_url, config=self._config, **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), + 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(base_url=base_url, policies=_policies, **kwargs) super(MonitorManagementClient, self).__init__( api_version=api_version, profile=profile @@ -121,6 +144,7 @@ def _models_dict(cls, api_version): def models(cls, api_version=DEFAULT_API_VERSION): """Module depends on the API version: + * 2014-04-01: :mod:`v2014_04_01.models` * 2015-04-01: :mod:`v2015_04_01.models` * 2015-07-01: :mod:`v2015_07_01.models` * 2016-03-01: :mod:`v2016_03_01.models` @@ -156,7 +180,10 @@ def models(cls, api_version=DEFAULT_API_VERSION): * 2023-01-01: :mod:`v2023_01_01.models` * 2023-03-01-preview: :mod:`v2023_03_01_preview.models` """ - if api_version == '2015-04-01': + if api_version == '2014-04-01': + from .v2014_04_01 import models + return models + elif api_version == '2015-04-01': from .v2015_04_01 import models return models elif api_version == '2015-07-01': @@ -296,7 +323,7 @@ def action_groups(self): else: raise ValueError("API version {} does not have operation group 'action_groups'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def activity_log_alerts(self): @@ -316,7 +343,7 @@ def activity_log_alerts(self): else: raise ValueError("API version {} does not have operation group 'activity_log_alerts'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def activity_logs(self): @@ -330,7 +357,7 @@ def activity_logs(self): else: raise ValueError("API version {} does not have operation group 'activity_logs'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def alert_rule_incidents(self): @@ -344,38 +371,38 @@ def alert_rule_incidents(self): else: raise ValueError("API version {} does not have operation group 'alert_rule_incidents'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def alert_rules(self): """Instance depends on the API version: - * 2015-04-01: :class:`AlertRulesOperations` - * 2015-07-01: :class:`AlertRulesOperations` + * 2014-04-01: :class:`AlertRulesOperations` * 2016-03-01: :class:`AlertRulesOperations` """ api_version = self._get_api_version('alert_rules') - if api_version == '2015-04-01': - from .v2015_04_01.operations import AlertRulesOperations as OperationClass - elif api_version == '2015-07-01': - from .v2015_07_01.operations import AlertRulesOperations as OperationClass + if api_version == '2014-04-01': + from .v2014_04_01.operations import AlertRulesOperations as OperationClass elif api_version == '2016-03-01': from .v2016_03_01.operations import AlertRulesOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'alert_rules'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def autoscale_settings(self): """Instance depends on the API version: + * 2014-04-01: :class:`AutoscaleSettingsOperations` * 2015-04-01: :class:`AutoscaleSettingsOperations` * 2021-05-01-preview: :class:`AutoscaleSettingsOperations` * 2022-10-01: :class:`AutoscaleSettingsOperations` """ api_version = self._get_api_version('autoscale_settings') - if api_version == '2015-04-01': + if api_version == '2014-04-01': + from .v2014_04_01.operations import AutoscaleSettingsOperations as OperationClass + elif api_version == '2015-04-01': from .v2015_04_01.operations import AutoscaleSettingsOperations as OperationClass elif api_version == '2021-05-01-preview': from .v2021_05_01_preview.operations import AutoscaleSettingsOperations as OperationClass @@ -384,7 +411,7 @@ def autoscale_settings(self): else: raise ValueError("API version {} does not have operation group 'autoscale_settings'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def azure_monitor_workspaces(self): @@ -398,7 +425,7 @@ def azure_monitor_workspaces(self): else: raise ValueError("API version {} does not have operation group 'azure_monitor_workspaces'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def baselines(self): @@ -415,7 +442,7 @@ def baselines(self): else: raise ValueError("API version {} does not have operation group 'baselines'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def data_collection_endpoints(self): @@ -435,7 +462,7 @@ def data_collection_endpoints(self): else: raise ValueError("API version {} does not have operation group 'data_collection_endpoints'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def data_collection_rule_associations(self): @@ -458,7 +485,7 @@ def data_collection_rule_associations(self): else: raise ValueError("API version {} does not have operation group 'data_collection_rule_associations'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def data_collection_rules(self): @@ -481,7 +508,7 @@ def data_collection_rules(self): else: raise ValueError("API version {} does not have operation group 'data_collection_rules'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def diagnostic_settings(self): @@ -498,7 +525,7 @@ def diagnostic_settings(self): else: raise ValueError("API version {} does not have operation group 'diagnostic_settings'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def diagnostic_settings_category(self): @@ -515,7 +542,7 @@ def diagnostic_settings_category(self): else: raise ValueError("API version {} does not have operation group 'diagnostic_settings_category'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def event_categories(self): @@ -529,7 +556,7 @@ def event_categories(self): else: raise ValueError("API version {} does not have operation group 'event_categories'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def guest_diagnostics_settings(self): @@ -543,7 +570,7 @@ def guest_diagnostics_settings(self): else: raise ValueError("API version {} does not have operation group 'guest_diagnostics_settings'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def guest_diagnostics_settings_association(self): @@ -557,7 +584,7 @@ def guest_diagnostics_settings_association(self): else: raise ValueError("API version {} does not have operation group 'guest_diagnostics_settings_association'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def log_profiles(self): @@ -571,7 +598,7 @@ def log_profiles(self): else: raise ValueError("API version {} does not have operation group 'log_profiles'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def management_group_diagnostic_settings(self): @@ -588,7 +615,7 @@ def management_group_diagnostic_settings(self): else: raise ValueError("API version {} does not have operation group 'management_group_diagnostic_settings'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def metric_alerts(self): @@ -602,7 +629,7 @@ def metric_alerts(self): else: raise ValueError("API version {} does not have operation group 'metric_alerts'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def metric_alerts_status(self): @@ -616,7 +643,7 @@ def metric_alerts_status(self): else: raise ValueError("API version {} does not have operation group 'metric_alerts_status'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def metric_definitions(self): @@ -642,7 +669,7 @@ def metric_definitions(self): else: raise ValueError("API version {} does not have operation group 'metric_definitions'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def metric_namespaces(self): @@ -656,7 +683,7 @@ def metric_namespaces(self): else: raise ValueError("API version {} does not have operation group 'metric_namespaces'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def metrics(self): @@ -679,7 +706,7 @@ def metrics(self): else: raise ValueError("API version {} does not have operation group 'metrics'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def monitor_operations(self): @@ -693,7 +720,7 @@ def monitor_operations(self): else: raise ValueError("API version {} does not have operation group 'monitor_operations'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def operations(self): @@ -713,7 +740,7 @@ def operations(self): else: raise ValueError("API version {} does not have operation group 'operations'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def predictive_metric(self): @@ -730,7 +757,7 @@ def predictive_metric(self): else: raise ValueError("API version {} does not have operation group 'predictive_metric'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def private_endpoint_connections(self): @@ -747,7 +774,7 @@ def private_endpoint_connections(self): else: raise ValueError("API version {} does not have operation group 'private_endpoint_connections'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def private_link_resources(self): @@ -764,7 +791,7 @@ def private_link_resources(self): else: raise ValueError("API version {} does not have operation group 'private_link_resources'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def private_link_scope_operation_status(self): @@ -781,7 +808,7 @@ def private_link_scope_operation_status(self): else: raise ValueError("API version {} does not have operation group 'private_link_scope_operation_status'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def private_link_scoped_resources(self): @@ -798,7 +825,7 @@ def private_link_scoped_resources(self): else: raise ValueError("API version {} does not have operation group 'private_link_scoped_resources'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def private_link_scopes(self): @@ -815,7 +842,7 @@ def private_link_scopes(self): else: raise ValueError("API version {} does not have operation group 'private_link_scopes'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def scheduled_query_rules(self): @@ -835,7 +862,7 @@ def scheduled_query_rules(self): else: raise ValueError("API version {} does not have operation group 'scheduled_query_rules'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def service_diagnostic_settings(self): @@ -852,7 +879,7 @@ def service_diagnostic_settings(self): else: raise ValueError("API version {} does not have operation group 'service_diagnostic_settings'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def subscription_diagnostic_settings(self): @@ -869,7 +896,7 @@ def subscription_diagnostic_settings(self): else: raise ValueError("API version {} does not have operation group 'subscription_diagnostic_settings'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def tenant_action_groups(self): @@ -883,7 +910,7 @@ def tenant_action_groups(self): else: raise ValueError("API version {} does not have operation group 'tenant_action_groups'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def tenant_activity_logs(self): @@ -897,7 +924,7 @@ def tenant_activity_logs(self): else: raise ValueError("API version {} does not have operation group 'tenant_activity_logs'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def vm_insights(self): @@ -911,7 +938,7 @@ def vm_insights(self): else: raise ValueError("API version {} does not have operation group 'vm_insights'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) def close(self): self._client.close() diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/_serialization.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/_serialization.py index 6b97ccd93a79..dc8692e6ec0f 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/_serialization.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/_serialization.py @@ -24,7 +24,6 @@ # # -------------------------------------------------------------------------- -# pylint: skip-file # pyright: reportUnnecessaryTypeIgnoreComment=false from base64 import b64decode, b64encode @@ -52,7 +51,6 @@ MutableMapping, Type, List, - Mapping, ) try: @@ -63,8 +61,8 @@ import isodate # type: ignore -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback -from azure.core.serialization import NULL as AzureCoreNull +from azure.core.exceptions import DeserializationError, SerializationError +from azure.core.serialization import NULL as CoreNull _BOM = codecs.BOM_UTF8.decode(encoding="utf-8") @@ -91,6 +89,8 @@ def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: :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 @@ -112,7 +112,7 @@ def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: 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: @@ -124,7 +124,7 @@ def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: 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 @@ -143,7 +143,9 @@ 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 @@ -153,6 +155,11 @@ def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], 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 @@ -170,13 +177,6 @@ def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], return None -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str - unicode_str = str - _LOGGER = logging.getLogger(__name__) try: @@ -189,15 +189,30 @@ class UTC(datetime.tzinfo): """Time Zone info for handling UTC""" def utcoffset(self, dt): - """UTF offset for UTC is 0.""" + """UTF offset for UTC is 0. + + :param datetime.datetime dt: The datetime + :returns: The offset + :rtype: datetime.timedelta + """ return datetime.timedelta(0) def tzname(self, dt): - """Timestamp representation.""" + """Timestamp representation. + + :param datetime.datetime dt: The datetime + :returns: The timestamp representation + :rtype: str + """ return "Z" def dst(self, dt): - """No daylight saving for UTC.""" + """No daylight saving for UTC. + + :param datetime.datetime dt: The datetime + :returns: The daylight saving time + :rtype: datetime.timedelta + """ return datetime.timedelta(hours=1) @@ -211,7 +226,7 @@ class _FixedOffset(datetime.tzinfo): # type: ignore :param datetime.timedelta offset: offset in timedelta format """ - def __init__(self, offset): + def __init__(self, offset) -> None: self.__offset = offset def utcoffset(self, dt): @@ -240,24 +255,26 @@ def __getinitargs__(self): _FLATTEN = re.compile(r"(? None: - self.additional_properties: Dict[str, Any] = {} - for k in kwargs: + 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): @@ -305,13 +329,23 @@ def __init__(self, **kwargs: Any) -> None: setattr(self, k, kwargs[k]) def __eq__(self, other: Any) -> bool: - """Compare objects by comparing all attributes.""" + """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: Any) -> bool: - """Compare objects by comparing all attributes.""" + """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) -> str: @@ -331,7 +365,11 @@ def is_xml_model(cls) -> bool: @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 # type: ignore except AttributeError: @@ -340,7 +378,7 @@ def _create_xml_node(cls): return _create_xml_node(xml_map.get("name", cls.__name__), xml_map.get("prefix", None), xml_map.get("ns", None)) def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: - """Return the JSON that would be sent to azure from this model. + """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)`. @@ -351,14 +389,14 @@ def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: :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: bool = True, - key_transformer: Callable[ - [str, Dict[str, Any], Any], Any - ] = attribute_transformer, + key_transformer: Callable[[str, Dict[str, Any], Any], Any] = attribute_transformer, **kwargs: Any ) -> JSON: """Return a dict that can be serialized using json.dump. @@ -387,12 +425,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): @@ -402,7 +443,7 @@ 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 @@ -415,9 +456,10 @@ def deserialize(cls: Type[ModelType], data: Any, content_type: Optional[str] = N :param str content_type: JSON by default, set application/xml if XML. :returns: An instance of this model :raises: DeserializationError if something went wrong + :rtype: ModelType """ 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( @@ -433,9 +475,11 @@ def from_dict( 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 + :rtype: ModelType """ deserializer = Deserializer(cls._infer_class_models()) deserializer.key_extractors = ( # type: ignore @@ -447,7 +491,7 @@ def from_dict( 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): @@ -455,21 +499,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.update(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: @@ -508,11 +556,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(object): # pylint: disable=too-many-public-methods """Request object model serializer.""" basic_types = {str: "str", int: "int", bool: "bool", float: "float"} @@ -547,7 +597,7 @@ class Serializer(object): "multiple": lambda x, y: x % y != 0, } - def __init__(self, classes: Optional[Mapping[str, Type[ModelType]]]=None): + def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: self.serialize_type = { "iso-8601": Serializer.serialize_iso, "rfc-1123": Serializer.serialize_rfc, @@ -563,17 +613,20 @@ def __init__(self, classes: Optional[Mapping[str, Type[ModelType]]]=None): "[]": self.serialize_iter, "{}": self.serialize_dict, } - self.dependencies: Dict[str, Type[ModelType]] = 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. + :returns: The serialized data. """ key_transformer = kwargs.get("key_transformer", self.key_transformer) keep_readonly = kwargs.get("keep_readonly", False) @@ -599,12 +652,14 @@ 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"] == "": @@ -640,7 +695,8 @@ def _serialize(self, target_obj, data_type=None, **kwargs): if isinstance(new_attr, list): serialized.extend(new_attr) # type: ignore elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. + # If 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 @@ -651,7 +707,7 @@ def _serialize(self, target_obj, data_type=None, **kwargs): 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) + local_node.text = str(new_attr) serialized.append(local_node) # type: ignore else: # JSON for k in reversed(keys): # type: ignore @@ -664,23 +720,24 @@ def _serialize(self, target_obj, data_type=None, **kwargs): _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 + :returns: The serialized request body """ # Just in case this is a dict @@ -709,18 +766,20 @@ 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 + :returns: The serialized URL path :raises: TypeError if serialization fails. :raises: ValueError if data is None """ @@ -734,28 +793,27 @@ def url(self, name, data, data_type, **kwargs): 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 + :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) @@ -765,19 +823,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 + :returns: The serialized header """ try: if data_type in ["[str]"]: @@ -786,32 +845,31 @@ 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. + :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 AzureCoreNull: + 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 @@ -826,12 +884,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 @@ -847,23 +904,26 @@ 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 """ 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 + return eval(data_type)(data) # nosec # pylint: disable=eval-used @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 @@ -877,8 +937,7 @@ def serialize_unicode(cls, data): 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. @@ -888,13 +947,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.") @@ -906,9 +965,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) @@ -944,16 +1008,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: @@ -968,7 +1033,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 @@ -976,6 +1041,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 @@ -986,7 +1052,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) @@ -1000,7 +1066,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: @@ -1031,56 +1097,61 @@ def serialize_enum(attr, enum_obj=None): try: enum_obj(result) # type: ignore return result - except ValueError: + 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) @@ -1088,11 +1159,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) @@ -1102,30 +1174,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. + :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], @@ -1138,12 +1212,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. + :return: serialized iso """ if isinstance(attr, str): attr = isodate.parse_datetime(attr) @@ -1163,19 +1238,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 + :return: serialied unix """ if isinstance(attr, int): return attr @@ -1183,11 +1259,11 @@ 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 @@ -1202,14 +1278,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 @@ -1223,7 +1300,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:]) @@ -1231,17 +1307,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) @@ -1278,7 +1366,7 @@ def _extract_name_from_internal_type(internal_type): 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 @@ -1330,22 +1418,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( # pylint: disable=line-too-long + 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: @@ -1362,9 +1449,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: Optional[Mapping[str, Type[ModelType]]]=None): + def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: self.deserialize_type = { "iso-8601": Deserializer.deserialize_iso, "rfc-1123": Deserializer.deserialize_rfc, @@ -1384,7 +1471,7 @@ def __init__(self, classes: Optional[Mapping[str, Type[ModelType]]]=None): "duration": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } - self.dependencies: Dict[str, Type[ModelType]] = 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 @@ -1402,11 +1489,12 @@ def __call__(self, target_obj, response_data, content_type=None): :param str content_type: Swagger "produces" if available. :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 @@ -1415,12 +1503,13 @@ def _deserialize(self, target_obj, data): :param object data: Object to deserialize. :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) @@ -1437,15 +1526,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 # type: ignore + 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"... @@ -1474,10 +1563,9 @@ def _deserialize(self, target_obj, data): d_attrs[attr] = value except (AttributeError, TypeError, KeyError) as err: msg = "Unable to deserialize to object: " + class_name # type: ignore - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) + 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: @@ -1504,18 +1592,20 @@ def _classify_target(self, target, data): :param str target: The target object type to deserialize to. :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__ # type: ignore @@ -1530,10 +1620,12 @@ def failsafe_deserialize(self, target_obj, data, content_type=None): :param str target_obj: The target object type to deserialize to. :param str/dict data: The response data to deserialize. :param str content_type: Swagger "produces" if available. + :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 ) @@ -1551,10 +1643,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", {}) @@ -1571,21 +1665,28 @@ 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"): + 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() if v.get("readonly") # pylint: disable=protected-access + ] + const = [ + k for k, v in response._validation.items() if v.get("constant") # pylint: disable=protected-access + ] 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: @@ -1595,7 +1696,7 @@ def _instantiate_model(self, response, attrs, additional_properties=None): return response_obj except TypeError as err: msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) # type: ignore - raise DeserializationError(msg + str(err)) + raise DeserializationError(msg + str(err)) from err else: try: for attr, value in attrs.items(): @@ -1604,15 +1705,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. :return: Deserialized object. + :rtype: object """ if data is None: return data @@ -1626,7 +1728,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) @@ -1645,15 +1751,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: @@ -1670,6 +1776,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): @@ -1680,11 +1787,12 @@ 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. """ @@ -1693,7 +1801,7 @@ def deserialize_object(self, attr, **kwargs): 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: @@ -1719,11 +1827,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 @@ -1731,6 +1838,7 @@ 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. """ @@ -1742,24 +1850,23 @@ 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 + return eval(data_type)(attr) # nosec # pylint: disable=eval-used @staticmethod def deserialize_unicode(data): @@ -1767,6 +1874,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, @@ -1780,8 +1888,7 @@ def deserialize_unicode(data): return data except NameError: return str(data) - else: - return str(data) + return str(data) @staticmethod def deserialize_enum(data, enum_obj): @@ -1793,6 +1900,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: @@ -1801,12 +1909,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: @@ -1822,6 +1929,7 @@ 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. """ @@ -1834,6 +1942,7 @@ 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. """ @@ -1849,22 +1958,24 @@ def deserialize_decimal(attr): """Deserialize string into Decimal object. :param str attr: response string to be deserialized. - :rtype: Decimal + :return: Deserialized decimal :raises: DeserializationError if string format invalid. + :rtype: decimal """ if isinstance(attr, ET.Element): attr = attr.text try: - return decimal.Decimal(attr) # type: ignore + 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. """ @@ -1877,6 +1988,7 @@ 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. """ @@ -1886,15 +1998,15 @@ 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. """ @@ -1903,13 +2015,14 @@ def deserialize_date(attr): 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. """ @@ -1924,6 +2037,7 @@ 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. """ @@ -1938,15 +2052,15 @@ def deserialize_rfc(attr): 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. """ @@ -1975,9 +2089,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): @@ -1985,15 +2098,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 """ if isinstance(attr, ET.Element): 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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/aio/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/aio/_configuration.py index a1914da0a578..088c188be4d2 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/aio/_configuration.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/aio/_configuration.py @@ -10,7 +10,6 @@ # -------------------------------------------------------------------------- from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy @@ -20,7 +19,7 @@ # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MonitorManagementClientConfiguration(Configuration): +class MonitorManagementClientConfiguration: """Configuration for MonitorManagementClient. Note that all parameters used to create this instance are saved as instance @@ -42,12 +41,12 @@ def __init__( raise ValueError("Parameter 'credential' must not be None.") if subscription_id is None: raise ValueError("Parameter 'subscription_id' must not be None.") - super(MonitorManagementClientConfiguration, self).__init__(**kwargs) self.credential = credential self.subscription_id = subscription_id self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) kwargs.setdefault('sdk_moniker', 'azure-mgmt-monitor/{}'.format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure( diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/aio/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/aio/_monitor_management_client.py index fa4aca79c769..c879f45d5827 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/aio/_monitor_management_client.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/aio/_monitor_management_client.py @@ -10,8 +10,11 @@ # -------------------------------------------------------------------------- from typing import Any, Optional, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.mgmt.core import AsyncARMPipelineClient +from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy from azure.profiles import KnownProfiles, ProfileDefinition from azure.profiles.multiapiclient import MultiApiClientMixin @@ -106,8 +109,28 @@ def __init__( profile: KnownProfiles = KnownProfiles.default, **kwargs: Any ) -> None: + if api_version: + kwargs.setdefault('api_version', api_version) self._config = MonitorManagementClientConfiguration(credential, subscription_id, **kwargs) - self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **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(base_url=base_url, policies=_policies, **kwargs) super(MonitorManagementClient, self).__init__( api_version=api_version, profile=profile @@ -121,6 +144,7 @@ def _models_dict(cls, api_version): def models(cls, api_version=DEFAULT_API_VERSION): """Module depends on the API version: + * 2014-04-01: :mod:`v2014_04_01.models` * 2015-04-01: :mod:`v2015_04_01.models` * 2015-07-01: :mod:`v2015_07_01.models` * 2016-03-01: :mod:`v2016_03_01.models` @@ -156,7 +180,10 @@ def models(cls, api_version=DEFAULT_API_VERSION): * 2023-01-01: :mod:`v2023_01_01.models` * 2023-03-01-preview: :mod:`v2023_03_01_preview.models` """ - if api_version == '2015-04-01': + if api_version == '2014-04-01': + from ..v2014_04_01 import models + return models + elif api_version == '2015-04-01': from ..v2015_04_01 import models return models elif api_version == '2015-07-01': @@ -296,7 +323,7 @@ def action_groups(self): else: raise ValueError("API version {} does not have operation group 'action_groups'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def activity_log_alerts(self): @@ -316,7 +343,7 @@ def activity_log_alerts(self): else: raise ValueError("API version {} does not have operation group 'activity_log_alerts'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def activity_logs(self): @@ -330,7 +357,7 @@ def activity_logs(self): else: raise ValueError("API version {} does not have operation group 'activity_logs'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def alert_rule_incidents(self): @@ -344,38 +371,38 @@ def alert_rule_incidents(self): else: raise ValueError("API version {} does not have operation group 'alert_rule_incidents'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def alert_rules(self): """Instance depends on the API version: - * 2015-04-01: :class:`AlertRulesOperations` - * 2015-07-01: :class:`AlertRulesOperations` + * 2014-04-01: :class:`AlertRulesOperations` * 2016-03-01: :class:`AlertRulesOperations` """ api_version = self._get_api_version('alert_rules') - if api_version == '2015-04-01': - from ..v2015_04_01.aio.operations import AlertRulesOperations as OperationClass - elif api_version == '2015-07-01': - from ..v2015_07_01.aio.operations import AlertRulesOperations as OperationClass + if api_version == '2014-04-01': + from ..v2014_04_01.aio.operations import AlertRulesOperations as OperationClass elif api_version == '2016-03-01': from ..v2016_03_01.aio.operations import AlertRulesOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'alert_rules'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def autoscale_settings(self): """Instance depends on the API version: + * 2014-04-01: :class:`AutoscaleSettingsOperations` * 2015-04-01: :class:`AutoscaleSettingsOperations` * 2021-05-01-preview: :class:`AutoscaleSettingsOperations` * 2022-10-01: :class:`AutoscaleSettingsOperations` """ api_version = self._get_api_version('autoscale_settings') - if api_version == '2015-04-01': + if api_version == '2014-04-01': + from ..v2014_04_01.aio.operations import AutoscaleSettingsOperations as OperationClass + elif api_version == '2015-04-01': from ..v2015_04_01.aio.operations import AutoscaleSettingsOperations as OperationClass elif api_version == '2021-05-01-preview': from ..v2021_05_01_preview.aio.operations import AutoscaleSettingsOperations as OperationClass @@ -384,7 +411,7 @@ def autoscale_settings(self): else: raise ValueError("API version {} does not have operation group 'autoscale_settings'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def azure_monitor_workspaces(self): @@ -398,7 +425,7 @@ def azure_monitor_workspaces(self): else: raise ValueError("API version {} does not have operation group 'azure_monitor_workspaces'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def baselines(self): @@ -415,7 +442,7 @@ def baselines(self): else: raise ValueError("API version {} does not have operation group 'baselines'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def data_collection_endpoints(self): @@ -435,7 +462,7 @@ def data_collection_endpoints(self): else: raise ValueError("API version {} does not have operation group 'data_collection_endpoints'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def data_collection_rule_associations(self): @@ -458,7 +485,7 @@ def data_collection_rule_associations(self): else: raise ValueError("API version {} does not have operation group 'data_collection_rule_associations'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def data_collection_rules(self): @@ -481,7 +508,7 @@ def data_collection_rules(self): else: raise ValueError("API version {} does not have operation group 'data_collection_rules'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def diagnostic_settings(self): @@ -498,7 +525,7 @@ def diagnostic_settings(self): else: raise ValueError("API version {} does not have operation group 'diagnostic_settings'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def diagnostic_settings_category(self): @@ -515,7 +542,7 @@ def diagnostic_settings_category(self): else: raise ValueError("API version {} does not have operation group 'diagnostic_settings_category'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def event_categories(self): @@ -529,7 +556,7 @@ def event_categories(self): else: raise ValueError("API version {} does not have operation group 'event_categories'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def guest_diagnostics_settings(self): @@ -543,7 +570,7 @@ def guest_diagnostics_settings(self): else: raise ValueError("API version {} does not have operation group 'guest_diagnostics_settings'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def guest_diagnostics_settings_association(self): @@ -557,7 +584,7 @@ def guest_diagnostics_settings_association(self): else: raise ValueError("API version {} does not have operation group 'guest_diagnostics_settings_association'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def log_profiles(self): @@ -571,7 +598,7 @@ def log_profiles(self): else: raise ValueError("API version {} does not have operation group 'log_profiles'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def management_group_diagnostic_settings(self): @@ -588,7 +615,7 @@ def management_group_diagnostic_settings(self): else: raise ValueError("API version {} does not have operation group 'management_group_diagnostic_settings'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def metric_alerts(self): @@ -602,7 +629,7 @@ def metric_alerts(self): else: raise ValueError("API version {} does not have operation group 'metric_alerts'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def metric_alerts_status(self): @@ -616,7 +643,7 @@ def metric_alerts_status(self): else: raise ValueError("API version {} does not have operation group 'metric_alerts_status'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def metric_definitions(self): @@ -642,7 +669,7 @@ def metric_definitions(self): else: raise ValueError("API version {} does not have operation group 'metric_definitions'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def metric_namespaces(self): @@ -656,7 +683,7 @@ def metric_namespaces(self): else: raise ValueError("API version {} does not have operation group 'metric_namespaces'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def metrics(self): @@ -679,7 +706,7 @@ def metrics(self): else: raise ValueError("API version {} does not have operation group 'metrics'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def monitor_operations(self): @@ -693,7 +720,7 @@ def monitor_operations(self): else: raise ValueError("API version {} does not have operation group 'monitor_operations'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def operations(self): @@ -713,7 +740,7 @@ def operations(self): else: raise ValueError("API version {} does not have operation group 'operations'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def predictive_metric(self): @@ -730,7 +757,7 @@ def predictive_metric(self): else: raise ValueError("API version {} does not have operation group 'predictive_metric'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def private_endpoint_connections(self): @@ -747,7 +774,7 @@ def private_endpoint_connections(self): else: raise ValueError("API version {} does not have operation group 'private_endpoint_connections'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def private_link_resources(self): @@ -764,7 +791,7 @@ def private_link_resources(self): else: raise ValueError("API version {} does not have operation group 'private_link_resources'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def private_link_scope_operation_status(self): @@ -781,7 +808,7 @@ def private_link_scope_operation_status(self): else: raise ValueError("API version {} does not have operation group 'private_link_scope_operation_status'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def private_link_scoped_resources(self): @@ -798,7 +825,7 @@ def private_link_scoped_resources(self): else: raise ValueError("API version {} does not have operation group 'private_link_scoped_resources'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def private_link_scopes(self): @@ -815,7 +842,7 @@ def private_link_scopes(self): else: raise ValueError("API version {} does not have operation group 'private_link_scopes'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def scheduled_query_rules(self): @@ -835,7 +862,7 @@ def scheduled_query_rules(self): else: raise ValueError("API version {} does not have operation group 'scheduled_query_rules'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def service_diagnostic_settings(self): @@ -852,7 +879,7 @@ def service_diagnostic_settings(self): else: raise ValueError("API version {} does not have operation group 'service_diagnostic_settings'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def subscription_diagnostic_settings(self): @@ -869,7 +896,7 @@ def subscription_diagnostic_settings(self): else: raise ValueError("API version {} does not have operation group 'subscription_diagnostic_settings'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def tenant_action_groups(self): @@ -883,7 +910,7 @@ def tenant_action_groups(self): else: raise ValueError("API version {} does not have operation group 'tenant_action_groups'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def tenant_activity_logs(self): @@ -897,7 +924,7 @@ def tenant_activity_logs(self): else: raise ValueError("API version {} does not have operation group 'tenant_activity_logs'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) @property def vm_insights(self): @@ -911,7 +938,7 @@ def vm_insights(self): else: raise ValueError("API version {} does not have operation group 'vm_insights'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version))) + return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) async def close(self): await self._client.close() diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2014_04_01/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2014_04_01/__init__.py new file mode 100644 index 000000000000..42cc62301757 --- /dev/null +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2014_04_01/__init__.py @@ -0,0 +1,32 @@ +# 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. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._monitor_management_client import MonitorManagementClient # type: ignore +from ._version import VERSION + +__version__ = VERSION + +try: + from ._patch import __all__ as _patch_all + from ._patch import * +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "MonitorManagementClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore + +_patch_sdk() diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2014_04_01/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2014_04_01/_configuration.py new file mode 100644 index 000000000000..2dc2946641b9 --- /dev/null +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2014_04_01/_configuration.py @@ -0,0 +1,64 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, TYPE_CHECKING + +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy + +from ._version import VERSION + +if TYPE_CHECKING: + from azure.core.credentials import TokenCredential + + +class MonitorManagementClientConfiguration: # pylint: disable=too-many-instance-attributes + """Configuration for MonitorManagementClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :keyword api_version: Api Version. Default value is "2014-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: + api_version: str = kwargs.pop("api_version", "2014-04-01") + + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + + self.credential = credential + self.subscription_id = subscription_id + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-monitor/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.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( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2014_04_01/_metadata.json b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2014_04_01/_metadata.json new file mode 100644 index 000000000000..441614babbbb --- /dev/null +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2014_04_01/_metadata.json @@ -0,0 +1,111 @@ +{ + "chosen_version": "2014-04-01", + "total_api_version_list": ["2014-04-01"], + "client": { + "name": "MonitorManagementClient", + "filename": "_monitor_management_client", + "description": "Monitor Management Client.", + "host_value": "\"https://management.azure.com\"", + "parameterized_host_template": null, + "azure_arm": true, + "has_public_lro_operations": false, + "client_side_validation": false, + "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"sdkcore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMAutoResourceProviderRegistrationPolicy\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}, \"stdlib\": {\"typing_extensions\": [\"Self\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"sdkcore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"AsyncARMAutoResourceProviderRegistrationPolicy\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}, \"stdlib\": {\"typing_extensions\": [\"Self\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + }, + "global_parameters": { + "sync": { + "credential": { + "signature": "credential: \"TokenCredential\",", + "description": "Credential needed for the client to connect to Azure. Required.", + "docstring_type": "~azure.core.credentials.TokenCredential", + "required": true, + "method_location": "positional" + }, + "subscription_id": { + "signature": "subscription_id: str,", + "description": "The ID of the target subscription. Required.", + "docstring_type": "str", + "required": true, + "method_location": "positional" + } + }, + "async": { + "credential": { + "signature": "credential: \"AsyncTokenCredential\",", + "description": "Credential needed for the client to connect to Azure. Required.", + "docstring_type": "~azure.core.credentials_async.AsyncTokenCredential", + "required": true + }, + "subscription_id": { + "signature": "subscription_id: str,", + "description": "The ID of the target subscription. Required.", + "docstring_type": "str", + "required": true + } + }, + "constant": { + }, + "call": "credential, subscription_id", + "service_client_specific": { + "sync": { + "api_version": { + "signature": "api_version: Optional[str]=None,", + "description": "API version to use if no profile is provided, or if missing in profile.", + "docstring_type": "str", + "required": false, + "method_location": "positional" + }, + "base_url": { + "signature": "base_url: str = \"https://management.azure.com\",", + "description": "Service URL", + "docstring_type": "str", + "required": false, + "method_location": "positional" + }, + "profile": { + "signature": "profile: KnownProfiles=KnownProfiles.default,", + "description": "A profile definition, from KnownProfiles to dict.", + "docstring_type": "azure.profiles.KnownProfiles", + "required": false, + "method_location": "positional" + } + }, + "async": { + "api_version": { + "signature": "api_version: Optional[str] = None,", + "description": "API version to use if no profile is provided, or if missing in profile.", + "docstring_type": "str", + "required": false, + "method_location": "positional" + }, + "base_url": { + "signature": "base_url: str = \"https://management.azure.com\",", + "description": "Service URL", + "docstring_type": "str", + "required": false, + "method_location": "positional" + }, + "profile": { + "signature": "profile: KnownProfiles = KnownProfiles.default,", + "description": "A profile definition, from KnownProfiles to dict.", + "docstring_type": "azure.profiles.KnownProfiles", + "required": false, + "method_location": "positional" + } + } + } + }, + "config": { + "credential": true, + "credential_scopes": ["https://management.azure.com/.default"], + "credential_call_sync": "ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", + "credential_call_async": "AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", + "sync_imports": "{\"regular\": {\"sdkcore\": {\"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"regular\": {\"sdkcore\": {\"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + }, + "operation_groups": { + "alert_rules": "AlertRulesOperations", + "autoscale_settings": "AutoscaleSettingsOperations" + } +} diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2014_04_01/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2014_04_01/_monitor_management_client.py new file mode 100644 index 000000000000..1076c377b079 --- /dev/null +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2014_04_01/_monitor_management_client.py @@ -0,0 +1,117 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +from typing import Any, TYPE_CHECKING +from typing_extensions import Self + +from azure.core.pipeline import policies +from azure.core.rest import HttpRequest, HttpResponse +from azure.mgmt.core import ARMPipelineClient +from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy + +from . import models as _models +from .._serialization import Deserializer, Serializer +from ._configuration import MonitorManagementClientConfiguration +from .operations import AlertRulesOperations, AutoscaleSettingsOperations + +if TYPE_CHECKING: + from azure.core.credentials import TokenCredential + + +class MonitorManagementClient: + """Monitor Management Client. + + :ivar alert_rules: AlertRulesOperations operations + :vartype alert_rules: azure.mgmt.monitor.v2014_04_01.operations.AlertRulesOperations + :ivar autoscale_settings: AutoscaleSettingsOperations operations + :vartype autoscale_settings: + azure.mgmt.monitor.v2014_04_01.operations.AutoscaleSettingsOperations + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials.TokenCredential + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword api_version: Api Version. Default value is "2014-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, + base_url: str = "https://management.azure.com", + **kwargs: Any + ) -> None: + self._config = MonitorManagementClientConfiguration( + credential=credential, subscription_id=subscription_id, **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), + 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=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.alert_rules = AlertRulesOperations( + self._client, self._config, self._serialize, self._deserialize, "2014-04-01" + ) + self.autoscale_settings = AutoscaleSettingsOperations( + self._client, self._config, self._serialize, self._deserialize, "2014-04-01" + ) + + 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 + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.HttpResponse + """ + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore + + def close(self) -> None: + self._client.close() + + def __enter__(self) -> Self: + self._client.__enter__() + return self + + def __exit__(self, *exc_details: Any) -> None: + self._client.__exit__(*exc_details) diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2014_04_01/_patch.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2014_04_01/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2014_04_01/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2014_04_01/_version.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2014_04_01/_version.py new file mode 100644 index 000000000000..e5754a47ce68 --- /dev/null +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2014_04_01/_version.py @@ -0,0 +1,9 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +VERSION = "1.0.0b1" diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2014_04_01/aio/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2014_04_01/aio/__init__.py new file mode 100644 index 000000000000..3df30ff42149 --- /dev/null +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2014_04_01/aio/__init__.py @@ -0,0 +1,29 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._monitor_management_client import MonitorManagementClient # type: ignore + +try: + from ._patch import __all__ as _patch_all + from ._patch import * +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "MonitorManagementClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore + +_patch_sdk() diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2014_04_01/aio/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2014_04_01/aio/_configuration.py new file mode 100644 index 000000000000..b16df57d5ca7 --- /dev/null +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2014_04_01/aio/_configuration.py @@ -0,0 +1,64 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, TYPE_CHECKING + +from azure.core.pipeline import policies +from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy + +from .._version import VERSION + +if TYPE_CHECKING: + from azure.core.credentials_async import AsyncTokenCredential + + +class MonitorManagementClientConfiguration: # pylint: disable=too-many-instance-attributes + """Configuration for MonitorManagementClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :keyword api_version: Api Version. Default value is "2014-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: + api_version: str = kwargs.pop("api_version", "2014-04-01") + + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + + self.credential = credential + self.subscription_id = subscription_id + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-monitor/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.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( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2014_04_01/aio/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2014_04_01/aio/_monitor_management_client.py new file mode 100644 index 000000000000..f7a16be933c1 --- /dev/null +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2014_04_01/aio/_monitor_management_client.py @@ -0,0 +1,119 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +from typing import Any, Awaitable, TYPE_CHECKING +from typing_extensions import Self + +from azure.core.pipeline import policies +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.mgmt.core import AsyncARMPipelineClient +from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy + +from .. import models as _models +from ..._serialization import Deserializer, Serializer +from ._configuration import MonitorManagementClientConfiguration +from .operations import AlertRulesOperations, AutoscaleSettingsOperations + +if TYPE_CHECKING: + from azure.core.credentials_async import AsyncTokenCredential + + +class MonitorManagementClient: + """Monitor Management Client. + + :ivar alert_rules: AlertRulesOperations operations + :vartype alert_rules: azure.mgmt.monitor.v2014_04_01.aio.operations.AlertRulesOperations + :ivar autoscale_settings: AutoscaleSettingsOperations operations + :vartype autoscale_settings: + azure.mgmt.monitor.v2014_04_01.aio.operations.AutoscaleSettingsOperations + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param subscription_id: The ID of the target subscription. Required. + :type subscription_id: str + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword api_version: Api Version. Default value is "2014-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, + base_url: str = "https://management.azure.com", + **kwargs: Any + ) -> None: + self._config = MonitorManagementClientConfiguration( + credential=credential, subscription_id=subscription_id, **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=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.alert_rules = AlertRulesOperations( + self._client, self._config, self._serialize, self._deserialize, "2014-04-01" + ) + self.autoscale_settings = AutoscaleSettingsOperations( + self._client, self._config, self._serialize, self._deserialize, "2014-04-01" + ) + + 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 + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = await client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.AsyncHttpResponse + """ + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore + + async def close(self) -> None: + await self._client.close() + + async def __aenter__(self) -> Self: + await self._client.__aenter__() + return self + + async def __aexit__(self, *exc_details: Any) -> None: + await self._client.__aexit__(*exc_details) diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2014_04_01/aio/_patch.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2014_04_01/aio/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2014_04_01/aio/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2014_04_01/aio/operations/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2014_04_01/aio/operations/__init__.py new file mode 100644 index 000000000000..4d9f261f8722 --- /dev/null +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2014_04_01/aio/operations/__init__.py @@ -0,0 +1,27 @@ +# 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. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._alert_rules_operations import AlertRulesOperations # type: ignore +from ._autoscale_settings_operations import AutoscaleSettingsOperations # type: ignore + +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "AlertRulesOperations", + "AutoscaleSettingsOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/aio/operations/_alert_rules_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2014_04_01/aio/operations/_alert_rules_operations.py similarity index 73% rename from sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/aio/operations/_alert_rules_operations.py rename to sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2014_04_01/aio/operations/_alert_rules_operations.py index 01f85a07da2c..5524e0aa7dc2 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/aio/operations/_alert_rules_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2014_04_01/aio/operations/_alert_rules_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,7 +5,10 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( @@ -18,15 +20,13 @@ 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 ...operations._alert_rules_operations import ( build_create_or_update_request, build_delete_request, @@ -36,6 +36,10 @@ build_update_request, ) +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -46,7 +50,7 @@ class AlertRulesOperations: **DO NOT** instantiate this class directly. Instead, you should access the following operations through - :class:`~azure.mgmt.monitor.v2015_07_01.aio.MonitorManagementClient`'s + :class:`~azure.mgmt.monitor.v2014_04_01.aio.MonitorManagementClient`'s :attr:`alert_rules` attribute. """ @@ -58,6 +62,7 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @overload async def create_or_update( @@ -77,13 +82,12 @@ async def create_or_update( :param rule_name: The name of the rule. Required. :type rule_name: str :param parameters: The parameters of the rule to create or update. Required. - :type parameters: ~azure.mgmt.monitor.v2015_07_01.models.AlertRuleResource + :type parameters: ~azure.mgmt.monitor.v2014_04_01.models.AlertRuleResource :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: AlertRuleResource or the result of cls(response) - :rtype: ~azure.mgmt.monitor.v2015_07_01.models.AlertRuleResource + :rtype: ~azure.mgmt.monitor.v2014_04_01.models.AlertRuleResource :raises ~azure.core.exceptions.HttpResponseError: """ @@ -92,7 +96,7 @@ async def create_or_update( self, resource_group_name: str, rule_name: str, - parameters: IO, + parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -105,19 +109,22 @@ async def create_or_update( :param rule_name: The name of the rule. Required. :type rule_name: str :param parameters: The parameters of the rule to create or update. Required. - :type parameters: IO + :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: AlertRuleResource or the result of cls(response) - :rtype: ~azure.mgmt.monitor.v2015_07_01.models.AlertRuleResource + :rtype: ~azure.mgmt.monitor.v2014_04_01.models.AlertRuleResource :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async async def create_or_update( - self, resource_group_name: str, rule_name: str, parameters: Union[_models.AlertRuleResource, IO], **kwargs: Any + self, + resource_group_name: str, + rule_name: str, + parameters: Union[_models.AlertRuleResource, IO[bytes]], + **kwargs: Any ) -> _models.AlertRuleResource: """Creates or updates a classic metric alert rule. @@ -127,17 +134,13 @@ async def create_or_update( :param rule_name: The name of the rule. Required. :type rule_name: str :param parameters: The parameters of the rule to create or update. Is either a - AlertRuleResource type or a IO type. Required. - :type parameters: ~azure.mgmt.monitor.v2015_07_01.models.AlertRuleResource 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 + AlertRuleResource type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.monitor.v2014_04_01.models.AlertRuleResource or IO[bytes] :return: AlertRuleResource or the result of cls(response) - :rtype: ~azure.mgmt.monitor.v2015_07_01.models.AlertRuleResource + :rtype: ~azure.mgmt.monitor.v2014_04_01.models.AlertRuleResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -148,19 +151,19 @@ async def create_or_update( _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", "2014-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2014-04-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.AlertRuleResource] = 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, "AlertRuleResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, rule_name=rule_name, subscription_id=self._config.subscription_id, @@ -168,16 +171,14 @@ async def create_or_update( 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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -187,25 +188,15 @@ async def create_or_update( 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("AlertRuleResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("AlertRuleResource", pipeline_response) + deserialized = self._deserialize("AlertRuleResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/alertrules/{ruleName}" - } - @distributed_trace_async - async def delete( # pylint: disable=inconsistent-return-statements - self, resource_group_name: str, rule_name: str, **kwargs: Any - ) -> None: + async def delete(self, resource_group_name: str, rule_name: str, **kwargs: Any) -> None: """Deletes a classic metric alert rule. :param resource_group_name: The name of the resource group. The name is case insensitive. @@ -213,12 +204,11 @@ async def delete( # pylint: disable=inconsistent-return-statements :type resource_group_name: str :param rule_name: The name of the rule. Required. :type 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, @@ -229,24 +219,22 @@ async def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2014-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2014-04-01")) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, rule_name=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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -257,11 +245,7 @@ async def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/alertrules/{ruleName}" - } + return cls(pipeline_response, None, {}) # type: ignore @distributed_trace_async async def get(self, resource_group_name: str, rule_name: str, **kwargs: Any) -> _models.AlertRuleResource: @@ -272,12 +256,11 @@ async def get(self, resource_group_name: str, rule_name: str, **kwargs: Any) -> :type resource_group_name: str :param rule_name: The name of the rule. Required. :type rule_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: AlertRuleResource or the result of cls(response) - :rtype: ~azure.mgmt.monitor.v2015_07_01.models.AlertRuleResource + :rtype: ~azure.mgmt.monitor.v2014_04_01.models.AlertRuleResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -288,24 +271,22 @@ async def get(self, resource_group_name: str, rule_name: str, **kwargs: Any) -> _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2014-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2014-04-01")) cls: ClsType[_models.AlertRuleResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, rule_name=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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -315,16 +296,12 @@ async def get(self, resource_group_name: str, rule_name: str, **kwargs: Any) -> error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("AlertRuleResource", pipeline_response) + deserialized = self._deserialize("AlertRuleResource", 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.Insights/alertrules/{ruleName}" - } + return deserialized # type: ignore @overload async def update( @@ -345,13 +322,12 @@ async def update( :param rule_name: The name of the rule. Required. :type rule_name: str :param alert_rules_resource: Parameters supplied to the operation. Required. - :type alert_rules_resource: ~azure.mgmt.monitor.v2015_07_01.models.AlertRuleResourcePatch + :type alert_rules_resource: ~azure.mgmt.monitor.v2014_04_01.models.AlertRuleResourcePatch :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: AlertRuleResource or the result of cls(response) - :rtype: ~azure.mgmt.monitor.v2015_07_01.models.AlertRuleResource + :rtype: ~azure.mgmt.monitor.v2014_04_01.models.AlertRuleResource :raises ~azure.core.exceptions.HttpResponseError: """ @@ -360,7 +336,7 @@ async def update( self, resource_group_name: str, rule_name: str, - alert_rules_resource: IO, + alert_rules_resource: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -374,13 +350,12 @@ async def update( :param rule_name: The name of the rule. Required. :type rule_name: str :param alert_rules_resource: Parameters supplied to the operation. Required. - :type alert_rules_resource: IO + :type alert_rules_resource: 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: AlertRuleResource or the result of cls(response) - :rtype: ~azure.mgmt.monitor.v2015_07_01.models.AlertRuleResource + :rtype: ~azure.mgmt.monitor.v2014_04_01.models.AlertRuleResource :raises ~azure.core.exceptions.HttpResponseError: """ @@ -389,7 +364,7 @@ async def update( self, resource_group_name: str, rule_name: str, - alert_rules_resource: Union[_models.AlertRuleResourcePatch, IO], + alert_rules_resource: Union[_models.AlertRuleResourcePatch, IO[bytes]], **kwargs: Any ) -> _models.AlertRuleResource: """Updates an existing classic metric AlertRuleResource. To update other fields use the @@ -401,17 +376,14 @@ async def update( :param rule_name: The name of the rule. Required. :type rule_name: str :param alert_rules_resource: Parameters supplied to the operation. Is either a - AlertRuleResourcePatch type or a IO type. Required. - :type alert_rules_resource: ~azure.mgmt.monitor.v2015_07_01.models.AlertRuleResourcePatch 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 + AlertRuleResourcePatch type or a IO[bytes] type. Required. + :type alert_rules_resource: ~azure.mgmt.monitor.v2014_04_01.models.AlertRuleResourcePatch or + IO[bytes] :return: AlertRuleResource or the result of cls(response) - :rtype: ~azure.mgmt.monitor.v2015_07_01.models.AlertRuleResource + :rtype: ~azure.mgmt.monitor.v2014_04_01.models.AlertRuleResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -422,19 +394,19 @@ async def update( _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", "2014-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2014-04-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.AlertRuleResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(alert_rules_resource, (IO, bytes)): + if isinstance(alert_rules_resource, (IOBase, bytes)): _content = alert_rules_resource else: _json = self._serialize.body(alert_rules_resource, "AlertRuleResourcePatch") - request = build_update_request( + _request = build_update_request( resource_group_name=resource_group_name, rule_name=rule_name, subscription_id=self._config.subscription_id, @@ -442,16 +414,14 @@ async def update( 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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -461,21 +431,13 @@ async def update( 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("AlertRuleResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("AlertRuleResource", pipeline_response) + deserialized = self._deserialize("AlertRuleResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/alertrules/{ruleName}" - } - @distributed_trace def list_by_resource_group( self, resource_group_name: str, **kwargs: Any @@ -485,19 +447,18 @@ def list_by_resource_group( :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either AlertRuleResource or the result of cls(response) :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.monitor.v2015_07_01.models.AlertRuleResource] + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.monitor.v2014_04_01.models.AlertRuleResource] :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", "2014-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2014-04-01")) cls: ClsType[_models.AlertRuleResourceCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -508,23 +469,31 @@ 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_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: - request = HttpRequest("GET", next_link) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + # 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._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 async def extract_data(pipeline_response): deserialized = self._deserialize("AlertRuleResourceCollection", pipeline_response) @@ -534,11 +503,11 @@ async def extract_data(pipeline_response): return None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -551,27 +520,22 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/alertrules" - } - @distributed_trace def list_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.AlertRuleResource"]: """List the classic metric alert rules within a subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either AlertRuleResource or the result of cls(response) :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.monitor.v2015_07_01.models.AlertRuleResource] + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.monitor.v2014_04_01.models.AlertRuleResource] :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", "2014-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2014-04-01")) cls: ClsType[_models.AlertRuleResourceCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -582,22 +546,30 @@ def list_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.AlertRul def prepare_request(next_link=None): if not next_link: - request = build_list_by_subscription_request( + _request = build_list_by_subscription_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_subscription.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: - request = HttpRequest("GET", next_link) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + # 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._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 async def extract_data(pipeline_response): deserialized = self._deserialize("AlertRuleResourceCollection", pipeline_response) @@ -607,11 +579,11 @@ async def extract_data(pipeline_response): return None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -623,5 +595,3 @@ async def get_next(next_link=None): return pipeline_response return AsyncItemPaged(get_next, extract_data) - - list_by_subscription.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/alertrules"} diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/aio/operations/_alert_rules_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2014_04_01/aio/operations/_autoscale_settings_operations.py similarity index 56% rename from sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/aio/operations/_alert_rules_operations.py rename to sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2014_04_01/aio/operations/_autoscale_settings_operations.py index ab65fc45afc3..61d8f47cfce6 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/aio/operations/_alert_rules_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2014_04_01/aio/operations/_autoscale_settings_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,7 +5,10 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( @@ -18,16 +20,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 ...operations._alert_rules_operations import ( +from ...operations._autoscale_settings_operations import ( build_create_or_update_request, build_delete_request, build_get_request, @@ -36,18 +36,22 @@ build_update_request, ) +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class AlertRulesOperations: +class AutoscaleSettingsOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through - :class:`~azure.mgmt.monitor.v2015_04_01.aio.MonitorManagementClient`'s - :attr:`alert_rules` attribute. + :class:`~azure.mgmt.monitor.v2014_04_01.aio.MonitorManagementClient`'s + :attr:`autoscale_settings` attribute. """ models = _models @@ -58,32 +62,115 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") + + @distributed_trace + def list_by_resource_group( + self, resource_group_name: str, **kwargs: Any + ) -> AsyncIterable["_models.AutoscaleSettingResource"]: + """Lists the autoscale settings for a resource group. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :return: An iterator like instance of either AutoscaleSettingResource or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.monitor.v2014_04_01.models.AutoscaleSettingResource] + :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._api_version or "2014-04-01")) + cls: ClsType[_models.AutoscaleSettingResourceCollection] = 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_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._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 + + async def extract_data(pipeline_response): + deserialized = self._deserialize("AutoscaleSettingResourceCollection", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _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) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) @overload async def create_or_update( self, resource_group_name: str, - rule_name: str, - parameters: _models.AlertRuleResource, + autoscale_setting_name: str, + parameters: _models.AutoscaleSettingResource, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.AlertRuleResource: - """Creates or updates a classic metric alert rule. + ) -> _models.AutoscaleSettingResource: + """Creates or updates an autoscale setting. :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :param rule_name: The name of the rule. Required. - :type rule_name: str - :param parameters: The parameters of the rule to create or update. Required. - :type parameters: ~azure.mgmt.monitor.v2015_04_01.models.AlertRuleResource + :param autoscale_setting_name: The autoscale setting name. Required. + :type autoscale_setting_name: str + :param parameters: Parameters supplied to the operation. Required. + :type parameters: ~azure.mgmt.monitor.v2014_04_01.models.AutoscaleSettingResource :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: AlertRuleResource or the result of cls(response) - :rtype: ~azure.mgmt.monitor.v2015_04_01.models.AlertRuleResource + :return: AutoscaleSettingResource or the result of cls(response) + :rtype: ~azure.mgmt.monitor.v2014_04_01.models.AutoscaleSettingResource :raises ~azure.core.exceptions.HttpResponseError: """ @@ -91,53 +178,52 @@ async def create_or_update( async def create_or_update( self, resource_group_name: str, - rule_name: str, - parameters: IO, + autoscale_setting_name: str, + parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.AlertRuleResource: - """Creates or updates a classic metric alert rule. + ) -> _models.AutoscaleSettingResource: + """Creates or updates an autoscale setting. :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :param rule_name: The name of the rule. Required. - :type rule_name: str - :param parameters: The parameters of the rule to create or update. Required. - :type parameters: IO + :param autoscale_setting_name: The autoscale setting name. Required. + :type autoscale_setting_name: str + :param parameters: Parameters supplied to the operation. 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: AlertRuleResource or the result of cls(response) - :rtype: ~azure.mgmt.monitor.v2015_04_01.models.AlertRuleResource + :return: AutoscaleSettingResource or the result of cls(response) + :rtype: ~azure.mgmt.monitor.v2014_04_01.models.AutoscaleSettingResource :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async async def create_or_update( - self, resource_group_name: str, rule_name: str, parameters: Union[_models.AlertRuleResource, IO], **kwargs: Any - ) -> _models.AlertRuleResource: - """Creates or updates a classic metric alert rule. + self, + resource_group_name: str, + autoscale_setting_name: str, + parameters: Union[_models.AutoscaleSettingResource, IO[bytes]], + **kwargs: Any + ) -> _models.AutoscaleSettingResource: + """Creates or updates an autoscale setting. :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :param rule_name: The name of the rule. Required. - :type rule_name: str - :param parameters: The parameters of the rule to create or update. Is either a - AlertRuleResource type or a IO type. Required. - :type parameters: ~azure.mgmt.monitor.v2015_04_01.models.AlertRuleResource 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: AlertRuleResource or the result of cls(response) - :rtype: ~azure.mgmt.monitor.v2015_04_01.models.AlertRuleResource + :param autoscale_setting_name: The autoscale setting name. Required. + :type autoscale_setting_name: str + :param parameters: Parameters supplied to the operation. Is either a AutoscaleSettingResource + type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.monitor.v2014_04_01.models.AutoscaleSettingResource or IO[bytes] + :return: AutoscaleSettingResource or the result of cls(response) + :rtype: ~azure.mgmt.monitor.v2014_04_01.models.AutoscaleSettingResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -148,36 +234,34 @@ async def create_or_update( _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", "2014-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2014-04-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.AlertRuleResource] = kwargs.pop("cls", None) + cls: ClsType[_models.AutoscaleSettingResource] = 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, "AlertRuleResource") + _json = self._serialize.body(parameters, "AutoscaleSettingResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, - rule_name=rule_name, + autoscale_setting_name=autoscale_setting_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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -187,38 +271,27 @@ async def create_or_update( 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("AlertRuleResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("AlertRuleResource", pipeline_response) + deserialized = self._deserialize("AutoscaleSettingResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/alertrules/{ruleName}" - } - @distributed_trace_async - async def delete( # pylint: disable=inconsistent-return-statements - self, resource_group_name: str, rule_name: str, **kwargs: Any - ) -> None: - """Deletes a classic metric alert rule. + async def delete(self, resource_group_name: str, autoscale_setting_name: str, **kwargs: Any) -> None: + """Deletes and autoscale setting. :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :param rule_name: The name of the rule. Required. - :type rule_name: str - :keyword callable cls: A custom type or function that will be passed the direct response + :param autoscale_setting_name: The autoscale setting name. Required. + :type autoscale_setting_name: str :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, @@ -229,24 +302,22 @@ async def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2014-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2014-04-01")) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, - rule_name=rule_name, + autoscale_setting_name=autoscale_setting_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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -257,27 +328,24 @@ async def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/alertrules/{ruleName}" - } + return cls(pipeline_response, None, {}) # type: ignore @distributed_trace_async - async def get(self, resource_group_name: str, rule_name: str, **kwargs: Any) -> _models.AlertRuleResource: - """Gets a classic metric alert rule. + async def get( + self, resource_group_name: str, autoscale_setting_name: str, **kwargs: Any + ) -> _models.AutoscaleSettingResource: + """Gets an autoscale setting. :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :param rule_name: The name of the rule. Required. - :type rule_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: AlertRuleResource or the result of cls(response) - :rtype: ~azure.mgmt.monitor.v2015_04_01.models.AlertRuleResource + :param autoscale_setting_name: The autoscale setting name. Required. + :type autoscale_setting_name: str + :return: AutoscaleSettingResource or the result of cls(response) + :rtype: ~azure.mgmt.monitor.v2014_04_01.models.AutoscaleSettingResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -288,24 +356,22 @@ async def get(self, resource_group_name: str, rule_name: str, **kwargs: Any) -> _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2014-04-01")) - cls: ClsType[_models.AlertRuleResource] = kwargs.pop("cls", None) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2014-04-01")) + cls: ClsType[_models.AutoscaleSettingResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, - rule_name=rule_name, + autoscale_setting_name=autoscale_setting_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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -315,43 +381,39 @@ async def get(self, resource_group_name: str, rule_name: str, **kwargs: Any) -> error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("AlertRuleResource", pipeline_response) + deserialized = self._deserialize("AutoscaleSettingResource", 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.Insights/alertrules/{ruleName}" - } + return deserialized # type: ignore @overload async def update( self, resource_group_name: str, - rule_name: str, - alert_rules_resource: _models.AlertRuleResourcePatch, + autoscale_setting_name: str, + autoscale_setting_resource: _models.AutoscaleSettingResourcePatch, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.AlertRuleResource: - """Updates an existing classic metric AlertRuleResource. To update other fields use the - CreateOrUpdate method. + ) -> _models.AutoscaleSettingResource: + """Updates an existing AutoscaleSettingsResource. To update other fields use the CreateOrUpdate + method. :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :param rule_name: The name of the rule. Required. - :type rule_name: str - :param alert_rules_resource: Parameters supplied to the operation. Required. - :type alert_rules_resource: ~azure.mgmt.monitor.v2015_04_01.models.AlertRuleResourcePatch + :param autoscale_setting_name: The autoscale setting name. Required. + :type autoscale_setting_name: str + :param autoscale_setting_resource: Parameters supplied to the operation. Required. + :type autoscale_setting_resource: + ~azure.mgmt.monitor.v2014_04_01.models.AutoscaleSettingResourcePatch :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: AlertRuleResource or the result of cls(response) - :rtype: ~azure.mgmt.monitor.v2015_04_01.models.AlertRuleResource + :return: AutoscaleSettingResource or the result of cls(response) + :rtype: ~azure.mgmt.monitor.v2014_04_01.models.AutoscaleSettingResource :raises ~azure.core.exceptions.HttpResponseError: """ @@ -359,28 +421,27 @@ async def update( async def update( self, resource_group_name: str, - rule_name: str, - alert_rules_resource: IO, + autoscale_setting_name: str, + autoscale_setting_resource: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.AlertRuleResource: - """Updates an existing classic metric AlertRuleResource. To update other fields use the - CreateOrUpdate method. + ) -> _models.AutoscaleSettingResource: + """Updates an existing AutoscaleSettingsResource. To update other fields use the CreateOrUpdate + method. :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :param rule_name: The name of the rule. Required. - :type rule_name: str - :param alert_rules_resource: Parameters supplied to the operation. Required. - :type alert_rules_resource: IO + :param autoscale_setting_name: The autoscale setting name. Required. + :type autoscale_setting_name: str + :param autoscale_setting_resource: Parameters supplied to the operation. Required. + :type autoscale_setting_resource: 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: AlertRuleResource or the result of cls(response) - :rtype: ~azure.mgmt.monitor.v2015_04_01.models.AlertRuleResource + :return: AutoscaleSettingResource or the result of cls(response) + :rtype: ~azure.mgmt.monitor.v2014_04_01.models.AutoscaleSettingResource :raises ~azure.core.exceptions.HttpResponseError: """ @@ -388,30 +449,27 @@ async def update( async def update( self, resource_group_name: str, - rule_name: str, - alert_rules_resource: Union[_models.AlertRuleResourcePatch, IO], + autoscale_setting_name: str, + autoscale_setting_resource: Union[_models.AutoscaleSettingResourcePatch, IO[bytes]], **kwargs: Any - ) -> _models.AlertRuleResource: - """Updates an existing classic metric AlertRuleResource. To update other fields use the - CreateOrUpdate method. + ) -> _models.AutoscaleSettingResource: + """Updates an existing AutoscaleSettingsResource. To update other fields use the CreateOrUpdate + method. :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :param rule_name: The name of the rule. Required. - :type rule_name: str - :param alert_rules_resource: Parameters supplied to the operation. Is either a - AlertRuleResourcePatch type or a IO type. Required. - :type alert_rules_resource: ~azure.mgmt.monitor.v2015_04_01.models.AlertRuleResourcePatch 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: AlertRuleResource or the result of cls(response) - :rtype: ~azure.mgmt.monitor.v2015_04_01.models.AlertRuleResource + :param autoscale_setting_name: The autoscale setting name. Required. + :type autoscale_setting_name: str + :param autoscale_setting_resource: Parameters supplied to the operation. Is either a + AutoscaleSettingResourcePatch type or a IO[bytes] type. Required. + :type autoscale_setting_resource: + ~azure.mgmt.monitor.v2014_04_01.models.AutoscaleSettingResourcePatch or IO[bytes] + :return: AutoscaleSettingResource or the result of cls(response) + :rtype: ~azure.mgmt.monitor.v2014_04_01.models.AutoscaleSettingResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -422,82 +480,67 @@ async def update( _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", "2014-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2014-04-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.AlertRuleResource] = kwargs.pop("cls", None) + cls: ClsType[_models.AutoscaleSettingResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(alert_rules_resource, (IO, bytes)): - _content = alert_rules_resource + if isinstance(autoscale_setting_resource, (IOBase, bytes)): + _content = autoscale_setting_resource else: - _json = self._serialize.body(alert_rules_resource, "AlertRuleResourcePatch") + _json = self._serialize.body(autoscale_setting_resource, "AutoscaleSettingResourcePatch") - request = build_update_request( + _request = build_update_request( resource_group_name=resource_group_name, - rule_name=rule_name, + autoscale_setting_name=autoscale_setting_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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _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) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if response.status_code == 200: - deserialized = self._deserialize("AlertRuleResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("AlertRuleResource", pipeline_response) + deserialized = self._deserialize("AutoscaleSettingResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/alertrules/{ruleName}" - } - @distributed_trace - def list_by_resource_group( - self, resource_group_name: str, **kwargs: Any - ) -> AsyncIterable["_models.AlertRuleResource"]: - """List the classic metric alert rules within a resource group. + def list_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.AutoscaleSettingResource"]: + """Lists the autoscale settings for a subscription. - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either AlertRuleResource or the result of cls(response) + :return: An iterator like instance of either AutoscaleSettingResource or the result of + cls(response) :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.monitor.v2015_04_01.models.AlertRuleResource] + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.monitor.v2014_04_01.models.AutoscaleSettingResource] :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", "2014-04-01")) - cls: ClsType[_models.AlertRuleResourceCollection] = kwargs.pop("cls", None) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2014-04-01")) + cls: ClsType[_models.AutoscaleSettingResourceCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -508,110 +551,44 @@ def list_by_resource_group( def prepare_request(next_link=None): if not next_link: - request = build_list_by_resource_group_request( - resource_group_name=resource_group_name, + _request = build_list_by_subscription_request( 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) + _request.url = self._client.format_url(_request.url) else: - request = HttpRequest("GET", next_link) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request - - async def extract_data(pipeline_response): - deserialized = self._deserialize("AlertRuleResourceCollection", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - request = prepare_request(next_link) - - _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) - 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.Insights/alertrules" - } - - @distributed_trace - def list_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.AlertRuleResource"]: - """List the classic metric alert rules within a subscription. - - :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either AlertRuleResource or the result of cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.monitor.v2015_04_01.models.AlertRuleResource] - :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", "2014-04-01")) - cls: ClsType[_models.AlertRuleResourceCollection] = kwargs.pop("cls", None) - - error_map = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - request = build_list_by_subscription_request( - subscription_id=self._config.subscription_id, - api_version=api_version, - template_url=self.list_by_subscription.metadata["url"], - headers=_headers, - params=_params, + # 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() + } ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - - else: - request = HttpRequest("GET", next_link) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _next_request_params["api-version"] = self._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 async def extract_data(pipeline_response): - deserialized = self._deserialize("AlertRuleResourceCollection", pipeline_response) + deserialized = self._deserialize("AutoscaleSettingResourceCollection", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) # type: ignore - return None, AsyncList(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) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -623,5 +600,3 @@ async def get_next(next_link=None): return pipeline_response return AsyncItemPaged(get_next, extract_data) - - list_by_subscription.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/alertrules"} diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2014_04_01/aio/operations/_patch.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2014_04_01/aio/operations/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2014_04_01/aio/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2014_04_01/models/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2014_04_01/models/__init__.py new file mode 100644 index 000000000000..d21127c76faf --- /dev/null +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2014_04_01/models/__init__.py @@ -0,0 +1,110 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models_py3 import ( # type: ignore + AlertRuleResource, + AlertRuleResourceCollection, + AlertRuleResourcePatch, + AutoscaleNotification, + AutoscaleProfile, + AutoscaleSettingResource, + AutoscaleSettingResourceCollection, + AutoscaleSettingResourcePatch, + EmailNotification, + ErrorResponse, + LocationThresholdRuleCondition, + ManagementEventAggregationCondition, + ManagementEventRuleCondition, + MetricTrigger, + Recurrence, + RecurrentSchedule, + Resource, + RuleAction, + RuleCondition, + RuleDataSource, + RuleEmailAction, + RuleManagementEventClaimsDataSource, + RuleManagementEventDataSource, + RuleMetricDataSource, + RuleWebhookAction, + ScaleAction, + ScaleCapacity, + ScaleRule, + ScaleRuleMetricDimension, + ThresholdRuleCondition, + TimeWindow, + WebhookNotification, +) + +from ._monitor_management_client_enums import ( # type: ignore + ComparisonOperationType, + ConditionOperator, + MetricStatisticType, + RecurrenceFrequency, + ScaleDirection, + ScaleRuleMetricDimensionOperationType, + ScaleType, + TimeAggregationOperator, + TimeAggregationType, +) +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "AlertRuleResource", + "AlertRuleResourceCollection", + "AlertRuleResourcePatch", + "AutoscaleNotification", + "AutoscaleProfile", + "AutoscaleSettingResource", + "AutoscaleSettingResourceCollection", + "AutoscaleSettingResourcePatch", + "EmailNotification", + "ErrorResponse", + "LocationThresholdRuleCondition", + "ManagementEventAggregationCondition", + "ManagementEventRuleCondition", + "MetricTrigger", + "Recurrence", + "RecurrentSchedule", + "Resource", + "RuleAction", + "RuleCondition", + "RuleDataSource", + "RuleEmailAction", + "RuleManagementEventClaimsDataSource", + "RuleManagementEventDataSource", + "RuleMetricDataSource", + "RuleWebhookAction", + "ScaleAction", + "ScaleCapacity", + "ScaleRule", + "ScaleRuleMetricDimension", + "ThresholdRuleCondition", + "TimeWindow", + "WebhookNotification", + "ComparisonOperationType", + "ConditionOperator", + "MetricStatisticType", + "RecurrenceFrequency", + "ScaleDirection", + "ScaleRuleMetricDimensionOperationType", + "ScaleType", + "TimeAggregationOperator", + "TimeAggregationType", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2014_04_01/models/_models_py3.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2014_04_01/models/_models_py3.py new file mode 100644 index 000000000000..72b178d60870 --- /dev/null +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2014_04_01/models/_models_py3.py @@ -0,0 +1,1999 @@ +# 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 datetime +from typing import Any, Dict, List, Optional, TYPE_CHECKING, Union + +from ... import _serialization + +if TYPE_CHECKING: + from .. import models as _models + + +class Resource(_serialization.Model): + """An azure resource object. + + 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 id: Azure resource Id. + :vartype id: str + :ivar name: Azure resource name. + :vartype name: str + :ivar type: Azure resource type. + :vartype type: str + :ivar location: Resource location. Required. + :vartype location: str + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "location": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + } + + def __init__(self, *, location: str, tags: Optional[Dict[str, str]] = None, **kwargs: Any) -> None: + """ + :keyword location: Resource location. Required. + :paramtype location: str + :keyword tags: Resource tags. + :paramtype tags: dict[str, str] + """ + super().__init__(**kwargs) + self.id = None + self.name = None + self.type = None + self.location = location + self.tags = tags + + +class AlertRuleResource(Resource): + """The alert rule 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 server. + + :ivar id: Azure resource Id. + :vartype id: str + :ivar name: Azure resource name. + :vartype name: str + :ivar type: Azure resource type. + :vartype type: str + :ivar location: Resource location. Required. + :vartype location: str + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + :ivar name_properties_name: the name of the alert rule. Required. + :vartype name_properties_name: str + :ivar description: the description of the alert rule that will be included in the alert email. + :vartype description: str + :ivar provisioning_state: the provisioning state. + :vartype provisioning_state: str + :ivar is_enabled: the flag that indicates whether the alert rule is enabled. Required. + :vartype is_enabled: bool + :ivar condition: the condition that results in the alert rule being activated. Required. + :vartype condition: ~azure.mgmt.monitor.v2014_04_01.models.RuleCondition + :ivar action: action that is performed when the alert rule becomes active, and when an alert + condition is resolved. + :vartype action: ~azure.mgmt.monitor.v2014_04_01.models.RuleAction + :ivar actions: the array of actions that are performed when the alert rule becomes active, and + when an alert condition is resolved. + :vartype actions: list[~azure.mgmt.monitor.v2014_04_01.models.RuleAction] + :ivar last_updated_time: Last time the rule was updated in ISO8601 format. + :vartype last_updated_time: ~datetime.datetime + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "location": {"required": True}, + "name_properties_name": {"required": True}, + "is_enabled": {"required": True}, + "condition": {"required": True}, + "last_updated_time": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "name_properties_name": {"key": "properties.name", "type": "str"}, + "description": {"key": "properties.description", "type": "str"}, + "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, + "is_enabled": {"key": "properties.isEnabled", "type": "bool"}, + "condition": {"key": "properties.condition", "type": "RuleCondition"}, + "action": {"key": "properties.action", "type": "RuleAction"}, + "actions": {"key": "properties.actions", "type": "[RuleAction]"}, + "last_updated_time": {"key": "properties.lastUpdatedTime", "type": "iso-8601"}, + } + + def __init__( + self, + *, + location: str, + name_properties_name: str, + is_enabled: bool, + condition: "_models.RuleCondition", + tags: Optional[Dict[str, str]] = None, + description: Optional[str] = None, + provisioning_state: Optional[str] = None, + action: Optional["_models.RuleAction"] = None, + actions: Optional[List["_models.RuleAction"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword location: Resource location. Required. + :paramtype location: str + :keyword tags: Resource tags. + :paramtype tags: dict[str, str] + :keyword name_properties_name: the name of the alert rule. Required. + :paramtype name_properties_name: str + :keyword description: the description of the alert rule that will be included in the alert + email. + :paramtype description: str + :keyword provisioning_state: the provisioning state. + :paramtype provisioning_state: str + :keyword is_enabled: the flag that indicates whether the alert rule is enabled. Required. + :paramtype is_enabled: bool + :keyword condition: the condition that results in the alert rule being activated. Required. + :paramtype condition: ~azure.mgmt.monitor.v2014_04_01.models.RuleCondition + :keyword action: action that is performed when the alert rule becomes active, and when an alert + condition is resolved. + :paramtype action: ~azure.mgmt.monitor.v2014_04_01.models.RuleAction + :keyword actions: the array of actions that are performed when the alert rule becomes active, + and when an alert condition is resolved. + :paramtype actions: list[~azure.mgmt.monitor.v2014_04_01.models.RuleAction] + """ + super().__init__(location=location, tags=tags, **kwargs) + self.name_properties_name = name_properties_name + self.description = description + self.provisioning_state = provisioning_state + self.is_enabled = is_enabled + self.condition = condition + self.action = action + self.actions = actions + self.last_updated_time = None + + +class AlertRuleResourceCollection(_serialization.Model): + """Represents a collection of alert rule resources. + + :ivar value: the values for the alert rule resources. + :vartype value: list[~azure.mgmt.monitor.v2014_04_01.models.AlertRuleResource] + """ + + _attribute_map = { + "value": {"key": "value", "type": "[AlertRuleResource]"}, + } + + def __init__(self, *, value: Optional[List["_models.AlertRuleResource"]] = None, **kwargs: Any) -> None: + """ + :keyword value: the values for the alert rule resources. + :paramtype value: list[~azure.mgmt.monitor.v2014_04_01.models.AlertRuleResource] + """ + super().__init__(**kwargs) + self.value = value + + +class AlertRuleResourcePatch(_serialization.Model): + """The alert rule object for patch operations. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + :ivar name: the name of the alert rule. + :vartype name: str + :ivar description: the description of the alert rule that will be included in the alert email. + :vartype description: str + :ivar provisioning_state: the provisioning state. + :vartype provisioning_state: str + :ivar is_enabled: the flag that indicates whether the alert rule is enabled. + :vartype is_enabled: bool + :ivar condition: the condition that results in the alert rule being activated. + :vartype condition: ~azure.mgmt.monitor.v2014_04_01.models.RuleCondition + :ivar action: action that is performed when the alert rule becomes active, and when an alert + condition is resolved. + :vartype action: ~azure.mgmt.monitor.v2014_04_01.models.RuleAction + :ivar actions: the array of actions that are performed when the alert rule becomes active, and + when an alert condition is resolved. + :vartype actions: list[~azure.mgmt.monitor.v2014_04_01.models.RuleAction] + :ivar last_updated_time: Last time the rule was updated in ISO8601 format. + :vartype last_updated_time: ~datetime.datetime + """ + + _validation = { + "last_updated_time": {"readonly": True}, + } + + _attribute_map = { + "tags": {"key": "tags", "type": "{str}"}, + "name": {"key": "properties.name", "type": "str"}, + "description": {"key": "properties.description", "type": "str"}, + "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, + "is_enabled": {"key": "properties.isEnabled", "type": "bool"}, + "condition": {"key": "properties.condition", "type": "RuleCondition"}, + "action": {"key": "properties.action", "type": "RuleAction"}, + "actions": {"key": "properties.actions", "type": "[RuleAction]"}, + "last_updated_time": {"key": "properties.lastUpdatedTime", "type": "iso-8601"}, + } + + def __init__( + self, + *, + tags: Optional[Dict[str, str]] = None, + name: Optional[str] = None, + description: Optional[str] = None, + provisioning_state: Optional[str] = None, + is_enabled: Optional[bool] = None, + condition: Optional["_models.RuleCondition"] = None, + action: Optional["_models.RuleAction"] = None, + actions: Optional[List["_models.RuleAction"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword tags: Resource tags. + :paramtype tags: dict[str, str] + :keyword name: the name of the alert rule. + :paramtype name: str + :keyword description: the description of the alert rule that will be included in the alert + email. + :paramtype description: str + :keyword provisioning_state: the provisioning state. + :paramtype provisioning_state: str + :keyword is_enabled: the flag that indicates whether the alert rule is enabled. + :paramtype is_enabled: bool + :keyword condition: the condition that results in the alert rule being activated. + :paramtype condition: ~azure.mgmt.monitor.v2014_04_01.models.RuleCondition + :keyword action: action that is performed when the alert rule becomes active, and when an alert + condition is resolved. + :paramtype action: ~azure.mgmt.monitor.v2014_04_01.models.RuleAction + :keyword actions: the array of actions that are performed when the alert rule becomes active, + and when an alert condition is resolved. + :paramtype actions: list[~azure.mgmt.monitor.v2014_04_01.models.RuleAction] + """ + super().__init__(**kwargs) + self.tags = tags + self.name = name + self.description = description + self.provisioning_state = provisioning_state + self.is_enabled = is_enabled + self.condition = condition + self.action = action + self.actions = actions + self.last_updated_time = None + + +class AutoscaleNotification(_serialization.Model): + """Autoscale notification. + + 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 operation: the operation associated with the notification and its value must be "scale". + Required. Default value is "Scale". + :vartype operation: str + :ivar email: the email notification. + :vartype email: ~azure.mgmt.monitor.v2014_04_01.models.EmailNotification + :ivar webhooks: the collection of webhook notifications. + :vartype webhooks: list[~azure.mgmt.monitor.v2014_04_01.models.WebhookNotification] + """ + + _validation = { + "operation": {"required": True, "constant": True}, + } + + _attribute_map = { + "operation": {"key": "operation", "type": "str"}, + "email": {"key": "email", "type": "EmailNotification"}, + "webhooks": {"key": "webhooks", "type": "[WebhookNotification]"}, + } + + operation = "Scale" + + def __init__( + self, + *, + email: Optional["_models.EmailNotification"] = None, + webhooks: Optional[List["_models.WebhookNotification"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword email: the email notification. + :paramtype email: ~azure.mgmt.monitor.v2014_04_01.models.EmailNotification + :keyword webhooks: the collection of webhook notifications. + :paramtype webhooks: list[~azure.mgmt.monitor.v2014_04_01.models.WebhookNotification] + """ + super().__init__(**kwargs) + self.email = email + self.webhooks = webhooks + + +class AutoscaleProfile(_serialization.Model): + """Autoscale profile. + + All required parameters must be populated in order to send to server. + + :ivar name: the name of the profile. Required. + :vartype name: str + :ivar capacity: the number of instances that can be used during this profile. Required. + :vartype capacity: ~azure.mgmt.monitor.v2014_04_01.models.ScaleCapacity + :ivar rules: the collection of rules that provide the triggers and parameters for the scaling + action. A maximum of 10 rules can be specified. Required. + :vartype rules: list[~azure.mgmt.monitor.v2014_04_01.models.ScaleRule] + :ivar fixed_date: the specific date-time for the profile. This element is not used if the + Recurrence element is used. + :vartype fixed_date: ~azure.mgmt.monitor.v2014_04_01.models.TimeWindow + :ivar recurrence: the repeating times at which this profile begins. This element is not used if + the FixedDate element is used. + :vartype recurrence: ~azure.mgmt.monitor.v2014_04_01.models.Recurrence + """ + + _validation = { + "name": {"required": True}, + "capacity": {"required": True}, + "rules": {"required": True}, + } + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "capacity": {"key": "capacity", "type": "ScaleCapacity"}, + "rules": {"key": "rules", "type": "[ScaleRule]"}, + "fixed_date": {"key": "fixedDate", "type": "TimeWindow"}, + "recurrence": {"key": "recurrence", "type": "Recurrence"}, + } + + def __init__( + self, + *, + name: str, + capacity: "_models.ScaleCapacity", + rules: List["_models.ScaleRule"], + fixed_date: Optional["_models.TimeWindow"] = None, + recurrence: Optional["_models.Recurrence"] = None, + **kwargs: Any + ) -> None: + """ + :keyword name: the name of the profile. Required. + :paramtype name: str + :keyword capacity: the number of instances that can be used during this profile. Required. + :paramtype capacity: ~azure.mgmt.monitor.v2014_04_01.models.ScaleCapacity + :keyword rules: the collection of rules that provide the triggers and parameters for the + scaling action. A maximum of 10 rules can be specified. Required. + :paramtype rules: list[~azure.mgmt.monitor.v2014_04_01.models.ScaleRule] + :keyword fixed_date: the specific date-time for the profile. This element is not used if the + Recurrence element is used. + :paramtype fixed_date: ~azure.mgmt.monitor.v2014_04_01.models.TimeWindow + :keyword recurrence: the repeating times at which this profile begins. This element is not used + if the FixedDate element is used. + :paramtype recurrence: ~azure.mgmt.monitor.v2014_04_01.models.Recurrence + """ + super().__init__(**kwargs) + self.name = name + self.capacity = capacity + self.rules = rules + self.fixed_date = fixed_date + self.recurrence = recurrence + + +class AutoscaleSettingResource(Resource): + """The autoscale setting 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 server. + + :ivar id: Azure resource Id. + :vartype id: str + :ivar name: Azure resource name. + :vartype name: str + :ivar type: Azure resource type. + :vartype type: str + :ivar location: Resource location. Required. + :vartype location: str + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + :ivar profiles: the collection of automatic scaling profiles that specify different scaling + parameters for different time periods. A maximum of 20 profiles can be specified. Required. + :vartype profiles: list[~azure.mgmt.monitor.v2014_04_01.models.AutoscaleProfile] + :ivar notifications: the collection of notifications. + :vartype notifications: list[~azure.mgmt.monitor.v2014_04_01.models.AutoscaleNotification] + :ivar enabled: the enabled flag. Specifies whether automatic scaling is enabled for the + resource. The default value is 'false'. + :vartype enabled: bool + :ivar name_properties_name: the name of the autoscale setting. + :vartype name_properties_name: str + :ivar target_resource_uri: the resource identifier of the resource that the autoscale setting + should be added to. + :vartype target_resource_uri: str + :ivar target_resource_location: the location of the resource that the autoscale setting should + be added to. + :vartype target_resource_location: str + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "location": {"required": True}, + "profiles": {"required": True, "max_items": 20, "min_items": 0}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "profiles": {"key": "properties.profiles", "type": "[AutoscaleProfile]"}, + "notifications": {"key": "properties.notifications", "type": "[AutoscaleNotification]"}, + "enabled": {"key": "properties.enabled", "type": "bool"}, + "name_properties_name": {"key": "properties.name", "type": "str"}, + "target_resource_uri": {"key": "properties.targetResourceUri", "type": "str"}, + "target_resource_location": {"key": "properties.targetResourceLocation", "type": "str"}, + } + + def __init__( + self, + *, + location: str, + profiles: List["_models.AutoscaleProfile"], + tags: Optional[Dict[str, str]] = None, + notifications: Optional[List["_models.AutoscaleNotification"]] = None, + enabled: bool = False, + name_properties_name: Optional[str] = None, + target_resource_uri: Optional[str] = None, + target_resource_location: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword location: Resource location. Required. + :paramtype location: str + :keyword tags: Resource tags. + :paramtype tags: dict[str, str] + :keyword profiles: the collection of automatic scaling profiles that specify different scaling + parameters for different time periods. A maximum of 20 profiles can be specified. Required. + :paramtype profiles: list[~azure.mgmt.monitor.v2014_04_01.models.AutoscaleProfile] + :keyword notifications: the collection of notifications. + :paramtype notifications: list[~azure.mgmt.monitor.v2014_04_01.models.AutoscaleNotification] + :keyword enabled: the enabled flag. Specifies whether automatic scaling is enabled for the + resource. The default value is 'false'. + :paramtype enabled: bool + :keyword name_properties_name: the name of the autoscale setting. + :paramtype name_properties_name: str + :keyword target_resource_uri: the resource identifier of the resource that the autoscale + setting should be added to. + :paramtype target_resource_uri: str + :keyword target_resource_location: the location of the resource that the autoscale setting + should be added to. + :paramtype target_resource_location: str + """ + super().__init__(location=location, tags=tags, **kwargs) + self.profiles = profiles + self.notifications = notifications + self.enabled = enabled + self.name_properties_name = name_properties_name + self.target_resource_uri = target_resource_uri + self.target_resource_location = target_resource_location + + +class AutoscaleSettingResourceCollection(_serialization.Model): + """Represents a collection of autoscale setting resources. + + All required parameters must be populated in order to send to server. + + :ivar value: the values for the autoscale setting resources. Required. + :vartype value: list[~azure.mgmt.monitor.v2014_04_01.models.AutoscaleSettingResource] + :ivar next_link: URL to get the next set of results. + :vartype next_link: str + """ + + _validation = { + "value": {"required": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[AutoscaleSettingResource]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, *, value: List["_models.AutoscaleSettingResource"], next_link: Optional[str] = None, **kwargs: Any + ) -> None: + """ + :keyword value: the values for the autoscale setting resources. Required. + :paramtype value: list[~azure.mgmt.monitor.v2014_04_01.models.AutoscaleSettingResource] + :keyword next_link: URL to get the next set of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class AutoscaleSettingResourcePatch(_serialization.Model): + """The autoscale setting object for patch operations. + + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + :ivar profiles: the collection of automatic scaling profiles that specify different scaling + parameters for different time periods. A maximum of 20 profiles can be specified. + :vartype profiles: list[~azure.mgmt.monitor.v2014_04_01.models.AutoscaleProfile] + :ivar notifications: the collection of notifications. + :vartype notifications: list[~azure.mgmt.monitor.v2014_04_01.models.AutoscaleNotification] + :ivar enabled: the enabled flag. Specifies whether automatic scaling is enabled for the + resource. The default value is 'false'. + :vartype enabled: bool + :ivar name: the name of the autoscale setting. + :vartype name: str + :ivar target_resource_uri: the resource identifier of the resource that the autoscale setting + should be added to. + :vartype target_resource_uri: str + :ivar target_resource_location: the location of the resource that the autoscale setting should + be added to. + :vartype target_resource_location: str + """ + + _validation = { + "profiles": {"max_items": 20, "min_items": 0}, + } + + _attribute_map = { + "tags": {"key": "tags", "type": "{str}"}, + "profiles": {"key": "properties.profiles", "type": "[AutoscaleProfile]"}, + "notifications": {"key": "properties.notifications", "type": "[AutoscaleNotification]"}, + "enabled": {"key": "properties.enabled", "type": "bool"}, + "name": {"key": "properties.name", "type": "str"}, + "target_resource_uri": {"key": "properties.targetResourceUri", "type": "str"}, + "target_resource_location": {"key": "properties.targetResourceLocation", "type": "str"}, + } + + def __init__( + self, + *, + tags: Optional[Dict[str, str]] = None, + profiles: Optional[List["_models.AutoscaleProfile"]] = None, + notifications: Optional[List["_models.AutoscaleNotification"]] = None, + enabled: bool = False, + name: Optional[str] = None, + target_resource_uri: Optional[str] = None, + target_resource_location: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword tags: Resource tags. + :paramtype tags: dict[str, str] + :keyword profiles: the collection of automatic scaling profiles that specify different scaling + parameters for different time periods. A maximum of 20 profiles can be specified. + :paramtype profiles: list[~azure.mgmt.monitor.v2014_04_01.models.AutoscaleProfile] + :keyword notifications: the collection of notifications. + :paramtype notifications: list[~azure.mgmt.monitor.v2014_04_01.models.AutoscaleNotification] + :keyword enabled: the enabled flag. Specifies whether automatic scaling is enabled for the + resource. The default value is 'false'. + :paramtype enabled: bool + :keyword name: the name of the autoscale setting. + :paramtype name: str + :keyword target_resource_uri: the resource identifier of the resource that the autoscale + setting should be added to. + :paramtype target_resource_uri: str + :keyword target_resource_location: the location of the resource that the autoscale setting + should be added to. + :paramtype target_resource_location: str + """ + super().__init__(**kwargs) + self.tags = tags + self.profiles = profiles + self.notifications = notifications + self.enabled = enabled + self.name = name + self.target_resource_uri = target_resource_uri + self.target_resource_location = target_resource_location + + +class EmailNotification(_serialization.Model): + """Email notification of an autoscale event. + + :ivar send_to_subscription_administrator: a value indicating whether to send email to + subscription administrator. + :vartype send_to_subscription_administrator: bool + :ivar send_to_subscription_co_administrators: a value indicating whether to send email to + subscription co-administrators. + :vartype send_to_subscription_co_administrators: bool + :ivar custom_emails: the custom e-mails list. This value can be null or empty, in which case + this attribute will be ignored. + :vartype custom_emails: list[str] + """ + + _attribute_map = { + "send_to_subscription_administrator": {"key": "sendToSubscriptionAdministrator", "type": "bool"}, + "send_to_subscription_co_administrators": {"key": "sendToSubscriptionCoAdministrators", "type": "bool"}, + "custom_emails": {"key": "customEmails", "type": "[str]"}, + } + + def __init__( + self, + *, + send_to_subscription_administrator: bool = False, + send_to_subscription_co_administrators: bool = False, + custom_emails: Optional[List[str]] = None, + **kwargs: Any + ) -> None: + """ + :keyword send_to_subscription_administrator: a value indicating whether to send email to + subscription administrator. + :paramtype send_to_subscription_administrator: bool + :keyword send_to_subscription_co_administrators: a value indicating whether to send email to + subscription co-administrators. + :paramtype send_to_subscription_co_administrators: bool + :keyword custom_emails: the custom e-mails list. This value can be null or empty, in which case + this attribute will be ignored. + :paramtype custom_emails: list[str] + """ + super().__init__(**kwargs) + self.send_to_subscription_administrator = send_to_subscription_administrator + self.send_to_subscription_co_administrators = send_to_subscription_co_administrators + self.custom_emails = custom_emails + + +class ErrorResponse(_serialization.Model): + """Describes the format of Error response. + + :ivar code: Error code. + :vartype code: str + :ivar message: Error message indicating why the operation failed. + :vartype message: str + """ + + _attribute_map = { + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, + } + + def __init__(self, *, code: Optional[str] = None, message: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword code: Error code. + :paramtype code: str + :keyword message: Error message indicating why the operation failed. + :paramtype message: str + """ + super().__init__(**kwargs) + self.code = code + self.message = message + + +class RuleCondition(_serialization.Model): + """The condition that results in the alert rule being activated. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + LocationThresholdRuleCondition, ManagementEventRuleCondition, ThresholdRuleCondition + + All required parameters must be populated in order to send to server. + + :ivar odata_type: specifies the type of condition. This can be one of three types: + ManagementEventRuleCondition (occurrences of management events), LocationThresholdRuleCondition + (based on the number of failures of a web test), and ThresholdRuleCondition (based on the + threshold of a metric). Required. + :vartype odata_type: str + :ivar data_source: the resource from which the rule collects its data. For this type dataSource + will always be of type RuleMetricDataSource. + :vartype data_source: ~azure.mgmt.monitor.v2014_04_01.models.RuleDataSource + """ + + _validation = { + "odata_type": {"required": True}, + } + + _attribute_map = { + "odata_type": {"key": "odata\\.type", "type": "str"}, + "data_source": {"key": "dataSource", "type": "RuleDataSource"}, + } + + _subtype_map = { + "odata_type": { + "Microsoft.Azure.Management.Insights.Models.LocationThresholdRuleCondition": "LocationThresholdRuleCondition", + "Microsoft.Azure.Management.Insights.Models.ManagementEventRuleCondition": "ManagementEventRuleCondition", + "Microsoft.Azure.Management.Insights.Models.ThresholdRuleCondition": "ThresholdRuleCondition", + } + } + + def __init__(self, *, data_source: Optional["_models.RuleDataSource"] = None, **kwargs: Any) -> None: + """ + :keyword data_source: the resource from which the rule collects its data. For this type + dataSource will always be of type RuleMetricDataSource. + :paramtype data_source: ~azure.mgmt.monitor.v2014_04_01.models.RuleDataSource + """ + super().__init__(**kwargs) + self.odata_type: Optional[str] = None + self.data_source = data_source + + +class LocationThresholdRuleCondition(RuleCondition): + """A rule condition based on a certain number of locations failing. + + All required parameters must be populated in order to send to server. + + :ivar odata_type: specifies the type of condition. This can be one of three types: + ManagementEventRuleCondition (occurrences of management events), LocationThresholdRuleCondition + (based on the number of failures of a web test), and ThresholdRuleCondition (based on the + threshold of a metric). Required. + :vartype odata_type: str + :ivar data_source: the resource from which the rule collects its data. For this type dataSource + will always be of type RuleMetricDataSource. + :vartype data_source: ~azure.mgmt.monitor.v2014_04_01.models.RuleDataSource + :ivar window_size: the period of time (in ISO 8601 duration format) that is used to monitor + alert activity based on the threshold. If specified then it must be between 5 minutes and 1 + day. + :vartype window_size: ~datetime.timedelta + :ivar failed_location_count: the number of locations that must fail to activate the alert. + Required. + :vartype failed_location_count: int + """ + + _validation = { + "odata_type": {"required": True}, + "failed_location_count": {"required": True, "minimum": 0}, + } + + _attribute_map = { + "odata_type": {"key": "odata\\.type", "type": "str"}, + "data_source": {"key": "dataSource", "type": "RuleDataSource"}, + "window_size": {"key": "windowSize", "type": "duration"}, + "failed_location_count": {"key": "failedLocationCount", "type": "int"}, + } + + def __init__( + self, + *, + failed_location_count: int, + data_source: Optional["_models.RuleDataSource"] = None, + window_size: Optional[datetime.timedelta] = None, + **kwargs: Any + ) -> None: + """ + :keyword data_source: the resource from which the rule collects its data. For this type + dataSource will always be of type RuleMetricDataSource. + :paramtype data_source: ~azure.mgmt.monitor.v2014_04_01.models.RuleDataSource + :keyword window_size: the period of time (in ISO 8601 duration format) that is used to monitor + alert activity based on the threshold. If specified then it must be between 5 minutes and 1 + day. + :paramtype window_size: ~datetime.timedelta + :keyword failed_location_count: the number of locations that must fail to activate the alert. + Required. + :paramtype failed_location_count: int + """ + super().__init__(data_source=data_source, **kwargs) + self.odata_type: str = "Microsoft.Azure.Management.Insights.Models.LocationThresholdRuleCondition" + self.window_size = window_size + self.failed_location_count = failed_location_count + + +class ManagementEventAggregationCondition(_serialization.Model): + """How the data that is collected should be combined over time. + + :ivar operator: the condition operator. Known values are: "GreaterThan", "GreaterThanOrEqual", + "LessThan", and "LessThanOrEqual". + :vartype operator: str or ~azure.mgmt.monitor.v2014_04_01.models.ConditionOperator + :ivar threshold: The threshold value that activates the alert. + :vartype threshold: float + :ivar window_size: the period of time (in ISO 8601 duration format) that is used to monitor + alert activity based on the threshold. If specified then it must be between 5 minutes and 1 + day. + :vartype window_size: ~datetime.timedelta + """ + + _attribute_map = { + "operator": {"key": "operator", "type": "str"}, + "threshold": {"key": "threshold", "type": "float"}, + "window_size": {"key": "windowSize", "type": "duration"}, + } + + def __init__( + self, + *, + operator: Optional[Union[str, "_models.ConditionOperator"]] = None, + threshold: Optional[float] = None, + window_size: Optional[datetime.timedelta] = None, + **kwargs: Any + ) -> None: + """ + :keyword operator: the condition operator. Known values are: "GreaterThan", + "GreaterThanOrEqual", "LessThan", and "LessThanOrEqual". + :paramtype operator: str or ~azure.mgmt.monitor.v2014_04_01.models.ConditionOperator + :keyword threshold: The threshold value that activates the alert. + :paramtype threshold: float + :keyword window_size: the period of time (in ISO 8601 duration format) that is used to monitor + alert activity based on the threshold. If specified then it must be between 5 minutes and 1 + day. + :paramtype window_size: ~datetime.timedelta + """ + super().__init__(**kwargs) + self.operator = operator + self.threshold = threshold + self.window_size = window_size + + +class ManagementEventRuleCondition(RuleCondition): + """A management event rule condition. + + All required parameters must be populated in order to send to server. + + :ivar odata_type: specifies the type of condition. This can be one of three types: + ManagementEventRuleCondition (occurrences of management events), LocationThresholdRuleCondition + (based on the number of failures of a web test), and ThresholdRuleCondition (based on the + threshold of a metric). Required. + :vartype odata_type: str + :ivar data_source: the resource from which the rule collects its data. For this type dataSource + will always be of type RuleMetricDataSource. + :vartype data_source: ~azure.mgmt.monitor.v2014_04_01.models.RuleDataSource + :ivar aggregation: How the data that is collected should be combined over time and when the + alert is activated. Note that for management event alerts aggregation is optional – if it is + not provided then any event will cause the alert to activate. + :vartype aggregation: + ~azure.mgmt.monitor.v2014_04_01.models.ManagementEventAggregationCondition + """ + + _validation = { + "odata_type": {"required": True}, + } + + _attribute_map = { + "odata_type": {"key": "odata\\.type", "type": "str"}, + "data_source": {"key": "dataSource", "type": "RuleDataSource"}, + "aggregation": {"key": "aggregation", "type": "ManagementEventAggregationCondition"}, + } + + def __init__( + self, + *, + data_source: Optional["_models.RuleDataSource"] = None, + aggregation: Optional["_models.ManagementEventAggregationCondition"] = None, + **kwargs: Any + ) -> None: + """ + :keyword data_source: the resource from which the rule collects its data. For this type + dataSource will always be of type RuleMetricDataSource. + :paramtype data_source: ~azure.mgmt.monitor.v2014_04_01.models.RuleDataSource + :keyword aggregation: How the data that is collected should be combined over time and when the + alert is activated. Note that for management event alerts aggregation is optional – if it is + not provided then any event will cause the alert to activate. + :paramtype aggregation: + ~azure.mgmt.monitor.v2014_04_01.models.ManagementEventAggregationCondition + """ + super().__init__(data_source=data_source, **kwargs) + self.odata_type: str = "Microsoft.Azure.Management.Insights.Models.ManagementEventRuleCondition" + self.aggregation = aggregation + + +class MetricTrigger(_serialization.Model): + """The trigger that results in a scaling action. + + All required parameters must be populated in order to send to server. + + :ivar metric_name: the name of the metric that defines what the rule monitors. Required. + :vartype metric_name: str + :ivar metric_namespace: the namespace of the metric that defines what the rule monitors. + :vartype metric_namespace: str + :ivar metric_resource_uri: the resource identifier of the resource the rule monitors. Required. + :vartype metric_resource_uri: str + :ivar metric_resource_location: the location of the resource the rule monitors. + :vartype metric_resource_location: str + :ivar time_grain: the granularity of metrics the rule monitors. Must be one of the predefined + values returned from metric definitions for the metric. Must be between 12 hours and 1 minute. + Required. + :vartype time_grain: ~datetime.timedelta + :ivar statistic: the metric statistic type. How the metrics from multiple instances are + combined. Required. Known values are: "Average", "Min", "Max", "Sum", and "Count". + :vartype statistic: str or ~azure.mgmt.monitor.v2014_04_01.models.MetricStatisticType + :ivar time_window: the range of time in which instance data is collected. This value must be + greater than the delay in metric collection, which can vary from resource-to-resource. Must be + between 12 hours and 5 minutes. Required. + :vartype time_window: ~datetime.timedelta + :ivar time_aggregation: time aggregation type. How the data that is collected should be + combined over time. The default value is Average. Required. Known values are: "Average", + "Minimum", "Maximum", "Total", "Count", and "Last". + :vartype time_aggregation: str or ~azure.mgmt.monitor.v2014_04_01.models.TimeAggregationType + :ivar operator: the operator that is used to compare the metric data and the threshold. + Required. Known values are: "Equals", "NotEquals", "GreaterThan", "GreaterThanOrEqual", + "LessThan", and "LessThanOrEqual". + :vartype operator: str or ~azure.mgmt.monitor.v2014_04_01.models.ComparisonOperationType + :ivar threshold: the threshold of the metric that triggers the scale action. Required. + :vartype threshold: float + :ivar dimensions: List of dimension conditions. For example: + [{"DimensionName":"AppName","Operator":"Equals","Values":["App1"]},{"DimensionName":"Deployment","Operator":"Equals","Values":["default"]}]. # pylint: disable=line-too-long + :vartype dimensions: list[~azure.mgmt.monitor.v2014_04_01.models.ScaleRuleMetricDimension] + :ivar divide_per_instance: a value indicating whether metric should divide per instance. + :vartype divide_per_instance: bool + """ + + _validation = { + "metric_name": {"required": True}, + "metric_resource_uri": {"required": True}, + "time_grain": {"required": True}, + "statistic": {"required": True}, + "time_window": {"required": True}, + "time_aggregation": {"required": True}, + "operator": {"required": True}, + "threshold": {"required": True}, + } + + _attribute_map = { + "metric_name": {"key": "metricName", "type": "str"}, + "metric_namespace": {"key": "metricNamespace", "type": "str"}, + "metric_resource_uri": {"key": "metricResourceUri", "type": "str"}, + "metric_resource_location": {"key": "metricResourceLocation", "type": "str"}, + "time_grain": {"key": "timeGrain", "type": "duration"}, + "statistic": {"key": "statistic", "type": "str"}, + "time_window": {"key": "timeWindow", "type": "duration"}, + "time_aggregation": {"key": "timeAggregation", "type": "str"}, + "operator": {"key": "operator", "type": "str"}, + "threshold": {"key": "threshold", "type": "float"}, + "dimensions": {"key": "dimensions", "type": "[ScaleRuleMetricDimension]"}, + "divide_per_instance": {"key": "dividePerInstance", "type": "bool"}, + } + + def __init__( + self, + *, + metric_name: str, + metric_resource_uri: str, + time_grain: datetime.timedelta, + statistic: Union[str, "_models.MetricStatisticType"], + time_window: datetime.timedelta, + time_aggregation: Union[str, "_models.TimeAggregationType"], + operator: Union[str, "_models.ComparisonOperationType"], + threshold: float, + metric_namespace: Optional[str] = None, + metric_resource_location: Optional[str] = None, + dimensions: Optional[List["_models.ScaleRuleMetricDimension"]] = None, + divide_per_instance: Optional[bool] = None, + **kwargs: Any + ) -> None: + """ + :keyword metric_name: the name of the metric that defines what the rule monitors. Required. + :paramtype metric_name: str + :keyword metric_namespace: the namespace of the metric that defines what the rule monitors. + :paramtype metric_namespace: str + :keyword metric_resource_uri: the resource identifier of the resource the rule monitors. + Required. + :paramtype metric_resource_uri: str + :keyword metric_resource_location: the location of the resource the rule monitors. + :paramtype metric_resource_location: str + :keyword time_grain: the granularity of metrics the rule monitors. Must be one of the + predefined values returned from metric definitions for the metric. Must be between 12 hours and + 1 minute. Required. + :paramtype time_grain: ~datetime.timedelta + :keyword statistic: the metric statistic type. How the metrics from multiple instances are + combined. Required. Known values are: "Average", "Min", "Max", "Sum", and "Count". + :paramtype statistic: str or ~azure.mgmt.monitor.v2014_04_01.models.MetricStatisticType + :keyword time_window: the range of time in which instance data is collected. This value must be + greater than the delay in metric collection, which can vary from resource-to-resource. Must be + between 12 hours and 5 minutes. Required. + :paramtype time_window: ~datetime.timedelta + :keyword time_aggregation: time aggregation type. How the data that is collected should be + combined over time. The default value is Average. Required. Known values are: "Average", + "Minimum", "Maximum", "Total", "Count", and "Last". + :paramtype time_aggregation: str or ~azure.mgmt.monitor.v2014_04_01.models.TimeAggregationType + :keyword operator: the operator that is used to compare the metric data and the threshold. + Required. Known values are: "Equals", "NotEquals", "GreaterThan", "GreaterThanOrEqual", + "LessThan", and "LessThanOrEqual". + :paramtype operator: str or ~azure.mgmt.monitor.v2014_04_01.models.ComparisonOperationType + :keyword threshold: the threshold of the metric that triggers the scale action. Required. + :paramtype threshold: float + :keyword dimensions: List of dimension conditions. For example: + [{"DimensionName":"AppName","Operator":"Equals","Values":["App1"]},{"DimensionName":"Deployment","Operator":"Equals","Values":["default"]}]. # pylint: disable=line-too-long + :paramtype dimensions: list[~azure.mgmt.monitor.v2014_04_01.models.ScaleRuleMetricDimension] + :keyword divide_per_instance: a value indicating whether metric should divide per instance. + :paramtype divide_per_instance: bool + """ + super().__init__(**kwargs) + self.metric_name = metric_name + self.metric_namespace = metric_namespace + self.metric_resource_uri = metric_resource_uri + self.metric_resource_location = metric_resource_location + self.time_grain = time_grain + self.statistic = statistic + self.time_window = time_window + self.time_aggregation = time_aggregation + self.operator = operator + self.threshold = threshold + self.dimensions = dimensions + self.divide_per_instance = divide_per_instance + + +class Recurrence(_serialization.Model): + """The repeating times at which this profile begins. This element is not used if the FixedDate + element is used. + + All required parameters must be populated in order to send to server. + + :ivar frequency: the recurrence frequency. How often the schedule profile should take effect. + This value must be Week, meaning each week will have the same set of profiles. For example, to + set a daily schedule, set **schedule** to every day of the week. The frequency property + specifies that the schedule is repeated weekly. Required. Known values are: "None", "Second", + "Minute", "Hour", "Day", "Week", "Month", and "Year". + :vartype frequency: str or ~azure.mgmt.monitor.v2014_04_01.models.RecurrenceFrequency + :ivar schedule: the scheduling constraints for when the profile begins. Required. + :vartype schedule: ~azure.mgmt.monitor.v2014_04_01.models.RecurrentSchedule + """ + + _validation = { + "frequency": {"required": True}, + "schedule": {"required": True}, + } + + _attribute_map = { + "frequency": {"key": "frequency", "type": "str"}, + "schedule": {"key": "schedule", "type": "RecurrentSchedule"}, + } + + def __init__( + self, + *, + frequency: Union[str, "_models.RecurrenceFrequency"], + schedule: "_models.RecurrentSchedule", + **kwargs: Any + ) -> None: + """ + :keyword frequency: the recurrence frequency. How often the schedule profile should take + effect. This value must be Week, meaning each week will have the same set of profiles. For + example, to set a daily schedule, set **schedule** to every day of the week. The frequency + property specifies that the schedule is repeated weekly. Required. Known values are: "None", + "Second", "Minute", "Hour", "Day", "Week", "Month", and "Year". + :paramtype frequency: str or ~azure.mgmt.monitor.v2014_04_01.models.RecurrenceFrequency + :keyword schedule: the scheduling constraints for when the profile begins. Required. + :paramtype schedule: ~azure.mgmt.monitor.v2014_04_01.models.RecurrentSchedule + """ + super().__init__(**kwargs) + self.frequency = frequency + self.schedule = schedule + + +class RecurrentSchedule(_serialization.Model): + """The scheduling constraints for when the profile begins. + + All required parameters must be populated in order to send to server. + + :ivar time_zone: the timezone for the hours of the profile. Some examples of valid time zones + are: Dateline Standard Time, UTC-11, Hawaiian Standard Time, Alaskan Standard Time, Pacific + Standard Time (Mexico), Pacific Standard Time, US Mountain Standard Time, Mountain Standard + Time (Mexico), Mountain Standard Time, Central America Standard Time, Central Standard Time, + Central Standard Time (Mexico), Canada Central Standard Time, SA Pacific Standard Time, Eastern + Standard Time, US Eastern Standard Time, Venezuela Standard Time, Paraguay Standard Time, + Atlantic Standard Time, Central Brazilian Standard Time, SA Western Standard Time, Pacific SA + Standard Time, Newfoundland Standard Time, E. South America Standard Time, Argentina Standard + Time, SA Eastern Standard Time, Greenland Standard Time, Montevideo Standard Time, Bahia + Standard Time, UTC-02, Mid-Atlantic Standard Time, Azores Standard Time, Cape Verde Standard + Time, Morocco Standard Time, UTC, GMT Standard Time, Greenwich Standard Time, W. Europe + Standard Time, Central Europe Standard Time, Romance Standard Time, Central European Standard + Time, W. Central Africa Standard Time, Namibia Standard Time, Jordan Standard Time, GTB + Standard Time, Middle East Standard Time, Egypt Standard Time, Syria Standard Time, E. Europe + Standard Time, South Africa Standard Time, FLE Standard Time, Turkey Standard Time, Israel + Standard Time, Kaliningrad Standard Time, Libya Standard Time, Arabic Standard Time, Arab + Standard Time, Belarus Standard Time, Russian Standard Time, E. Africa Standard Time, Iran + Standard Time, Arabian Standard Time, Azerbaijan Standard Time, Russia Time Zone 3, Mauritius + Standard Time, Georgian Standard Time, Caucasus Standard Time, Afghanistan Standard Time, West + Asia Standard Time, Ekaterinburg Standard Time, Pakistan Standard Time, India Standard Time, + Sri Lanka Standard Time, Nepal Standard Time, Central Asia Standard Time, Bangladesh Standard + Time, N. Central Asia Standard Time, Myanmar Standard Time, SE Asia Standard Time, North Asia + Standard Time, China Standard Time, North Asia East Standard Time, Singapore Standard Time, W. + Australia Standard Time, Taipei Standard Time, Ulaanbaatar Standard Time, Tokyo Standard Time, + Korea Standard Time, Yakutsk Standard Time, Cen. Australia Standard Time, AUS Central Standard + Time, E. Australia Standard Time, AUS Eastern Standard Time, West Pacific Standard Time, + Tasmania Standard Time, Magadan Standard Time, Vladivostok Standard Time, Russia Time Zone 10, + Central Pacific Standard Time, Russia Time Zone 11, New Zealand Standard Time, UTC+12, Fiji + Standard Time, Kamchatka Standard Time, Tonga Standard Time, Samoa Standard Time, Line Islands + Standard Time. Required. + :vartype time_zone: str + :ivar days: the collection of days that the profile takes effect on. Possible values are Sunday + through Saturday. Required. + :vartype days: list[str] + :ivar hours: A collection of hours that the profile takes effect on. Values supported are 0 to + 23 on the 24-hour clock (AM/PM times are not supported). Required. + :vartype hours: list[int] + :ivar minutes: A collection of minutes at which the profile takes effect at. Required. + :vartype minutes: list[int] + """ + + _validation = { + "time_zone": {"required": True}, + "days": {"required": True}, + "hours": {"required": True}, + "minutes": {"required": True}, + } + + _attribute_map = { + "time_zone": {"key": "timeZone", "type": "str"}, + "days": {"key": "days", "type": "[str]"}, + "hours": {"key": "hours", "type": "[int]"}, + "minutes": {"key": "minutes", "type": "[int]"}, + } + + def __init__(self, *, time_zone: str, days: List[str], hours: List[int], minutes: List[int], **kwargs: Any) -> None: + """ + :keyword time_zone: the timezone for the hours of the profile. Some examples of valid time + zones are: Dateline Standard Time, UTC-11, Hawaiian Standard Time, Alaskan Standard Time, + Pacific Standard Time (Mexico), Pacific Standard Time, US Mountain Standard Time, Mountain + Standard Time (Mexico), Mountain Standard Time, Central America Standard Time, Central Standard + Time, Central Standard Time (Mexico), Canada Central Standard Time, SA Pacific Standard Time, + Eastern Standard Time, US Eastern Standard Time, Venezuela Standard Time, Paraguay Standard + Time, Atlantic Standard Time, Central Brazilian Standard Time, SA Western Standard Time, + Pacific SA Standard Time, Newfoundland Standard Time, E. South America Standard Time, Argentina + Standard Time, SA Eastern Standard Time, Greenland Standard Time, Montevideo Standard Time, + Bahia Standard Time, UTC-02, Mid-Atlantic Standard Time, Azores Standard Time, Cape Verde + Standard Time, Morocco Standard Time, UTC, GMT Standard Time, Greenwich Standard Time, W. + Europe Standard Time, Central Europe Standard Time, Romance Standard Time, Central European + Standard Time, W. Central Africa Standard Time, Namibia Standard Time, Jordan Standard Time, + GTB Standard Time, Middle East Standard Time, Egypt Standard Time, Syria Standard Time, E. + Europe Standard Time, South Africa Standard Time, FLE Standard Time, Turkey Standard Time, + Israel Standard Time, Kaliningrad Standard Time, Libya Standard Time, Arabic Standard Time, + Arab Standard Time, Belarus Standard Time, Russian Standard Time, E. Africa Standard Time, Iran + Standard Time, Arabian Standard Time, Azerbaijan Standard Time, Russia Time Zone 3, Mauritius + Standard Time, Georgian Standard Time, Caucasus Standard Time, Afghanistan Standard Time, West + Asia Standard Time, Ekaterinburg Standard Time, Pakistan Standard Time, India Standard Time, + Sri Lanka Standard Time, Nepal Standard Time, Central Asia Standard Time, Bangladesh Standard + Time, N. Central Asia Standard Time, Myanmar Standard Time, SE Asia Standard Time, North Asia + Standard Time, China Standard Time, North Asia East Standard Time, Singapore Standard Time, W. + Australia Standard Time, Taipei Standard Time, Ulaanbaatar Standard Time, Tokyo Standard Time, + Korea Standard Time, Yakutsk Standard Time, Cen. Australia Standard Time, AUS Central Standard + Time, E. Australia Standard Time, AUS Eastern Standard Time, West Pacific Standard Time, + Tasmania Standard Time, Magadan Standard Time, Vladivostok Standard Time, Russia Time Zone 10, + Central Pacific Standard Time, Russia Time Zone 11, New Zealand Standard Time, UTC+12, Fiji + Standard Time, Kamchatka Standard Time, Tonga Standard Time, Samoa Standard Time, Line Islands + Standard Time. Required. + :paramtype time_zone: str + :keyword days: the collection of days that the profile takes effect on. Possible values are + Sunday through Saturday. Required. + :paramtype days: list[str] + :keyword hours: A collection of hours that the profile takes effect on. Values supported are 0 + to 23 on the 24-hour clock (AM/PM times are not supported). Required. + :paramtype hours: list[int] + :keyword minutes: A collection of minutes at which the profile takes effect at. Required. + :paramtype minutes: list[int] + """ + super().__init__(**kwargs) + self.time_zone = time_zone + self.days = days + self.hours = hours + self.minutes = minutes + + +class RuleAction(_serialization.Model): + """The action that is performed when the alert rule becomes active, and when an alert condition is + resolved. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + RuleEmailAction, RuleWebhookAction + + All required parameters must be populated in order to send to server. + + :ivar odata_type: specifies the type of the action. There are two types of actions: + RuleEmailAction and RuleWebhookAction. Required. + :vartype odata_type: str + """ + + _validation = { + "odata_type": {"required": True}, + } + + _attribute_map = { + "odata_type": {"key": "odata\\.type", "type": "str"}, + } + + _subtype_map = { + "odata_type": { + "Microsoft.Azure.Management.Insights.Models.RuleEmailAction": "RuleEmailAction", + "Microsoft.Azure.Management.Insights.Models.RuleWebhookAction": "RuleWebhookAction", + } + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.odata_type: Optional[str] = None + + +class RuleDataSource(_serialization.Model): + """The resource from which the rule collects its data. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + RuleManagementEventDataSource, RuleMetricDataSource + + All required parameters must be populated in order to send to server. + + :ivar odata_type: specifies the type of data source. There are two types of rule data sources: + RuleMetricDataSource and RuleManagementEventDataSource. Required. + :vartype odata_type: str + :ivar resource_uri: the resource identifier of the resource the rule monitors. **NOTE**\\ : + this property cannot be updated for an existing rule. + :vartype resource_uri: str + :ivar legacy_resource_id: the legacy resource identifier of the resource the rule monitors. + **NOTE**\\ : this property cannot be updated for an existing rule. + :vartype legacy_resource_id: str + :ivar resource_location: the location of the resource. + :vartype resource_location: str + :ivar metric_namespace: the namespace of the metric. + :vartype metric_namespace: str + """ + + _validation = { + "odata_type": {"required": True}, + } + + _attribute_map = { + "odata_type": {"key": "odata\\.type", "type": "str"}, + "resource_uri": {"key": "resourceUri", "type": "str"}, + "legacy_resource_id": {"key": "legacyResourceId", "type": "str"}, + "resource_location": {"key": "resourceLocation", "type": "str"}, + "metric_namespace": {"key": "metricNamespace", "type": "str"}, + } + + _subtype_map = { + "odata_type": { + "Microsoft.Azure.Management.Insights.Models.RuleManagementEventDataSource": "RuleManagementEventDataSource", + "Microsoft.Azure.Management.Insights.Models.RuleMetricDataSource": "RuleMetricDataSource", + } + } + + def __init__( + self, + *, + resource_uri: Optional[str] = None, + legacy_resource_id: Optional[str] = None, + resource_location: Optional[str] = None, + metric_namespace: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword resource_uri: the resource identifier of the resource the rule monitors. **NOTE**\\ : + this property cannot be updated for an existing rule. + :paramtype resource_uri: str + :keyword legacy_resource_id: the legacy resource identifier of the resource the rule monitors. + **NOTE**\\ : this property cannot be updated for an existing rule. + :paramtype legacy_resource_id: str + :keyword resource_location: the location of the resource. + :paramtype resource_location: str + :keyword metric_namespace: the namespace of the metric. + :paramtype metric_namespace: str + """ + super().__init__(**kwargs) + self.odata_type: Optional[str] = None + self.resource_uri = resource_uri + self.legacy_resource_id = legacy_resource_id + self.resource_location = resource_location + self.metric_namespace = metric_namespace + + +class RuleEmailAction(RuleAction): + """Specifies the action to send email when the rule condition is evaluated. The discriminator is + always RuleEmailAction in this case. + + All required parameters must be populated in order to send to server. + + :ivar odata_type: specifies the type of the action. There are two types of actions: + RuleEmailAction and RuleWebhookAction. Required. + :vartype odata_type: str + :ivar send_to_service_owners: Whether the administrators (service and co-administrators) of the + service should be notified when the alert is activated. + :vartype send_to_service_owners: bool + :ivar custom_emails: the list of administrator's custom email addresses to notify of the + activation of the alert. + :vartype custom_emails: list[str] + """ + + _validation = { + "odata_type": {"required": True}, + } + + _attribute_map = { + "odata_type": {"key": "odata\\.type", "type": "str"}, + "send_to_service_owners": {"key": "sendToServiceOwners", "type": "bool"}, + "custom_emails": {"key": "customEmails", "type": "[str]"}, + } + + def __init__( + self, *, send_to_service_owners: Optional[bool] = None, custom_emails: Optional[List[str]] = None, **kwargs: Any + ) -> None: + """ + :keyword send_to_service_owners: Whether the administrators (service and co-administrators) of + the service should be notified when the alert is activated. + :paramtype send_to_service_owners: bool + :keyword custom_emails: the list of administrator's custom email addresses to notify of the + activation of the alert. + :paramtype custom_emails: list[str] + """ + super().__init__(**kwargs) + self.odata_type: str = "Microsoft.Azure.Management.Insights.Models.RuleEmailAction" + self.send_to_service_owners = send_to_service_owners + self.custom_emails = custom_emails + + +class RuleManagementEventClaimsDataSource(_serialization.Model): + """The claims for a rule management event data source. + + :ivar email_address: the email address. + :vartype email_address: str + """ + + _attribute_map = { + "email_address": {"key": "emailAddress", "type": "str"}, + } + + def __init__(self, *, email_address: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword email_address: the email address. + :paramtype email_address: str + """ + super().__init__(**kwargs) + self.email_address = email_address + + +class RuleManagementEventDataSource(RuleDataSource): + """A rule management event data source. The discriminator fields is always + RuleManagementEventDataSource in this case. + + All required parameters must be populated in order to send to server. + + :ivar odata_type: specifies the type of data source. There are two types of rule data sources: + RuleMetricDataSource and RuleManagementEventDataSource. Required. + :vartype odata_type: str + :ivar resource_uri: the resource identifier of the resource the rule monitors. **NOTE**\\ : + this property cannot be updated for an existing rule. + :vartype resource_uri: str + :ivar legacy_resource_id: the legacy resource identifier of the resource the rule monitors. + **NOTE**\\ : this property cannot be updated for an existing rule. + :vartype legacy_resource_id: str + :ivar resource_location: the location of the resource. + :vartype resource_location: str + :ivar metric_namespace: the namespace of the metric. + :vartype metric_namespace: str + :ivar event_name: the event name. + :vartype event_name: str + :ivar event_source: the event source. + :vartype event_source: str + :ivar level: the level. + :vartype level: str + :ivar operation_name: The name of the operation that should be checked for. If no name is + provided, any operation will match. + :vartype operation_name: str + :ivar resource_group_name: the resource group name. + :vartype resource_group_name: str + :ivar resource_provider_name: the resource provider name. + :vartype resource_provider_name: str + :ivar status: The status of the operation that should be checked for. If no status is provided, + any status will match. + :vartype status: str + :ivar sub_status: the substatus. + :vartype sub_status: str + :ivar claims: the claims. + :vartype claims: ~azure.mgmt.monitor.v2014_04_01.models.RuleManagementEventClaimsDataSource + """ + + _validation = { + "odata_type": {"required": True}, + } + + _attribute_map = { + "odata_type": {"key": "odata\\.type", "type": "str"}, + "resource_uri": {"key": "resourceUri", "type": "str"}, + "legacy_resource_id": {"key": "legacyResourceId", "type": "str"}, + "resource_location": {"key": "resourceLocation", "type": "str"}, + "metric_namespace": {"key": "metricNamespace", "type": "str"}, + "event_name": {"key": "eventName", "type": "str"}, + "event_source": {"key": "eventSource", "type": "str"}, + "level": {"key": "level", "type": "str"}, + "operation_name": {"key": "operationName", "type": "str"}, + "resource_group_name": {"key": "resourceGroupName", "type": "str"}, + "resource_provider_name": {"key": "resourceProviderName", "type": "str"}, + "status": {"key": "status", "type": "str"}, + "sub_status": {"key": "subStatus", "type": "str"}, + "claims": {"key": "claims", "type": "RuleManagementEventClaimsDataSource"}, + } + + def __init__( + self, + *, + resource_uri: Optional[str] = None, + legacy_resource_id: Optional[str] = None, + resource_location: Optional[str] = None, + metric_namespace: Optional[str] = None, + event_name: Optional[str] = None, + event_source: Optional[str] = None, + level: Optional[str] = None, + operation_name: Optional[str] = None, + resource_group_name: Optional[str] = None, + resource_provider_name: Optional[str] = None, + status: Optional[str] = None, + sub_status: Optional[str] = None, + claims: Optional["_models.RuleManagementEventClaimsDataSource"] = None, + **kwargs: Any + ) -> None: + """ + :keyword resource_uri: the resource identifier of the resource the rule monitors. **NOTE**\\ : + this property cannot be updated for an existing rule. + :paramtype resource_uri: str + :keyword legacy_resource_id: the legacy resource identifier of the resource the rule monitors. + **NOTE**\\ : this property cannot be updated for an existing rule. + :paramtype legacy_resource_id: str + :keyword resource_location: the location of the resource. + :paramtype resource_location: str + :keyword metric_namespace: the namespace of the metric. + :paramtype metric_namespace: str + :keyword event_name: the event name. + :paramtype event_name: str + :keyword event_source: the event source. + :paramtype event_source: str + :keyword level: the level. + :paramtype level: str + :keyword operation_name: The name of the operation that should be checked for. If no name is + provided, any operation will match. + :paramtype operation_name: str + :keyword resource_group_name: the resource group name. + :paramtype resource_group_name: str + :keyword resource_provider_name: the resource provider name. + :paramtype resource_provider_name: str + :keyword status: The status of the operation that should be checked for. If no status is + provided, any status will match. + :paramtype status: str + :keyword sub_status: the substatus. + :paramtype sub_status: str + :keyword claims: the claims. + :paramtype claims: ~azure.mgmt.monitor.v2014_04_01.models.RuleManagementEventClaimsDataSource + """ + super().__init__( + resource_uri=resource_uri, + legacy_resource_id=legacy_resource_id, + resource_location=resource_location, + metric_namespace=metric_namespace, + **kwargs + ) + self.odata_type: str = "Microsoft.Azure.Management.Insights.Models.RuleManagementEventDataSource" + self.event_name = event_name + self.event_source = event_source + self.level = level + self.operation_name = operation_name + self.resource_group_name = resource_group_name + self.resource_provider_name = resource_provider_name + self.status = status + self.sub_status = sub_status + self.claims = claims + + +class RuleMetricDataSource(RuleDataSource): + """A rule metric data source. The discriminator value is always RuleMetricDataSource in this case. + + All required parameters must be populated in order to send to server. + + :ivar odata_type: specifies the type of data source. There are two types of rule data sources: + RuleMetricDataSource and RuleManagementEventDataSource. Required. + :vartype odata_type: str + :ivar resource_uri: the resource identifier of the resource the rule monitors. **NOTE**\\ : + this property cannot be updated for an existing rule. + :vartype resource_uri: str + :ivar legacy_resource_id: the legacy resource identifier of the resource the rule monitors. + **NOTE**\\ : this property cannot be updated for an existing rule. + :vartype legacy_resource_id: str + :ivar resource_location: the location of the resource. + :vartype resource_location: str + :ivar metric_namespace: the namespace of the metric. + :vartype metric_namespace: str + :ivar metric_name: the name of the metric that defines what the rule monitors. + :vartype metric_name: str + """ + + _validation = { + "odata_type": {"required": True}, + } + + _attribute_map = { + "odata_type": {"key": "odata\\.type", "type": "str"}, + "resource_uri": {"key": "resourceUri", "type": "str"}, + "legacy_resource_id": {"key": "legacyResourceId", "type": "str"}, + "resource_location": {"key": "resourceLocation", "type": "str"}, + "metric_namespace": {"key": "metricNamespace", "type": "str"}, + "metric_name": {"key": "metricName", "type": "str"}, + } + + def __init__( + self, + *, + resource_uri: Optional[str] = None, + legacy_resource_id: Optional[str] = None, + resource_location: Optional[str] = None, + metric_namespace: Optional[str] = None, + metric_name: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword resource_uri: the resource identifier of the resource the rule monitors. **NOTE**\\ : + this property cannot be updated for an existing rule. + :paramtype resource_uri: str + :keyword legacy_resource_id: the legacy resource identifier of the resource the rule monitors. + **NOTE**\\ : this property cannot be updated for an existing rule. + :paramtype legacy_resource_id: str + :keyword resource_location: the location of the resource. + :paramtype resource_location: str + :keyword metric_namespace: the namespace of the metric. + :paramtype metric_namespace: str + :keyword metric_name: the name of the metric that defines what the rule monitors. + :paramtype metric_name: str + """ + super().__init__( + resource_uri=resource_uri, + legacy_resource_id=legacy_resource_id, + resource_location=resource_location, + metric_namespace=metric_namespace, + **kwargs + ) + self.odata_type: str = "Microsoft.Azure.Management.Insights.Models.RuleMetricDataSource" + self.metric_name = metric_name + + +class RuleWebhookAction(RuleAction): + """Specifies the action to post to service when the rule condition is evaluated. The discriminator + is always RuleWebhookAction in this case. + + All required parameters must be populated in order to send to server. + + :ivar odata_type: specifies the type of the action. There are two types of actions: + RuleEmailAction and RuleWebhookAction. Required. + :vartype odata_type: str + :ivar service_uri: the service uri to Post the notification when the alert activates or + resolves. + :vartype service_uri: str + :ivar properties: the dictionary of custom properties to include with the post operation. These + data are appended to the webhook payload. + :vartype properties: dict[str, str] + """ + + _validation = { + "odata_type": {"required": True}, + } + + _attribute_map = { + "odata_type": {"key": "odata\\.type", "type": "str"}, + "service_uri": {"key": "serviceUri", "type": "str"}, + "properties": {"key": "properties", "type": "{str}"}, + } + + def __init__( + self, *, service_uri: Optional[str] = None, properties: Optional[Dict[str, str]] = None, **kwargs: Any + ) -> None: + """ + :keyword service_uri: the service uri to Post the notification when the alert activates or + resolves. + :paramtype service_uri: str + :keyword properties: the dictionary of custom properties to include with the post operation. + These data are appended to the webhook payload. + :paramtype properties: dict[str, str] + """ + super().__init__(**kwargs) + self.odata_type: str = "Microsoft.Azure.Management.Insights.Models.RuleWebhookAction" + self.service_uri = service_uri + self.properties = properties + + +class ScaleAction(_serialization.Model): + """The parameters for the scaling action. + + All required parameters must be populated in order to send to server. + + :ivar direction: the scale direction. Whether the scaling action increases or decreases the + number of instances. Required. Known values are: "None", "Increase", and "Decrease". + :vartype direction: str or ~azure.mgmt.monitor.v2014_04_01.models.ScaleDirection + :ivar type: the type of action that should occur when the scale rule fires. Required. Known + values are: "ChangeCount", "PercentChangeCount", "ExactCount", and "ServiceAllowedNextValue". + :vartype type: str or ~azure.mgmt.monitor.v2014_04_01.models.ScaleType + :ivar value: the number of instances that are involved in the scaling action. This value must + be 1 or greater. The default value is 1. + :vartype value: str + :ivar cooldown: the amount of time to wait since the last scaling action before this action + occurs. It must be between 1 week and 1 minute in ISO 8601 format. Required. + :vartype cooldown: ~datetime.timedelta + """ + + _validation = { + "direction": {"required": True}, + "type": {"required": True}, + "cooldown": {"required": True}, + } + + _attribute_map = { + "direction": {"key": "direction", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "value": {"key": "value", "type": "str"}, + "cooldown": {"key": "cooldown", "type": "duration"}, + } + + def __init__( + self, + *, + direction: Union[str, "_models.ScaleDirection"], + type: Union[str, "_models.ScaleType"], + cooldown: datetime.timedelta, + value: str = "1", + **kwargs: Any + ) -> None: + """ + :keyword direction: the scale direction. Whether the scaling action increases or decreases the + number of instances. Required. Known values are: "None", "Increase", and "Decrease". + :paramtype direction: str or ~azure.mgmt.monitor.v2014_04_01.models.ScaleDirection + :keyword type: the type of action that should occur when the scale rule fires. Required. Known + values are: "ChangeCount", "PercentChangeCount", "ExactCount", and "ServiceAllowedNextValue". + :paramtype type: str or ~azure.mgmt.monitor.v2014_04_01.models.ScaleType + :keyword value: the number of instances that are involved in the scaling action. This value + must be 1 or greater. The default value is 1. + :paramtype value: str + :keyword cooldown: the amount of time to wait since the last scaling action before this action + occurs. It must be between 1 week and 1 minute in ISO 8601 format. Required. + :paramtype cooldown: ~datetime.timedelta + """ + super().__init__(**kwargs) + self.direction = direction + self.type = type + self.value = value + self.cooldown = cooldown + + +class ScaleCapacity(_serialization.Model): + """The number of instances that can be used during this profile. + + All required parameters must be populated in order to send to server. + + :ivar minimum: the minimum number of instances for the resource. Required. + :vartype minimum: str + :ivar maximum: the maximum number of instances for the resource. The actual maximum number of + instances is limited by the cores that are available in the subscription. Required. + :vartype maximum: str + :ivar default: the number of instances that will be set if metrics are not available for + evaluation. The default is only used if the current instance count is lower than the default. + Required. + :vartype default: str + """ + + _validation = { + "minimum": {"required": True}, + "maximum": {"required": True}, + "default": {"required": True}, + } + + _attribute_map = { + "minimum": {"key": "minimum", "type": "str"}, + "maximum": {"key": "maximum", "type": "str"}, + "default": {"key": "default", "type": "str"}, + } + + def __init__(self, *, minimum: str, maximum: str, default: str, **kwargs: Any) -> None: + """ + :keyword minimum: the minimum number of instances for the resource. Required. + :paramtype minimum: str + :keyword maximum: the maximum number of instances for the resource. The actual maximum number + of instances is limited by the cores that are available in the subscription. Required. + :paramtype maximum: str + :keyword default: the number of instances that will be set if metrics are not available for + evaluation. The default is only used if the current instance count is lower than the default. + Required. + :paramtype default: str + """ + super().__init__(**kwargs) + self.minimum = minimum + self.maximum = maximum + self.default = default + + +class ScaleRule(_serialization.Model): + """A rule that provide the triggers and parameters for the scaling action. + + All required parameters must be populated in order to send to server. + + :ivar metric_trigger: the trigger that results in a scaling action. Required. + :vartype metric_trigger: ~azure.mgmt.monitor.v2014_04_01.models.MetricTrigger + :ivar scale_action: the parameters for the scaling action. Required. + :vartype scale_action: ~azure.mgmt.monitor.v2014_04_01.models.ScaleAction + """ + + _validation = { + "metric_trigger": {"required": True}, + "scale_action": {"required": True}, + } + + _attribute_map = { + "metric_trigger": {"key": "metricTrigger", "type": "MetricTrigger"}, + "scale_action": {"key": "scaleAction", "type": "ScaleAction"}, + } + + def __init__( + self, *, metric_trigger: "_models.MetricTrigger", scale_action: "_models.ScaleAction", **kwargs: Any + ) -> None: + """ + :keyword metric_trigger: the trigger that results in a scaling action. Required. + :paramtype metric_trigger: ~azure.mgmt.monitor.v2014_04_01.models.MetricTrigger + :keyword scale_action: the parameters for the scaling action. Required. + :paramtype scale_action: ~azure.mgmt.monitor.v2014_04_01.models.ScaleAction + """ + super().__init__(**kwargs) + self.metric_trigger = metric_trigger + self.scale_action = scale_action + + +class ScaleRuleMetricDimension(_serialization.Model): + """Specifies an auto scale rule metric dimension. + + All required parameters must be populated in order to send to server. + + :ivar dimension_name: Name of the dimension. Required. + :vartype dimension_name: str + :ivar operator: the dimension operator. Only 'Equals' and 'NotEquals' are supported. 'Equals' + being equal to any of the values. 'NotEquals' being not equal to all of the values. Required. + Known values are: "Equals" and "NotEquals". + :vartype operator: str or + ~azure.mgmt.monitor.v2014_04_01.models.ScaleRuleMetricDimensionOperationType + :ivar values: list of dimension values. For example: ["App1","App2"]. Required. + :vartype values: list[str] + """ + + _validation = { + "dimension_name": {"required": True}, + "operator": {"required": True}, + "values": {"required": True}, + } + + _attribute_map = { + "dimension_name": {"key": "DimensionName", "type": "str"}, + "operator": {"key": "Operator", "type": "str"}, + "values": {"key": "Values", "type": "[str]"}, + } + + def __init__( + self, + *, + dimension_name: str, + operator: Union[str, "_models.ScaleRuleMetricDimensionOperationType"], + values: List[str], + **kwargs: Any + ) -> None: + """ + :keyword dimension_name: Name of the dimension. Required. + :paramtype dimension_name: str + :keyword operator: the dimension operator. Only 'Equals' and 'NotEquals' are supported. + 'Equals' being equal to any of the values. 'NotEquals' being not equal to all of the values. + Required. Known values are: "Equals" and "NotEquals". + :paramtype operator: str or + ~azure.mgmt.monitor.v2014_04_01.models.ScaleRuleMetricDimensionOperationType + :keyword values: list of dimension values. For example: ["App1","App2"]. Required. + :paramtype values: list[str] + """ + super().__init__(**kwargs) + self.dimension_name = dimension_name + self.operator = operator + self.values = values + + +class ThresholdRuleCondition(RuleCondition): + """A rule condition based on a metric crossing a threshold. + + All required parameters must be populated in order to send to server. + + :ivar odata_type: specifies the type of condition. This can be one of three types: + ManagementEventRuleCondition (occurrences of management events), LocationThresholdRuleCondition + (based on the number of failures of a web test), and ThresholdRuleCondition (based on the + threshold of a metric). Required. + :vartype odata_type: str + :ivar data_source: the resource from which the rule collects its data. For this type dataSource + will always be of type RuleMetricDataSource. + :vartype data_source: ~azure.mgmt.monitor.v2014_04_01.models.RuleDataSource + :ivar operator: the operator used to compare the data and the threshold. Required. Known values + are: "GreaterThan", "GreaterThanOrEqual", "LessThan", and "LessThanOrEqual". + :vartype operator: str or ~azure.mgmt.monitor.v2014_04_01.models.ConditionOperator + :ivar threshold: the threshold value that activates the alert. Required. + :vartype threshold: float + :ivar window_size: the period of time (in ISO 8601 duration format) that is used to monitor + alert activity based on the threshold. If specified then it must be between 5 minutes and 1 + day. + :vartype window_size: ~datetime.timedelta + :ivar time_aggregation: the time aggregation operator. How the data that are collected should + be combined over time. The default value is the PrimaryAggregationType of the Metric. Known + values are: "Average", "Minimum", "Maximum", "Total", and "Last". + :vartype time_aggregation: str or + ~azure.mgmt.monitor.v2014_04_01.models.TimeAggregationOperator + """ + + _validation = { + "odata_type": {"required": True}, + "operator": {"required": True}, + "threshold": {"required": True}, + } + + _attribute_map = { + "odata_type": {"key": "odata\\.type", "type": "str"}, + "data_source": {"key": "dataSource", "type": "RuleDataSource"}, + "operator": {"key": "operator", "type": "str"}, + "threshold": {"key": "threshold", "type": "float"}, + "window_size": {"key": "windowSize", "type": "duration"}, + "time_aggregation": {"key": "timeAggregation", "type": "str"}, + } + + def __init__( + self, + *, + operator: Union[str, "_models.ConditionOperator"], + threshold: float, + data_source: Optional["_models.RuleDataSource"] = None, + window_size: Optional[datetime.timedelta] = None, + time_aggregation: Optional[Union[str, "_models.TimeAggregationOperator"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword data_source: the resource from which the rule collects its data. For this type + dataSource will always be of type RuleMetricDataSource. + :paramtype data_source: ~azure.mgmt.monitor.v2014_04_01.models.RuleDataSource + :keyword operator: the operator used to compare the data and the threshold. Required. Known + values are: "GreaterThan", "GreaterThanOrEqual", "LessThan", and "LessThanOrEqual". + :paramtype operator: str or ~azure.mgmt.monitor.v2014_04_01.models.ConditionOperator + :keyword threshold: the threshold value that activates the alert. Required. + :paramtype threshold: float + :keyword window_size: the period of time (in ISO 8601 duration format) that is used to monitor + alert activity based on the threshold. If specified then it must be between 5 minutes and 1 + day. + :paramtype window_size: ~datetime.timedelta + :keyword time_aggregation: the time aggregation operator. How the data that are collected + should be combined over time. The default value is the PrimaryAggregationType of the Metric. + Known values are: "Average", "Minimum", "Maximum", "Total", and "Last". + :paramtype time_aggregation: str or + ~azure.mgmt.monitor.v2014_04_01.models.TimeAggregationOperator + """ + super().__init__(data_source=data_source, **kwargs) + self.odata_type: str = "Microsoft.Azure.Management.Insights.Models.ThresholdRuleCondition" + self.operator = operator + self.threshold = threshold + self.window_size = window_size + self.time_aggregation = time_aggregation + + +class TimeWindow(_serialization.Model): + """A specific date-time for the profile. + + All required parameters must be populated in order to send to server. + + :ivar time_zone: the timezone of the start and end times for the profile. Some examples of + valid time zones are: Dateline Standard Time, UTC-11, Hawaiian Standard Time, Alaskan Standard + Time, Pacific Standard Time (Mexico), Pacific Standard Time, US Mountain Standard Time, + Mountain Standard Time (Mexico), Mountain Standard Time, Central America Standard Time, Central + Standard Time, Central Standard Time (Mexico), Canada Central Standard Time, SA Pacific + Standard Time, Eastern Standard Time, US Eastern Standard Time, Venezuela Standard Time, + Paraguay Standard Time, Atlantic Standard Time, Central Brazilian Standard Time, SA Western + Standard Time, Pacific SA Standard Time, Newfoundland Standard Time, E. South America Standard + Time, Argentina Standard Time, SA Eastern Standard Time, Greenland Standard Time, Montevideo + Standard Time, Bahia Standard Time, UTC-02, Mid-Atlantic Standard Time, Azores Standard Time, + Cape Verde Standard Time, Morocco Standard Time, UTC, GMT Standard Time, Greenwich Standard + Time, W. Europe Standard Time, Central Europe Standard Time, Romance Standard Time, Central + European Standard Time, W. Central Africa Standard Time, Namibia Standard Time, Jordan Standard + Time, GTB Standard Time, Middle East Standard Time, Egypt Standard Time, Syria Standard Time, + E. Europe Standard Time, South Africa Standard Time, FLE Standard Time, Turkey Standard Time, + Israel Standard Time, Kaliningrad Standard Time, Libya Standard Time, Arabic Standard Time, + Arab Standard Time, Belarus Standard Time, Russian Standard Time, E. Africa Standard Time, Iran + Standard Time, Arabian Standard Time, Azerbaijan Standard Time, Russia Time Zone 3, Mauritius + Standard Time, Georgian Standard Time, Caucasus Standard Time, Afghanistan Standard Time, West + Asia Standard Time, Ekaterinburg Standard Time, Pakistan Standard Time, India Standard Time, + Sri Lanka Standard Time, Nepal Standard Time, Central Asia Standard Time, Bangladesh Standard + Time, N. Central Asia Standard Time, Myanmar Standard Time, SE Asia Standard Time, North Asia + Standard Time, China Standard Time, North Asia East Standard Time, Singapore Standard Time, W. + Australia Standard Time, Taipei Standard Time, Ulaanbaatar Standard Time, Tokyo Standard Time, + Korea Standard Time, Yakutsk Standard Time, Cen. Australia Standard Time, AUS Central Standard + Time, E. Australia Standard Time, AUS Eastern Standard Time, West Pacific Standard Time, + Tasmania Standard Time, Magadan Standard Time, Vladivostok Standard Time, Russia Time Zone 10, + Central Pacific Standard Time, Russia Time Zone 11, New Zealand Standard Time, UTC+12, Fiji + Standard Time, Kamchatka Standard Time, Tonga Standard Time, Samoa Standard Time, Line Islands + Standard Time. + :vartype time_zone: str + :ivar start: the start time for the profile in ISO 8601 format. Required. + :vartype start: ~datetime.datetime + :ivar end: the end time for the profile in ISO 8601 format. Required. + :vartype end: ~datetime.datetime + """ + + _validation = { + "start": {"required": True}, + "end": {"required": True}, + } + + _attribute_map = { + "time_zone": {"key": "timeZone", "type": "str"}, + "start": {"key": "start", "type": "iso-8601"}, + "end": {"key": "end", "type": "iso-8601"}, + } + + def __init__( + self, *, start: datetime.datetime, end: datetime.datetime, time_zone: Optional[str] = None, **kwargs: Any + ) -> None: + """ + :keyword time_zone: the timezone of the start and end times for the profile. Some examples of + valid time zones are: Dateline Standard Time, UTC-11, Hawaiian Standard Time, Alaskan Standard + Time, Pacific Standard Time (Mexico), Pacific Standard Time, US Mountain Standard Time, + Mountain Standard Time (Mexico), Mountain Standard Time, Central America Standard Time, Central + Standard Time, Central Standard Time (Mexico), Canada Central Standard Time, SA Pacific + Standard Time, Eastern Standard Time, US Eastern Standard Time, Venezuela Standard Time, + Paraguay Standard Time, Atlantic Standard Time, Central Brazilian Standard Time, SA Western + Standard Time, Pacific SA Standard Time, Newfoundland Standard Time, E. South America Standard + Time, Argentina Standard Time, SA Eastern Standard Time, Greenland Standard Time, Montevideo + Standard Time, Bahia Standard Time, UTC-02, Mid-Atlantic Standard Time, Azores Standard Time, + Cape Verde Standard Time, Morocco Standard Time, UTC, GMT Standard Time, Greenwich Standard + Time, W. Europe Standard Time, Central Europe Standard Time, Romance Standard Time, Central + European Standard Time, W. Central Africa Standard Time, Namibia Standard Time, Jordan Standard + Time, GTB Standard Time, Middle East Standard Time, Egypt Standard Time, Syria Standard Time, + E. Europe Standard Time, South Africa Standard Time, FLE Standard Time, Turkey Standard Time, + Israel Standard Time, Kaliningrad Standard Time, Libya Standard Time, Arabic Standard Time, + Arab Standard Time, Belarus Standard Time, Russian Standard Time, E. Africa Standard Time, Iran + Standard Time, Arabian Standard Time, Azerbaijan Standard Time, Russia Time Zone 3, Mauritius + Standard Time, Georgian Standard Time, Caucasus Standard Time, Afghanistan Standard Time, West + Asia Standard Time, Ekaterinburg Standard Time, Pakistan Standard Time, India Standard Time, + Sri Lanka Standard Time, Nepal Standard Time, Central Asia Standard Time, Bangladesh Standard + Time, N. Central Asia Standard Time, Myanmar Standard Time, SE Asia Standard Time, North Asia + Standard Time, China Standard Time, North Asia East Standard Time, Singapore Standard Time, W. + Australia Standard Time, Taipei Standard Time, Ulaanbaatar Standard Time, Tokyo Standard Time, + Korea Standard Time, Yakutsk Standard Time, Cen. Australia Standard Time, AUS Central Standard + Time, E. Australia Standard Time, AUS Eastern Standard Time, West Pacific Standard Time, + Tasmania Standard Time, Magadan Standard Time, Vladivostok Standard Time, Russia Time Zone 10, + Central Pacific Standard Time, Russia Time Zone 11, New Zealand Standard Time, UTC+12, Fiji + Standard Time, Kamchatka Standard Time, Tonga Standard Time, Samoa Standard Time, Line Islands + Standard Time. + :paramtype time_zone: str + :keyword start: the start time for the profile in ISO 8601 format. Required. + :paramtype start: ~datetime.datetime + :keyword end: the end time for the profile in ISO 8601 format. Required. + :paramtype end: ~datetime.datetime + """ + super().__init__(**kwargs) + self.time_zone = time_zone + self.start = start + self.end = end + + +class WebhookNotification(_serialization.Model): + """Webhook notification of an autoscale event. + + :ivar service_uri: the service address to receive the notification. + :vartype service_uri: str + :ivar properties: a property bag of settings. This value can be empty. + :vartype properties: dict[str, str] + """ + + _attribute_map = { + "service_uri": {"key": "serviceUri", "type": "str"}, + "properties": {"key": "properties", "type": "{str}"}, + } + + def __init__( + self, *, service_uri: Optional[str] = None, properties: Optional[Dict[str, str]] = None, **kwargs: Any + ) -> None: + """ + :keyword service_uri: the service address to receive the notification. + :paramtype service_uri: str + :keyword properties: a property bag of settings. This value can be empty. + :paramtype properties: dict[str, str] + """ + super().__init__(**kwargs) + self.service_uri = service_uri + self.properties = properties diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2014_04_01/models/_monitor_management_client_enums.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2014_04_01/models/_monitor_management_client_enums.py new file mode 100644 index 000000000000..27266a2765e3 --- /dev/null +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2014_04_01/models/_monitor_management_client_enums.py @@ -0,0 +1,106 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from enum import Enum +from azure.core import CaseInsensitiveEnumMeta + + +class ComparisonOperationType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """the operator that is used to compare the metric data and the threshold.""" + + EQUALS = "Equals" + NOT_EQUALS = "NotEquals" + GREATER_THAN = "GreaterThan" + GREATER_THAN_OR_EQUAL = "GreaterThanOrEqual" + LESS_THAN = "LessThan" + LESS_THAN_OR_EQUAL = "LessThanOrEqual" + + +class ConditionOperator(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Operators allowed in the rule condition.""" + + GREATER_THAN = "GreaterThan" + GREATER_THAN_OR_EQUAL = "GreaterThanOrEqual" + LESS_THAN = "LessThan" + LESS_THAN_OR_EQUAL = "LessThanOrEqual" + + +class MetricStatisticType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """the metric statistic type. How the metrics from multiple instances are combined.""" + + AVERAGE = "Average" + MIN = "Min" + MAX = "Max" + SUM = "Sum" + COUNT = "Count" + + +class RecurrenceFrequency(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """the recurrence frequency. How often the schedule profile should take effect. This value must be + Week, meaning each week will have the same set of profiles. For example, to set a daily + schedule, set **schedule** to every day of the week. The frequency property specifies that the + schedule is repeated weekly. + """ + + NONE = "None" + SECOND = "Second" + MINUTE = "Minute" + HOUR = "Hour" + DAY = "Day" + WEEK = "Week" + MONTH = "Month" + YEAR = "Year" + + +class ScaleDirection(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """the scale direction. Whether the scaling action increases or decreases the number of instances.""" + + NONE = "None" + INCREASE = "Increase" + DECREASE = "Decrease" + + +class ScaleRuleMetricDimensionOperationType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """the dimension operator. Only 'Equals' and 'NotEquals' are supported. 'Equals' being equal to + any of the values. 'NotEquals' being not equal to all of the values. + """ + + EQUALS = "Equals" + NOT_EQUALS = "NotEquals" + + +class ScaleType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """the type of action that should occur when the scale rule fires.""" + + CHANGE_COUNT = "ChangeCount" + PERCENT_CHANGE_COUNT = "PercentChangeCount" + EXACT_COUNT = "ExactCount" + SERVICE_ALLOWED_NEXT_VALUE = "ServiceAllowedNextValue" + + +class TimeAggregationOperator(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Aggregation operators allowed in a rule.""" + + AVERAGE = "Average" + MINIMUM = "Minimum" + MAXIMUM = "Maximum" + TOTAL = "Total" + LAST = "Last" + + +class TimeAggregationType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """time aggregation type. How the data that is collected should be combined over time. The default + value is Average. + """ + + AVERAGE = "Average" + MINIMUM = "Minimum" + MAXIMUM = "Maximum" + TOTAL = "Total" + COUNT = "Count" + LAST = "Last" diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2014_04_01/models/_patch.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2014_04_01/models/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2014_04_01/models/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2014_04_01/operations/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2014_04_01/operations/__init__.py new file mode 100644 index 000000000000..4d9f261f8722 --- /dev/null +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2014_04_01/operations/__init__.py @@ -0,0 +1,27 @@ +# 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. +# -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._alert_rules_operations import AlertRulesOperations # type: ignore +from ._autoscale_settings_operations import AutoscaleSettingsOperations # type: ignore + +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "AlertRulesOperations", + "AutoscaleSettingsOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/operations/_alert_rules_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2014_04_01/operations/_alert_rules_operations.py similarity index 78% rename from sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/operations/_alert_rules_operations.py rename to sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2014_04_01/operations/_alert_rules_operations.py index 4d80bab51be1..3d28297e4f3d 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/operations/_alert_rules_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2014_04_01/operations/_alert_rules_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,7 +5,10 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload +import urllib.parse from azure.core.exceptions import ( ClientAuthenticationError, @@ -18,16 +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, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -58,7 +62,7 @@ def build_create_or_update_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -91,7 +95,7 @@ def build_delete_request(resource_group_name: str, rule_name: str, subscription_ "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -122,7 +126,7 @@ def build_get_request(resource_group_name: str, rule_name: str, subscription_id: "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -154,7 +158,7 @@ def build_update_request(resource_group_name: str, rule_name: str, subscription_ "ruleName": _SERIALIZER.url("rule_name", rule_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -186,7 +190,7 @@ def build_list_by_resource_group_request(resource_group_name: str, subscription_ "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -210,7 +214,7 @@ def build_list_by_subscription_request(subscription_id: str, **kwargs: Any) -> H "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -227,7 +231,7 @@ class AlertRulesOperations: **DO NOT** instantiate this class directly. Instead, you should access the following operations through - :class:`~azure.mgmt.monitor.v2015_04_01.MonitorManagementClient`'s + :class:`~azure.mgmt.monitor.v2014_04_01.MonitorManagementClient`'s :attr:`alert_rules` attribute. """ @@ -239,6 +243,7 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @overload def create_or_update( @@ -258,13 +263,12 @@ def create_or_update( :param rule_name: The name of the rule. Required. :type rule_name: str :param parameters: The parameters of the rule to create or update. Required. - :type parameters: ~azure.mgmt.monitor.v2015_04_01.models.AlertRuleResource + :type parameters: ~azure.mgmt.monitor.v2014_04_01.models.AlertRuleResource :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: AlertRuleResource or the result of cls(response) - :rtype: ~azure.mgmt.monitor.v2015_04_01.models.AlertRuleResource + :rtype: ~azure.mgmt.monitor.v2014_04_01.models.AlertRuleResource :raises ~azure.core.exceptions.HttpResponseError: """ @@ -273,7 +277,7 @@ def create_or_update( self, resource_group_name: str, rule_name: str, - parameters: IO, + parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -286,19 +290,22 @@ def create_or_update( :param rule_name: The name of the rule. Required. :type rule_name: str :param parameters: The parameters of the rule to create or update. Required. - :type parameters: IO + :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: AlertRuleResource or the result of cls(response) - :rtype: ~azure.mgmt.monitor.v2015_04_01.models.AlertRuleResource + :rtype: ~azure.mgmt.monitor.v2014_04_01.models.AlertRuleResource :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace def create_or_update( - self, resource_group_name: str, rule_name: str, parameters: Union[_models.AlertRuleResource, IO], **kwargs: Any + self, + resource_group_name: str, + rule_name: str, + parameters: Union[_models.AlertRuleResource, IO[bytes]], + **kwargs: Any ) -> _models.AlertRuleResource: """Creates or updates a classic metric alert rule. @@ -308,17 +315,13 @@ def create_or_update( :param rule_name: The name of the rule. Required. :type rule_name: str :param parameters: The parameters of the rule to create or update. Is either a - AlertRuleResource type or a IO type. Required. - :type parameters: ~azure.mgmt.monitor.v2015_04_01.models.AlertRuleResource 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 + AlertRuleResource type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.monitor.v2014_04_01.models.AlertRuleResource or IO[bytes] :return: AlertRuleResource or the result of cls(response) - :rtype: ~azure.mgmt.monitor.v2015_04_01.models.AlertRuleResource + :rtype: ~azure.mgmt.monitor.v2014_04_01.models.AlertRuleResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -329,19 +332,19 @@ def create_or_update( _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", "2014-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2014-04-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.AlertRuleResource] = 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, "AlertRuleResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, rule_name=rule_name, subscription_id=self._config.subscription_id, @@ -349,16 +352,14 @@ def create_or_update( 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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -368,21 +369,13 @@ def create_or_update( 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("AlertRuleResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("AlertRuleResource", pipeline_response) + deserialized = self._deserialize("AlertRuleResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/alertrules/{ruleName}" - } - @distributed_trace def delete( # pylint: disable=inconsistent-return-statements self, resource_group_name: str, rule_name: str, **kwargs: Any @@ -394,12 +387,11 @@ def delete( # pylint: disable=inconsistent-return-statements :type resource_group_name: str :param rule_name: The name of the rule. Required. :type 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, @@ -410,24 +402,22 @@ def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2014-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2014-04-01")) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, rule_name=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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -438,11 +428,7 @@ def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/alertrules/{ruleName}" - } + return cls(pipeline_response, None, {}) # type: ignore @distributed_trace def get(self, resource_group_name: str, rule_name: str, **kwargs: Any) -> _models.AlertRuleResource: @@ -453,12 +439,11 @@ def get(self, resource_group_name: str, rule_name: str, **kwargs: Any) -> _model :type resource_group_name: str :param rule_name: The name of the rule. Required. :type rule_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: AlertRuleResource or the result of cls(response) - :rtype: ~azure.mgmt.monitor.v2015_04_01.models.AlertRuleResource + :rtype: ~azure.mgmt.monitor.v2014_04_01.models.AlertRuleResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -469,24 +454,22 @@ def get(self, resource_group_name: str, rule_name: str, **kwargs: Any) -> _model _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2014-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2014-04-01")) cls: ClsType[_models.AlertRuleResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, rule_name=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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -496,16 +479,12 @@ def get(self, resource_group_name: str, rule_name: str, **kwargs: Any) -> _model error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("AlertRuleResource", pipeline_response) + deserialized = self._deserialize("AlertRuleResource", 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.Insights/alertrules/{ruleName}" - } + return deserialized # type: ignore @overload def update( @@ -526,13 +505,12 @@ def update( :param rule_name: The name of the rule. Required. :type rule_name: str :param alert_rules_resource: Parameters supplied to the operation. Required. - :type alert_rules_resource: ~azure.mgmt.monitor.v2015_04_01.models.AlertRuleResourcePatch + :type alert_rules_resource: ~azure.mgmt.monitor.v2014_04_01.models.AlertRuleResourcePatch :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: AlertRuleResource or the result of cls(response) - :rtype: ~azure.mgmt.monitor.v2015_04_01.models.AlertRuleResource + :rtype: ~azure.mgmt.monitor.v2014_04_01.models.AlertRuleResource :raises ~azure.core.exceptions.HttpResponseError: """ @@ -541,7 +519,7 @@ def update( self, resource_group_name: str, rule_name: str, - alert_rules_resource: IO, + alert_rules_resource: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -555,13 +533,12 @@ def update( :param rule_name: The name of the rule. Required. :type rule_name: str :param alert_rules_resource: Parameters supplied to the operation. Required. - :type alert_rules_resource: IO + :type alert_rules_resource: 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: AlertRuleResource or the result of cls(response) - :rtype: ~azure.mgmt.monitor.v2015_04_01.models.AlertRuleResource + :rtype: ~azure.mgmt.monitor.v2014_04_01.models.AlertRuleResource :raises ~azure.core.exceptions.HttpResponseError: """ @@ -570,7 +547,7 @@ def update( self, resource_group_name: str, rule_name: str, - alert_rules_resource: Union[_models.AlertRuleResourcePatch, IO], + alert_rules_resource: Union[_models.AlertRuleResourcePatch, IO[bytes]], **kwargs: Any ) -> _models.AlertRuleResource: """Updates an existing classic metric AlertRuleResource. To update other fields use the @@ -582,17 +559,14 @@ def update( :param rule_name: The name of the rule. Required. :type rule_name: str :param alert_rules_resource: Parameters supplied to the operation. Is either a - AlertRuleResourcePatch type or a IO type. Required. - :type alert_rules_resource: ~azure.mgmt.monitor.v2015_04_01.models.AlertRuleResourcePatch 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 + AlertRuleResourcePatch type or a IO[bytes] type. Required. + :type alert_rules_resource: ~azure.mgmt.monitor.v2014_04_01.models.AlertRuleResourcePatch or + IO[bytes] :return: AlertRuleResource or the result of cls(response) - :rtype: ~azure.mgmt.monitor.v2015_04_01.models.AlertRuleResource + :rtype: ~azure.mgmt.monitor.v2014_04_01.models.AlertRuleResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -603,19 +577,19 @@ def update( _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", "2014-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2014-04-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.AlertRuleResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(alert_rules_resource, (IO, bytes)): + if isinstance(alert_rules_resource, (IOBase, bytes)): _content = alert_rules_resource else: _json = self._serialize.body(alert_rules_resource, "AlertRuleResourcePatch") - request = build_update_request( + _request = build_update_request( resource_group_name=resource_group_name, rule_name=rule_name, subscription_id=self._config.subscription_id, @@ -623,16 +597,14 @@ def update( 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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -642,21 +614,13 @@ def update( 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("AlertRuleResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("AlertRuleResource", pipeline_response) + deserialized = self._deserialize("AlertRuleResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/alertrules/{ruleName}" - } - @distributed_trace def list_by_resource_group(self, resource_group_name: str, **kwargs: Any) -> Iterable["_models.AlertRuleResource"]: """List the classic metric alert rules within a resource group. @@ -664,18 +628,17 @@ def list_by_resource_group(self, resource_group_name: str, **kwargs: Any) -> Ite :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either AlertRuleResource or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.monitor.v2015_04_01.models.AlertRuleResource] + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.monitor.v2014_04_01.models.AlertRuleResource] :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", "2014-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2014-04-01")) cls: ClsType[_models.AlertRuleResourceCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -686,23 +649,31 @@ 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_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: - request = HttpRequest("GET", next_link) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + # 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._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("AlertRuleResourceCollection", pipeline_response) @@ -712,11 +683,11 @@ def extract_data(pipeline_response): return None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -729,26 +700,21 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/alertrules" - } - @distributed_trace def list_by_subscription(self, **kwargs: Any) -> Iterable["_models.AlertRuleResource"]: """List the classic metric alert rules within a subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either AlertRuleResource or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.monitor.v2015_04_01.models.AlertRuleResource] + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.monitor.v2014_04_01.models.AlertRuleResource] :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", "2014-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2014-04-01")) cls: ClsType[_models.AlertRuleResourceCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -759,22 +725,30 @@ def list_by_subscription(self, **kwargs: Any) -> Iterable["_models.AlertRuleReso def prepare_request(next_link=None): if not next_link: - request = build_list_by_subscription_request( + _request = build_list_by_subscription_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_subscription.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: - request = HttpRequest("GET", next_link) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + # 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._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("AlertRuleResourceCollection", pipeline_response) @@ -784,11 +758,11 @@ def extract_data(pipeline_response): return None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -800,5 +774,3 @@ def get_next(next_link=None): return pipeline_response return ItemPaged(get_next, extract_data) - - list_by_subscription.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/alertrules"} diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/operations/_alert_rules_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2014_04_01/operations/_autoscale_settings_operations.py similarity index 61% rename from sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/operations/_alert_rules_operations.py rename to sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2014_04_01/operations/_autoscale_settings_operations.py index f08dee11cab6..8c2030546814 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/operations/_alert_rules_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2014_04_01/operations/_autoscale_settings_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,7 +5,10 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload +import urllib.parse from azure.core.exceptions import ( ClientAuthenticationError, @@ -18,16 +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, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -35,74 +39,75 @@ _SERIALIZER.client_side_validation = False -def build_create_or_update_request( - resource_group_name: str, 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: str = kwargs.pop("api_version", _params.pop("api-version", "2014-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.Insights/alertrules/{ruleName}", + "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/autoscalesettings", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url( "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 ), - "ruleName": _SERIALIZER.url("rule_name", rule_name, "str"), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _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, rule_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: +def build_create_or_update_request( + resource_group_name: str, autoscale_setting_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: str = kwargs.pop("api_version", _params.pop("api-version", "2014-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.Insights/alertrules/{ruleName}", + "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/autoscalesettings/{autoscaleSettingName}", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url( "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 ), - "ruleName": _SERIALIZER.url("rule_name", rule_name, "str"), + "autoscaleSettingName": _SERIALIZER.url("autoscale_setting_name", autoscale_setting_name, "str"), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _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="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) -def build_get_request(resource_group_name: str, rule_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: +def build_delete_request( + resource_group_name: str, autoscale_setting_name: str, subscription_id: str, **kwargs: Any +) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -112,17 +117,17 @@ def build_get_request(resource_group_name: str, rule_name: str, subscription_id: # Construct URL _url = kwargs.pop( "template_url", - "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/alertrules/{ruleName}", + "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/autoscalesettings/{autoscaleSettingName}", ) # pylint: disable=line-too-long path_format_arguments = { "resourceGroupName": _SERIALIZER.url( "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 ), - "ruleName": _SERIALIZER.url("rule_name", rule_name, "str"), + "autoscaleSettingName": _SERIALIZER.url("autoscale_setting_name", autoscale_setting_name, "str"), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -130,71 +135,76 @@ def build_get_request(resource_group_name: str, rule_name: str, subscription_id: # 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_update_request(resource_group_name: str, rule_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: +def build_get_request( + resource_group_name: str, autoscale_setting_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: str = kwargs.pop("api_version", _params.pop("api-version", "2014-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.Insights/alertrules/{ruleName}", + "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/autoscalesettings/{autoscaleSettingName}", ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), "resourceGroupName": _SERIALIZER.url( "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 ), - "ruleName": _SERIALIZER.url("rule_name", rule_name, "str"), + "autoscaleSettingName": _SERIALIZER.url("autoscale_setting_name", autoscale_setting_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _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="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_list_by_resource_group_request(resource_group_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: +def build_update_request( + resource_group_name: str, autoscale_setting_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: str = kwargs.pop("api_version", _params.pop("api-version", "2014-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.Insights/alertrules", + "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/autoscalesettings/{autoscaleSettingName}", ) # pylint: disable=line-too-long path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), "resourceGroupName": _SERIALIZER.url( "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 ), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "autoscaleSettingName": _SERIALIZER.url("autoscale_setting_name", autoscale_setting_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _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="PATCH", url=_url, params=_params, headers=_headers, **kwargs) def build_list_by_subscription_request(subscription_id: str, **kwargs: Any) -> HttpRequest: @@ -205,12 +215,12 @@ def build_list_by_subscription_request(subscription_id: str, **kwargs: Any) -> H accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/alertrules") + _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/autoscalesettings") path_format_arguments = { "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -221,14 +231,14 @@ def build_list_by_subscription_request(subscription_id: str, **kwargs: Any) -> H return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -class AlertRulesOperations: +class AutoscaleSettingsOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through - :class:`~azure.mgmt.monitor.v2015_07_01.MonitorManagementClient`'s - :attr:`alert_rules` attribute. + :class:`~azure.mgmt.monitor.v2014_04_01.MonitorManagementClient`'s + :attr:`autoscale_settings` attribute. """ models = _models @@ -239,32 +249,115 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") + + @distributed_trace + def list_by_resource_group( + self, resource_group_name: str, **kwargs: Any + ) -> Iterable["_models.AutoscaleSettingResource"]: + """Lists the autoscale settings for a resource group. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :return: An iterator like instance of either AutoscaleSettingResource or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.monitor.v2014_04_01.models.AutoscaleSettingResource] + :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._api_version or "2014-04-01")) + cls: ClsType[_models.AutoscaleSettingResourceCollection] = 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_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._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("AutoscaleSettingResourceCollection", 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) @overload def create_or_update( self, resource_group_name: str, - rule_name: str, - parameters: _models.AlertRuleResource, + autoscale_setting_name: str, + parameters: _models.AutoscaleSettingResource, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.AlertRuleResource: - """Creates or updates a classic metric alert rule. + ) -> _models.AutoscaleSettingResource: + """Creates or updates an autoscale setting. :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :param rule_name: The name of the rule. Required. - :type rule_name: str - :param parameters: The parameters of the rule to create or update. Required. - :type parameters: ~azure.mgmt.monitor.v2015_07_01.models.AlertRuleResource + :param autoscale_setting_name: The autoscale setting name. Required. + :type autoscale_setting_name: str + :param parameters: Parameters supplied to the operation. Required. + :type parameters: ~azure.mgmt.monitor.v2014_04_01.models.AutoscaleSettingResource :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: AlertRuleResource or the result of cls(response) - :rtype: ~azure.mgmt.monitor.v2015_07_01.models.AlertRuleResource + :return: AutoscaleSettingResource or the result of cls(response) + :rtype: ~azure.mgmt.monitor.v2014_04_01.models.AutoscaleSettingResource :raises ~azure.core.exceptions.HttpResponseError: """ @@ -272,53 +365,52 @@ def create_or_update( def create_or_update( self, resource_group_name: str, - rule_name: str, - parameters: IO, + autoscale_setting_name: str, + parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.AlertRuleResource: - """Creates or updates a classic metric alert rule. + ) -> _models.AutoscaleSettingResource: + """Creates or updates an autoscale setting. :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :param rule_name: The name of the rule. Required. - :type rule_name: str - :param parameters: The parameters of the rule to create or update. Required. - :type parameters: IO + :param autoscale_setting_name: The autoscale setting name. Required. + :type autoscale_setting_name: str + :param parameters: Parameters supplied to the operation. 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: AlertRuleResource or the result of cls(response) - :rtype: ~azure.mgmt.monitor.v2015_07_01.models.AlertRuleResource + :return: AutoscaleSettingResource or the result of cls(response) + :rtype: ~azure.mgmt.monitor.v2014_04_01.models.AutoscaleSettingResource :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace def create_or_update( - self, resource_group_name: str, rule_name: str, parameters: Union[_models.AlertRuleResource, IO], **kwargs: Any - ) -> _models.AlertRuleResource: - """Creates or updates a classic metric alert rule. + self, + resource_group_name: str, + autoscale_setting_name: str, + parameters: Union[_models.AutoscaleSettingResource, IO[bytes]], + **kwargs: Any + ) -> _models.AutoscaleSettingResource: + """Creates or updates an autoscale setting. :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :param rule_name: The name of the rule. Required. - :type rule_name: str - :param parameters: The parameters of the rule to create or update. Is either a - AlertRuleResource type or a IO type. Required. - :type parameters: ~azure.mgmt.monitor.v2015_07_01.models.AlertRuleResource 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: AlertRuleResource or the result of cls(response) - :rtype: ~azure.mgmt.monitor.v2015_07_01.models.AlertRuleResource + :param autoscale_setting_name: The autoscale setting name. Required. + :type autoscale_setting_name: str + :param parameters: Parameters supplied to the operation. Is either a AutoscaleSettingResource + type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.monitor.v2014_04_01.models.AutoscaleSettingResource or IO[bytes] + :return: AutoscaleSettingResource or the result of cls(response) + :rtype: ~azure.mgmt.monitor.v2014_04_01.models.AutoscaleSettingResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -329,36 +421,34 @@ def create_or_update( _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", "2014-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2014-04-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.AlertRuleResource] = kwargs.pop("cls", None) + cls: ClsType[_models.AutoscaleSettingResource] = 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, "AlertRuleResource") + _json = self._serialize.body(parameters, "AutoscaleSettingResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, - rule_name=rule_name, + autoscale_setting_name=autoscale_setting_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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -368,38 +458,29 @@ def create_or_update( 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("AlertRuleResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("AlertRuleResource", pipeline_response) + deserialized = self._deserialize("AutoscaleSettingResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/alertrules/{ruleName}" - } - @distributed_trace def delete( # pylint: disable=inconsistent-return-statements - self, resource_group_name: str, rule_name: str, **kwargs: Any + self, resource_group_name: str, autoscale_setting_name: str, **kwargs: Any ) -> None: - """Deletes a classic metric alert rule. + """Deletes and autoscale setting. :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :param rule_name: The name of the rule. Required. - :type rule_name: str - :keyword callable cls: A custom type or function that will be passed the direct response + :param autoscale_setting_name: The autoscale setting name. Required. + :type autoscale_setting_name: str :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, @@ -410,24 +491,22 @@ def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2014-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2014-04-01")) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, - rule_name=rule_name, + autoscale_setting_name=autoscale_setting_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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -438,27 +517,24 @@ def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/alertrules/{ruleName}" - } + return cls(pipeline_response, None, {}) # type: ignore @distributed_trace - def get(self, resource_group_name: str, rule_name: str, **kwargs: Any) -> _models.AlertRuleResource: - """Gets a classic metric alert rule. + def get( + self, resource_group_name: str, autoscale_setting_name: str, **kwargs: Any + ) -> _models.AutoscaleSettingResource: + """Gets an autoscale setting. :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :param rule_name: The name of the rule. Required. - :type rule_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: AlertRuleResource or the result of cls(response) - :rtype: ~azure.mgmt.monitor.v2015_07_01.models.AlertRuleResource + :param autoscale_setting_name: The autoscale setting name. Required. + :type autoscale_setting_name: str + :return: AutoscaleSettingResource or the result of cls(response) + :rtype: ~azure.mgmt.monitor.v2014_04_01.models.AutoscaleSettingResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -469,24 +545,22 @@ def get(self, resource_group_name: str, rule_name: str, **kwargs: Any) -> _model _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2014-04-01")) - cls: ClsType[_models.AlertRuleResource] = kwargs.pop("cls", None) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2014-04-01")) + cls: ClsType[_models.AutoscaleSettingResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, - rule_name=rule_name, + autoscale_setting_name=autoscale_setting_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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -496,43 +570,39 @@ def get(self, resource_group_name: str, rule_name: str, **kwargs: Any) -> _model error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("AlertRuleResource", pipeline_response) + deserialized = self._deserialize("AutoscaleSettingResource", 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.Insights/alertrules/{ruleName}" - } + return deserialized # type: ignore @overload def update( self, resource_group_name: str, - rule_name: str, - alert_rules_resource: _models.AlertRuleResourcePatch, + autoscale_setting_name: str, + autoscale_setting_resource: _models.AutoscaleSettingResourcePatch, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.AlertRuleResource: - """Updates an existing classic metric AlertRuleResource. To update other fields use the - CreateOrUpdate method. + ) -> _models.AutoscaleSettingResource: + """Updates an existing AutoscaleSettingsResource. To update other fields use the CreateOrUpdate + method. :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :param rule_name: The name of the rule. Required. - :type rule_name: str - :param alert_rules_resource: Parameters supplied to the operation. Required. - :type alert_rules_resource: ~azure.mgmt.monitor.v2015_07_01.models.AlertRuleResourcePatch + :param autoscale_setting_name: The autoscale setting name. Required. + :type autoscale_setting_name: str + :param autoscale_setting_resource: Parameters supplied to the operation. Required. + :type autoscale_setting_resource: + ~azure.mgmt.monitor.v2014_04_01.models.AutoscaleSettingResourcePatch :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: AlertRuleResource or the result of cls(response) - :rtype: ~azure.mgmt.monitor.v2015_07_01.models.AlertRuleResource + :return: AutoscaleSettingResource or the result of cls(response) + :rtype: ~azure.mgmt.monitor.v2014_04_01.models.AutoscaleSettingResource :raises ~azure.core.exceptions.HttpResponseError: """ @@ -540,28 +610,27 @@ def update( def update( self, resource_group_name: str, - rule_name: str, - alert_rules_resource: IO, + autoscale_setting_name: str, + autoscale_setting_resource: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.AlertRuleResource: - """Updates an existing classic metric AlertRuleResource. To update other fields use the - CreateOrUpdate method. + ) -> _models.AutoscaleSettingResource: + """Updates an existing AutoscaleSettingsResource. To update other fields use the CreateOrUpdate + method. :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :param rule_name: The name of the rule. Required. - :type rule_name: str - :param alert_rules_resource: Parameters supplied to the operation. Required. - :type alert_rules_resource: IO + :param autoscale_setting_name: The autoscale setting name. Required. + :type autoscale_setting_name: str + :param autoscale_setting_resource: Parameters supplied to the operation. Required. + :type autoscale_setting_resource: 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: AlertRuleResource or the result of cls(response) - :rtype: ~azure.mgmt.monitor.v2015_07_01.models.AlertRuleResource + :return: AutoscaleSettingResource or the result of cls(response) + :rtype: ~azure.mgmt.monitor.v2014_04_01.models.AutoscaleSettingResource :raises ~azure.core.exceptions.HttpResponseError: """ @@ -569,30 +638,27 @@ def update( def update( self, resource_group_name: str, - rule_name: str, - alert_rules_resource: Union[_models.AlertRuleResourcePatch, IO], + autoscale_setting_name: str, + autoscale_setting_resource: Union[_models.AutoscaleSettingResourcePatch, IO[bytes]], **kwargs: Any - ) -> _models.AlertRuleResource: - """Updates an existing classic metric AlertRuleResource. To update other fields use the - CreateOrUpdate method. + ) -> _models.AutoscaleSettingResource: + """Updates an existing AutoscaleSettingsResource. To update other fields use the CreateOrUpdate + method. :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :param rule_name: The name of the rule. Required. - :type rule_name: str - :param alert_rules_resource: Parameters supplied to the operation. Is either a - AlertRuleResourcePatch type or a IO type. Required. - :type alert_rules_resource: ~azure.mgmt.monitor.v2015_07_01.models.AlertRuleResourcePatch 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: AlertRuleResource or the result of cls(response) - :rtype: ~azure.mgmt.monitor.v2015_07_01.models.AlertRuleResource + :param autoscale_setting_name: The autoscale setting name. Required. + :type autoscale_setting_name: str + :param autoscale_setting_resource: Parameters supplied to the operation. Is either a + AutoscaleSettingResourcePatch type or a IO[bytes] type. Required. + :type autoscale_setting_resource: + ~azure.mgmt.monitor.v2014_04_01.models.AutoscaleSettingResourcePatch or IO[bytes] + :return: AutoscaleSettingResource or the result of cls(response) + :rtype: ~azure.mgmt.monitor.v2014_04_01.models.AutoscaleSettingResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -603,79 +669,67 @@ def update( _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", "2014-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2014-04-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.AlertRuleResource] = kwargs.pop("cls", None) + cls: ClsType[_models.AutoscaleSettingResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(alert_rules_resource, (IO, bytes)): - _content = alert_rules_resource + if isinstance(autoscale_setting_resource, (IOBase, bytes)): + _content = autoscale_setting_resource else: - _json = self._serialize.body(alert_rules_resource, "AlertRuleResourcePatch") + _json = self._serialize.body(autoscale_setting_resource, "AutoscaleSettingResourcePatch") - request = build_update_request( + _request = build_update_request( resource_group_name=resource_group_name, - rule_name=rule_name, + autoscale_setting_name=autoscale_setting_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) + _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 + _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) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if response.status_code == 200: - deserialized = self._deserialize("AlertRuleResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("AlertRuleResource", pipeline_response) + deserialized = self._deserialize("AutoscaleSettingResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/alertrules/{ruleName}" - } - @distributed_trace - def list_by_resource_group(self, resource_group_name: str, **kwargs: Any) -> Iterable["_models.AlertRuleResource"]: - """List the classic metric alert rules within a resource group. + def list_by_subscription(self, **kwargs: Any) -> Iterable["_models.AutoscaleSettingResource"]: + """Lists the autoscale settings for a subscription. - :param resource_group_name: The name of the resource group. The name is case insensitive. - Required. - :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either AlertRuleResource or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.monitor.v2015_07_01.models.AlertRuleResource] + :return: An iterator like instance of either AutoscaleSettingResource or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.monitor.v2014_04_01.models.AutoscaleSettingResource] :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", "2014-04-01")) - cls: ClsType[_models.AlertRuleResourceCollection] = kwargs.pop("cls", None) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2014-04-01")) + cls: ClsType[_models.AutoscaleSettingResourceCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -686,109 +740,44 @@ 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( - resource_group_name=resource_group_name, + _request = build_list_by_subscription_request( 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) + _request.url = self._client.format_url(_request.url) else: - request = HttpRequest("GET", next_link) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request - - def extract_data(pipeline_response): - deserialized = self._deserialize("AlertRuleResourceCollection", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return 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) - - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/alertrules" - } - - @distributed_trace - def list_by_subscription(self, **kwargs: Any) -> Iterable["_models.AlertRuleResource"]: - """List the classic metric alert rules within a subscription. - - :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either AlertRuleResource or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.monitor.v2015_07_01.models.AlertRuleResource] - :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", "2014-04-01")) - cls: ClsType[_models.AlertRuleResourceCollection] = kwargs.pop("cls", None) - - error_map = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - request = build_list_by_subscription_request( - subscription_id=self._config.subscription_id, - api_version=api_version, - template_url=self.list_by_subscription.metadata["url"], - headers=_headers, - params=_params, + # 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() + } ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - - else: - request = HttpRequest("GET", next_link) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _next_request_params["api-version"] = self._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("AlertRuleResourceCollection", pipeline_response) + deserialized = self._deserialize("AutoscaleSettingResourceCollection", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) + 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) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -800,5 +789,3 @@ def get_next(next_link=None): return pipeline_response return ItemPaged(get_next, extract_data) - - list_by_subscription.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/alertrules"} diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2014_04_01/operations/_patch.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2014_04_01/operations/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2014_04_01/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2014_04_01/py.typed b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2014_04_01/py.typed new file mode 100644 index 000000000000..e5aff4f83af8 --- /dev/null +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2014_04_01/py.typed @@ -0,0 +1 @@ +# Marker file for PEP 561. \ No newline at end of file diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/__init__.py index 2c7733bfd566..42cc62301757 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/__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 ._monitor_management_client import MonitorManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._monitor_management_client import MonitorManagementClient # type: ignore from ._version import VERSION __version__ = VERSION try: from ._patch import __all__ as _patch_all - from ._patch import * # 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__ = [ "MonitorManagementClient", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/_configuration.py index 84225ab1970a..a6fbc08b4534 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/_configuration.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/_configuration.py @@ -8,18 +8,16 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy from ._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MonitorManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class MonitorManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for MonitorManagementClient. Note that all parameters used to create this instance are saved as instance @@ -29,10 +27,14 @@ class MonitorManagementClientConfiguration(Configuration): # pylint: disable=to :type credential: ~azure.core.credentials.TokenCredential :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str + :keyword api_version: Api Version. Default value is "2015-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(MonitorManagementClientConfiguration, self).__init__(**kwargs) + api_version: str = kwargs.pop("api_version", "2015-04-01") + if credential is None: raise ValueError("Parameter 'credential' must not be None.") if subscription_id is None: @@ -40,8 +42,10 @@ def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs self.credential = credential self.subscription_id = subscription_id + self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-monitor/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -50,9 +54,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.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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/_metadata.json b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/_metadata.json index 977b6fa08840..a0e38f56b72d 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/_metadata.json +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/_metadata.json @@ -1,6 +1,6 @@ { "chosen_version": "2015-04-01", - "total_api_version_list": ["2014-04-01", "2015-04-01"], + "total_api_version_list": ["2015-04-01"], "client": { "name": "MonitorManagementClient", "filename": "_monitor_management_client", @@ -8,10 +8,10 @@ "host_value": "\"https://management.azure.com\"", "parameterized_host_template": null, "azure_arm": true, - "has_lro_operations": false, + "has_public_lro_operations": false, "client_side_validation": false, - "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"sdkcore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMAutoResourceProviderRegistrationPolicy\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}, \"stdlib\": {\"typing_extensions\": [\"Self\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"sdkcore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"AsyncARMAutoResourceProviderRegistrationPolicy\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}, \"stdlib\": {\"typing_extensions\": [\"Self\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "global_parameters": { "sync": { @@ -101,15 +101,14 @@ "credential_scopes": ["https://management.azure.com/.default"], "credential_call_sync": "ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", "credential_call_async": "AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", - "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "sync_imports": "{\"regular\": {\"sdkcore\": {\"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"regular\": {\"sdkcore\": {\"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "operation_groups": { "activity_logs": "ActivityLogsOperations", "autoscale_settings": "AutoscaleSettingsOperations", "event_categories": "EventCategoriesOperations", "operations": "Operations", - "tenant_activity_logs": "TenantActivityLogsOperations", - "alert_rules": "AlertRulesOperations" + "tenant_activity_logs": "TenantActivityLogsOperations" } } diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/_monitor_management_client.py index 1c618b18af39..76e8be88a20e 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/_monitor_management_client.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/_monitor_management_client.py @@ -8,16 +8,18 @@ from copy import deepcopy from typing import Any, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient +from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy from . import models as _models from .._serialization import Deserializer, Serializer from ._configuration import MonitorManagementClientConfiguration from .operations import ( ActivityLogsOperations, - AlertRulesOperations, AutoscaleSettingsOperations, EventCategoriesOperations, Operations, @@ -25,11 +27,10 @@ ) if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MonitorManagementClient: # pylint: disable=client-accepts-api-version-keyword +class MonitorManagementClient: """Monitor Management Client. :ivar activity_logs: ActivityLogsOperations operations @@ -44,14 +45,15 @@ class MonitorManagementClient: # pylint: disable=client-accepts-api-version-key :ivar tenant_activity_logs: TenantActivityLogsOperations operations :vartype tenant_activity_logs: azure.mgmt.monitor.v2015_04_01.operations.TenantActivityLogsOperations - :ivar alert_rules: AlertRulesOperations operations - :vartype alert_rules: azure.mgmt.monitor.v2015_04_01.operations.AlertRulesOperations :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str :param base_url: Service URL. Default value is "https://management.azure.com". :type base_url: str + :keyword api_version: Api Version. Default value is "2015-04-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str """ def __init__( @@ -64,26 +66,45 @@ def __init__( self._config = MonitorManagementClientConfiguration( credential=credential, subscription_id=subscription_id, **kwargs ) - self._client: ARMPipelineClient = ARMPipelineClient(base_url=base_url, config=self._config, **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), + 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=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.activity_logs = ActivityLogsOperations(self._client, self._config, self._serialize, self._deserialize) + self.activity_logs = ActivityLogsOperations( + self._client, self._config, self._serialize, self._deserialize, "2015-04-01" + ) self.autoscale_settings = AutoscaleSettingsOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2015-04-01" ) self.event_categories = EventCategoriesOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2015-04-01" ) - self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) + self.operations = Operations(self._client, self._config, self._serialize, self._deserialize, "2015-04-01") self.tenant_activity_logs = TenantActivityLogsOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2015-04-01" ) - self.alert_rules = AlertRulesOperations(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 @@ -103,12 +124,12 @@ 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) -> None: self._client.close() - def __enter__(self) -> "MonitorManagementClient": + def __enter__(self) -> Self: self._client.__enter__() return self diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/_vendor.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/_vendor.py deleted file mode 100644 index bd0df84f5319..000000000000 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/_vendor.py +++ /dev/null @@ -1,30 +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 typing import List, cast - -from azure.core.pipeline.transport import HttpRequest - - -def _convert_request(request, files=None): - data = request.content if not files else None - request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) - if files: - request.set_formdata_body(files) - return request - - -def _format_url_section(template, **kwargs): - components = template.split("/") - while components: - try: - return template.format(**kwargs) - except KeyError as key: - # Need the cast, as for some reasons "split" is typed as list[str | Any] - formatted_components = cast(List[str], template.split("/")) - components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] - template = "/".join(components) diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/_version.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/_version.py index 394ee7c0c03c..e5754a47ce68 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/_version.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "6.0.2" +VERSION = "1.0.0b1" diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/aio/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/aio/__init__.py index 2c151bb41c19..3df30ff42149 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/aio/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/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 ._monitor_management_client import MonitorManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._monitor_management_client import MonitorManagementClient # type: ignore try: from ._patch import __all__ as _patch_all - from ._patch import * # 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__ = [ "MonitorManagementClient", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/aio/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/aio/_configuration.py index ff77a05cbd87..2cfa2fa80ffe 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/aio/_configuration.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/aio/_configuration.py @@ -8,18 +8,16 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy from .._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MonitorManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class MonitorManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for MonitorManagementClient. Note that all parameters used to create this instance are saved as instance @@ -29,10 +27,14 @@ class MonitorManagementClientConfiguration(Configuration): # pylint: disable=to :type credential: ~azure.core.credentials_async.AsyncTokenCredential :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str + :keyword api_version: Api Version. Default value is "2015-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(MonitorManagementClientConfiguration, self).__init__(**kwargs) + api_version: str = kwargs.pop("api_version", "2015-04-01") + if credential is None: raise ValueError("Parameter 'credential' must not be None.") if subscription_id is None: @@ -40,8 +42,10 @@ def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **k self.credential = credential self.subscription_id = subscription_id + self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-monitor/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -50,9 +54,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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/aio/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/aio/_monitor_management_client.py index 5640ee566505..d8e417d1effe 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/aio/_monitor_management_client.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/aio/_monitor_management_client.py @@ -8,16 +8,18 @@ from copy import deepcopy from typing import Any, Awaitable, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient +from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy from .. import models as _models from ..._serialization import Deserializer, Serializer from ._configuration import MonitorManagementClientConfiguration from .operations import ( ActivityLogsOperations, - AlertRulesOperations, AutoscaleSettingsOperations, EventCategoriesOperations, Operations, @@ -25,11 +27,10 @@ ) if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MonitorManagementClient: # pylint: disable=client-accepts-api-version-keyword +class MonitorManagementClient: """Monitor Management Client. :ivar activity_logs: ActivityLogsOperations operations @@ -45,14 +46,15 @@ class MonitorManagementClient: # pylint: disable=client-accepts-api-version-key :ivar tenant_activity_logs: TenantActivityLogsOperations operations :vartype tenant_activity_logs: azure.mgmt.monitor.v2015_04_01.aio.operations.TenantActivityLogsOperations - :ivar alert_rules: AlertRulesOperations operations - :vartype alert_rules: azure.mgmt.monitor.v2015_04_01.aio.operations.AlertRulesOperations :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str :param base_url: Service URL. Default value is "https://management.azure.com". :type base_url: str + :keyword api_version: Api Version. Default value is "2015-04-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str """ def __init__( @@ -65,26 +67,47 @@ def __init__( self._config = MonitorManagementClientConfiguration( credential=credential, subscription_id=subscription_id, **kwargs ) - self._client: AsyncARMPipelineClient = AsyncARMPipelineClient(base_url=base_url, config=self._config, **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=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.activity_logs = ActivityLogsOperations(self._client, self._config, self._serialize, self._deserialize) + self.activity_logs = ActivityLogsOperations( + self._client, self._config, self._serialize, self._deserialize, "2015-04-01" + ) self.autoscale_settings = AutoscaleSettingsOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2015-04-01" ) self.event_categories = EventCategoriesOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2015-04-01" ) - self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) + self.operations = Operations(self._client, self._config, self._serialize, self._deserialize, "2015-04-01") self.tenant_activity_logs = TenantActivityLogsOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2015-04-01" ) - self.alert_rules = AlertRulesOperations(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 @@ -104,12 +127,12 @@ 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) -> "MonitorManagementClient": + async def __aenter__(self) -> Self: await self._client.__aenter__() return self diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/aio/operations/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/aio/operations/__init__.py index c3fc4cfffbbe..53c594e43fbc 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/aio/operations/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/aio/operations/__init__.py @@ -5,16 +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 ._activity_logs_operations import ActivityLogsOperations -from ._autoscale_settings_operations import AutoscaleSettingsOperations -from ._event_categories_operations import EventCategoriesOperations -from ._operations import Operations -from ._tenant_activity_logs_operations import TenantActivityLogsOperations -from ._alert_rules_operations import AlertRulesOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._activity_logs_operations import ActivityLogsOperations # type: ignore +from ._autoscale_settings_operations import AutoscaleSettingsOperations # type: ignore +from ._event_categories_operations import EventCategoriesOperations # type: ignore +from ._operations import Operations # type: ignore +from ._tenant_activity_logs_operations import TenantActivityLogsOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ @@ -23,7 +28,6 @@ "EventCategoriesOperations", "Operations", "TenantActivityLogsOperations", - "AlertRulesOperations", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/aio/operations/_activity_logs_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/aio/operations/_activity_logs_operations.py index 696f55a089d1..140d4e4acc5e 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/aio/operations/_activity_logs_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/aio/operations/_activity_logs_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,7 +5,9 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( @@ -18,16 +19,18 @@ 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 ...operations._activity_logs_operations import build_list_request +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -50,6 +53,7 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list(self, filter: str, select: Optional[str] = None, **kwargs: Any) -> AsyncIterable["_models.EventData"]: @@ -58,28 +62,27 @@ def list(self, filter: str, select: Optional[str] = None, **kwargs: Any) -> Asyn :param filter: Reduces the set of data collected.:code:`
`This argument is required and it also requires at least the start date/time.:code:`
`The **$filter** argument is very restricted and allows only the following patterns.:code:`
`- *List events for a resource - group*\ : $filter=eventTimestamp ge '2014-07-16T04:36:37.6407898Z' and eventTimestamp le + group*\\ : $filter=eventTimestamp ge '2014-07-16T04:36:37.6407898Z' and eventTimestamp le '2014-07-20T04:36:37.6407898Z' and resourceGroupName eq 'resourceGroupName'.:code:`
`- *List - events for resource*\ : $filter=eventTimestamp ge '2014-07-16T04:36:37.6407898Z' and + events for resource*\\ : $filter=eventTimestamp ge '2014-07-16T04:36:37.6407898Z' and eventTimestamp le '2014-07-20T04:36:37.6407898Z' and resourceUri eq 'resourceURI'.:code:`
`- - *List events for a subscription in a time range*\ : $filter=eventTimestamp ge + *List events for a subscription in a time range*\\ : $filter=eventTimestamp ge '2014-07-16T04:36:37.6407898Z' and eventTimestamp le - '2014-07-20T04:36:37.6407898Z'.:code:`
`- *List events for a resource provider*\ : + '2014-07-20T04:36:37.6407898Z'.:code:`
`- *List events for a resource provider*\\ : $filter=eventTimestamp ge '2014-07-16T04:36:37.6407898Z' and eventTimestamp le '2014-07-20T04:36:37.6407898Z' and resourceProvider eq 'resourceProviderName'.:code:`
`- - *List events for a correlation Id*\ : $filter=eventTimestamp ge '2014-07-16T04:36:37.6407898Z' + *List events for a correlation Id*\\ : $filter=eventTimestamp ge '2014-07-16T04:36:37.6407898Z' and eventTimestamp le '2014-07-20T04:36:37.6407898Z' and correlationId eq - 'correlationID'.:code:`
`:code:`
`\ **NOTE**\ : No other syntax is allowed. Required. + 'correlationID'.:code:`
`:code:`
`\\ **NOTE**\\ : No other syntax is allowed. Required. :type filter: str :param select: Used to fetch events with only the given properties.:code:`
`The **$select** argument is a comma separated list of property names to be returned. Possible values are: - *authorization*\ , *claims*\ , *correlationId*\ , *description*\ , *eventDataId*\ , - *eventName*\ , *eventTimestamp*\ , *httpRequest*\ , *level*\ , *operationId*\ , - *operationName*\ , *properties*\ , *resourceGroupName*\ , *resourceProviderName*\ , - *resourceId*\ , *status*\ , *submissionTimestamp*\ , *subStatus*\ , *subscriptionId*. Default - value is None. + *authorization*\\ , *claims*\\ , *correlationId*\\ , *description*\\ , *eventDataId*\\ , + *eventName*\\ , *eventTimestamp*\\ , *httpRequest*\\ , *level*\\ , *operationId*\\ , + *operationName*\\ , *properties*\\ , *resourceGroupName*\\ , *resourceProviderName*\\ , + *resourceId*\\ , *status*\\ , *submissionTimestamp*\\ , *subStatus*\\ , *subscriptionId*. + Default value is None. :type select: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either EventData or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.monitor.v2015_04_01.models.EventData] @@ -88,10 +91,10 @@ def list(self, filter: str, select: Optional[str] = None, **kwargs: Any) -> Asyn _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2015-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2015-04-01")) cls: ClsType[_models.EventDataCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -102,24 +105,32 @@ def list(self, filter: str, select: Optional[str] = None, **kwargs: Any) -> Asyn def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( subscription_id=self._config.subscription_id, filter=filter, select=select, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: - request = HttpRequest("GET", next_link) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + # 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._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 async def extract_data(pipeline_response): deserialized = self._deserialize("EventDataCollection", pipeline_response) @@ -129,11 +140,11 @@ async def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -145,5 +156,3 @@ async def get_next(next_link=None): return pipeline_response return AsyncItemPaged(get_next, extract_data) - - list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/eventtypes/management/values"} diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/aio/operations/_autoscale_settings_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/aio/operations/_autoscale_settings_operations.py index c16d1484744b..4bcb3c9553ca 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/aio/operations/_autoscale_settings_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/aio/operations/_autoscale_settings_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,7 +5,10 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( @@ -18,15 +20,13 @@ 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 ...operations._autoscale_settings_operations import ( build_create_or_update_request, build_delete_request, @@ -36,6 +36,10 @@ build_update_request, ) +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -58,6 +62,7 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list_by_resource_group( @@ -68,7 +73,6 @@ def list_by_resource_group( :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either AutoscaleSettingResource or the result of cls(response) :rtype: @@ -78,10 +82,10 @@ def list_by_resource_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2015-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2015-04-01")) cls: ClsType[_models.AutoscaleSettingResourceCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -92,23 +96,31 @@ 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_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: - request = HttpRequest("GET", next_link) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + # 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._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 async def extract_data(pipeline_response): deserialized = self._deserialize("AutoscaleSettingResourceCollection", pipeline_response) @@ -118,11 +130,11 @@ async def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -135,10 +147,6 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/autoscalesettings" - } - @overload async def create_or_update( self, @@ -161,7 +169,6 @@ async def create_or_update( :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: AutoscaleSettingResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2015_04_01.models.AutoscaleSettingResource :raises ~azure.core.exceptions.HttpResponseError: @@ -172,7 +179,7 @@ async def create_or_update( self, resource_group_name: str, autoscale_setting_name: str, - parameters: IO, + parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -185,11 +192,10 @@ async def create_or_update( :param autoscale_setting_name: The autoscale setting name. Required. :type autoscale_setting_name: str :param parameters: Parameters supplied to the operation. Required. - :type parameters: IO + :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: AutoscaleSettingResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2015_04_01.models.AutoscaleSettingResource :raises ~azure.core.exceptions.HttpResponseError: @@ -200,7 +206,7 @@ async def create_or_update( self, resource_group_name: str, autoscale_setting_name: str, - parameters: Union[_models.AutoscaleSettingResource, IO], + parameters: Union[_models.AutoscaleSettingResource, IO[bytes]], **kwargs: Any ) -> _models.AutoscaleSettingResource: """Creates or updates an autoscale setting. @@ -211,17 +217,13 @@ async def create_or_update( :param autoscale_setting_name: The autoscale setting name. Required. :type autoscale_setting_name: str :param parameters: Parameters supplied to the operation. Is either a AutoscaleSettingResource - type or a IO type. Required. - :type parameters: ~azure.mgmt.monitor.v2015_04_01.models.AutoscaleSettingResource 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 + type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.monitor.v2015_04_01.models.AutoscaleSettingResource or IO[bytes] :return: AutoscaleSettingResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2015_04_01.models.AutoscaleSettingResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -232,19 +234,19 @@ async def create_or_update( _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", "2015-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2015-04-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.AutoscaleSettingResource] = 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, "AutoscaleSettingResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, autoscale_setting_name=autoscale_setting_name, subscription_id=self._config.subscription_id, @@ -252,16 +254,14 @@ async def create_or_update( 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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -271,25 +271,15 @@ async def create_or_update( 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("AutoscaleSettingResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("AutoscaleSettingResource", pipeline_response) + deserialized = self._deserialize("AutoscaleSettingResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/autoscalesettings/{autoscaleSettingName}" - } - @distributed_trace_async - async def delete( # pylint: disable=inconsistent-return-statements - self, resource_group_name: str, autoscale_setting_name: str, **kwargs: Any - ) -> None: + async def delete(self, resource_group_name: str, autoscale_setting_name: str, **kwargs: Any) -> None: """Deletes and autoscale setting. :param resource_group_name: The name of the resource group. The name is case insensitive. @@ -297,12 +287,11 @@ async def delete( # pylint: disable=inconsistent-return-statements :type resource_group_name: str :param autoscale_setting_name: The autoscale setting name. Required. :type autoscale_setting_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, @@ -313,24 +302,22 @@ async def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2015-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2015-04-01")) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, autoscale_setting_name=autoscale_setting_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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -341,11 +328,7 @@ async def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/autoscalesettings/{autoscaleSettingName}" - } + return cls(pipeline_response, None, {}) # type: ignore @distributed_trace_async async def get( @@ -358,12 +341,11 @@ async def get( :type resource_group_name: str :param autoscale_setting_name: The autoscale setting name. Required. :type autoscale_setting_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: AutoscaleSettingResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2015_04_01.models.AutoscaleSettingResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -374,24 +356,22 @@ async def get( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2015-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2015-04-01")) cls: ClsType[_models.AutoscaleSettingResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, autoscale_setting_name=autoscale_setting_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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -401,16 +381,12 @@ async def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("AutoscaleSettingResource", pipeline_response) + deserialized = self._deserialize("AutoscaleSettingResource", 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.Insights/autoscalesettings/{autoscaleSettingName}" - } + return deserialized # type: ignore @overload async def update( @@ -436,7 +412,6 @@ async def update( :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: AutoscaleSettingResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2015_04_01.models.AutoscaleSettingResource :raises ~azure.core.exceptions.HttpResponseError: @@ -447,7 +422,7 @@ async def update( self, resource_group_name: str, autoscale_setting_name: str, - autoscale_setting_resource: IO, + autoscale_setting_resource: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -461,11 +436,10 @@ async def update( :param autoscale_setting_name: The autoscale setting name. Required. :type autoscale_setting_name: str :param autoscale_setting_resource: Parameters supplied to the operation. Required. - :type autoscale_setting_resource: IO + :type autoscale_setting_resource: 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: AutoscaleSettingResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2015_04_01.models.AutoscaleSettingResource :raises ~azure.core.exceptions.HttpResponseError: @@ -476,7 +450,7 @@ async def update( self, resource_group_name: str, autoscale_setting_name: str, - autoscale_setting_resource: Union[_models.AutoscaleSettingResourcePatch, IO], + autoscale_setting_resource: Union[_models.AutoscaleSettingResourcePatch, IO[bytes]], **kwargs: Any ) -> _models.AutoscaleSettingResource: """Updates an existing AutoscaleSettingsResource. To update other fields use the CreateOrUpdate @@ -488,18 +462,14 @@ async def update( :param autoscale_setting_name: The autoscale setting name. Required. :type autoscale_setting_name: str :param autoscale_setting_resource: Parameters supplied to the operation. Is either a - AutoscaleSettingResourcePatch type or a IO type. Required. + AutoscaleSettingResourcePatch type or a IO[bytes] type. Required. :type autoscale_setting_resource: - ~azure.mgmt.monitor.v2015_04_01.models.AutoscaleSettingResourcePatch 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 + ~azure.mgmt.monitor.v2015_04_01.models.AutoscaleSettingResourcePatch or IO[bytes] :return: AutoscaleSettingResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2015_04_01.models.AutoscaleSettingResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -510,19 +480,19 @@ async def update( _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", "2015-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2015-04-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.AutoscaleSettingResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(autoscale_setting_resource, (IO, bytes)): + if isinstance(autoscale_setting_resource, (IOBase, bytes)): _content = autoscale_setting_resource else: _json = self._serialize.body(autoscale_setting_resource, "AutoscaleSettingResourcePatch") - request = build_update_request( + _request = build_update_request( resource_group_name=resource_group_name, autoscale_setting_name=autoscale_setting_name, subscription_id=self._config.subscription_id, @@ -530,16 +500,14 @@ async def update( 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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -549,22 +517,17 @@ async def update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("AutoscaleSettingResource", pipeline_response) + deserialized = self._deserialize("AutoscaleSettingResource", 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.Insights/autoscalesettings/{autoscaleSettingName}" - } + return deserialized # type: ignore @distributed_trace def list_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.AutoscaleSettingResource"]: """Lists the autoscale settings for a subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either AutoscaleSettingResource or the result of cls(response) :rtype: @@ -574,10 +537,10 @@ def list_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.Autoscal _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2015-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2015-04-01")) cls: ClsType[_models.AutoscaleSettingResourceCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -588,22 +551,30 @@ def list_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.Autoscal def prepare_request(next_link=None): if not next_link: - request = build_list_by_subscription_request( + _request = build_list_by_subscription_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_subscription.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: - request = HttpRequest("GET", next_link) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + # 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._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 async def extract_data(pipeline_response): deserialized = self._deserialize("AutoscaleSettingResourceCollection", pipeline_response) @@ -613,11 +584,11 @@ async def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -629,7 +600,3 @@ async def get_next(next_link=None): return pipeline_response return AsyncItemPaged(get_next, extract_data) - - list_by_subscription.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/autoscalesettings" - } diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/aio/operations/_event_categories_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/aio/operations/_event_categories_operations.py index a27a3ce7c584..5b0c3cf88f1b 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/aio/operations/_event_categories_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/aio/operations/_event_categories_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,7 +5,9 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( @@ -18,16 +19,18 @@ 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 ...operations._event_categories_operations import build_list_request +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -50,6 +53,7 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list(self, **kwargs: Any) -> AsyncIterable["_models.LocalizableString"]: @@ -57,7 +61,6 @@ def list(self, **kwargs: Any) -> AsyncIterable["_models.LocalizableString"]: Service.:code:`
`The current list includes the following: Administrative, Security, ServiceHealth, Alert, Recommendation, Policy. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either LocalizableString or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.monitor.v2015_04_01.models.LocalizableString] @@ -66,10 +69,10 @@ def list(self, **kwargs: Any) -> AsyncIterable["_models.LocalizableString"]: _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2015-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2015-04-01")) cls: ClsType[_models.EventCategoryCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -80,21 +83,29 @@ def list(self, **kwargs: Any) -> AsyncIterable["_models.LocalizableString"]: 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) + _request.url = self._client.format_url(_request.url) else: - request = HttpRequest("GET", next_link) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + # 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._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 async def extract_data(pipeline_response): deserialized = self._deserialize("EventCategoryCollection", pipeline_response) @@ -104,11 +115,11 @@ async def extract_data(pipeline_response): return None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -120,5 +131,3 @@ async def get_next(next_link=None): return pipeline_response return AsyncItemPaged(get_next, extract_data) - - list.metadata = {"url": "/providers/Microsoft.Insights/eventcategories"} diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/aio/operations/_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/aio/operations/_operations.py index c3ab3e4bac0d..8b4c33a3370f 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/aio/operations/_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/aio/operations/_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,7 @@ # 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 ( @@ -17,16 +17,18 @@ 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_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._operations import build_list_request +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -49,17 +51,17 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace_async async def list(self, **kwargs: Any) -> _models.OperationListResult: """Lists all of the available operations from Microsoft.Insights provider. - :keyword callable cls: A custom type or function that will be passed the direct response :return: OperationListResult or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2015_04_01.models.OperationListResult :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -70,21 +72,19 @@ async def list(self, **kwargs: Any) -> _models.OperationListResult: _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2015-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2015-04-01")) cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) - 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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -93,11 +93,9 @@ async def list(self, **kwargs: Any) -> _models.OperationListResult: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize("OperationListResult", pipeline_response) + deserialized = self._deserialize("OperationListResult", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - list.metadata = {"url": "/providers/Microsoft.Insights/operations"} + return deserialized # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/aio/operations/_tenant_activity_logs_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/aio/operations/_tenant_activity_logs_operations.py index 0a4609b6cb5e..ef878462771c 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/aio/operations/_tenant_activity_logs_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/aio/operations/_tenant_activity_logs_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,7 +5,9 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( @@ -18,16 +19,18 @@ 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 ...operations._tenant_activity_logs_operations import build_list_request +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -50,6 +53,7 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list( @@ -75,18 +79,17 @@ def list( ':code:``'.:code:`
`- List events for a correlation Id: api-version=2014-04-01&$filter=eventTimestamp ge '2014-07-16T04:36:37.6407898Z' and eventTimestamp le '2014-07-20T04:36:37.6407898Z' and eventChannels eq 'Admin, Operation' and - correlationId eq ':code:``'.:code:`
`\ **NOTE**\ : No other syntax is + correlationId eq ':code:``'.:code:`
`\\ **NOTE**\\ : No other syntax is allowed. Default value is None. :type filter: str :param select: Used to fetch events with only the given properties.:code:`
`The **$select** argument is a comma separated list of property names to be returned. Possible values are: - *authorization*\ , *claims*\ , *correlationId*\ , *description*\ , *eventDataId*\ , - *eventName*\ , *eventTimestamp*\ , *httpRequest*\ , *level*\ , *operationId*\ , - *operationName*\ , *properties*\ , *resourceGroupName*\ , *resourceProviderName*\ , - *resourceId*\ , *status*\ , *submissionTimestamp*\ , *subStatus*\ , *subscriptionId*. Default - value is None. + *authorization*\\ , *claims*\\ , *correlationId*\\ , *description*\\ , *eventDataId*\\ , + *eventName*\\ , *eventTimestamp*\\ , *httpRequest*\\ , *level*\\ , *operationId*\\ , + *operationName*\\ , *properties*\\ , *resourceGroupName*\\ , *resourceProviderName*\\ , + *resourceId*\\ , *status*\\ , *submissionTimestamp*\\ , *subStatus*\\ , *subscriptionId*. + Default value is None. :type select: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either EventData or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.monitor.v2015_04_01.models.EventData] @@ -95,10 +98,10 @@ def list( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2015-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2015-04-01")) cls: ClsType[_models.EventDataCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -109,23 +112,31 @@ def list( def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( filter=filter, select=select, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: - request = HttpRequest("GET", next_link) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + # 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._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 async def extract_data(pipeline_response): deserialized = self._deserialize("EventDataCollection", pipeline_response) @@ -135,11 +146,11 @@ async def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -151,5 +162,3 @@ async def get_next(next_link=None): return pipeline_response return AsyncItemPaged(get_next, extract_data) - - list.metadata = {"url": "/providers/Microsoft.Insights/eventtypes/management/values"} diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/models/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/models/__init__.py index 3b949b4fe53a..0c5440cf6235 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/models/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/models/__init__.py @@ -5,67 +5,58 @@ # 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 AlertRuleResource -from ._models_py3 import AlertRuleResourceCollection -from ._models_py3 import AlertRuleResourcePatch -from ._models_py3 import AutoscaleNotification -from ._models_py3 import AutoscaleProfile -from ._models_py3 import AutoscaleSettingResource -from ._models_py3 import AutoscaleSettingResourceCollection -from ._models_py3 import AutoscaleSettingResourcePatch -from ._models_py3 import EmailNotification -from ._models_py3 import ErrorResponse -from ._models_py3 import EventCategoryCollection -from ._models_py3 import EventData -from ._models_py3 import EventDataCollection -from ._models_py3 import HttpRequestInfo -from ._models_py3 import LocalizableString -from ._models_py3 import LocationThresholdRuleCondition -from ._models_py3 import ManagementEventAggregationCondition -from ._models_py3 import ManagementEventRuleCondition -from ._models_py3 import MetricTrigger -from ._models_py3 import Operation -from ._models_py3 import OperationDisplay -from ._models_py3 import OperationListResult -from ._models_py3 import Recurrence -from ._models_py3 import RecurrentSchedule -from ._models_py3 import Resource -from ._models_py3 import RuleAction -from ._models_py3 import RuleCondition -from ._models_py3 import RuleDataSource -from ._models_py3 import RuleEmailAction -from ._models_py3 import RuleManagementEventClaimsDataSource -from ._models_py3 import RuleManagementEventDataSource -from ._models_py3 import RuleMetricDataSource -from ._models_py3 import RuleWebhookAction -from ._models_py3 import ScaleAction -from ._models_py3 import ScaleCapacity -from ._models_py3 import ScaleRule -from ._models_py3 import ScaleRuleMetricDimension -from ._models_py3 import SenderAuthorization -from ._models_py3 import ThresholdRuleCondition -from ._models_py3 import TimeWindow -from ._models_py3 import WebhookNotification +from typing import TYPE_CHECKING -from ._monitor_management_client_enums import ComparisonOperationType -from ._monitor_management_client_enums import ConditionOperator -from ._monitor_management_client_enums import EventLevel -from ._monitor_management_client_enums import MetricStatisticType -from ._monitor_management_client_enums import RecurrenceFrequency -from ._monitor_management_client_enums import ScaleDirection -from ._monitor_management_client_enums import ScaleRuleMetricDimensionOperationType -from ._monitor_management_client_enums import ScaleType -from ._monitor_management_client_enums import TimeAggregationOperator -from ._monitor_management_client_enums import TimeAggregationType +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models_py3 import ( # type: ignore + AutoscaleNotification, + AutoscaleProfile, + AutoscaleSettingResource, + AutoscaleSettingResourceCollection, + AutoscaleSettingResourcePatch, + EmailNotification, + ErrorResponse, + EventCategoryCollection, + EventData, + EventDataCollection, + HttpRequestInfo, + LocalizableString, + MetricTrigger, + Operation, + OperationDisplay, + OperationListResult, + Recurrence, + RecurrentSchedule, + Resource, + ScaleAction, + ScaleCapacity, + ScaleRule, + ScaleRuleMetricDimension, + SenderAuthorization, + TimeWindow, + WebhookNotification, +) + +from ._monitor_management_client_enums import ( # type: ignore + ComparisonOperationType, + EventLevel, + MetricStatisticType, + RecurrenceFrequency, + ScaleDirection, + ScaleRuleMetricDimensionOperationType, + ScaleType, + TimeAggregationType, +) from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ - "AlertRuleResource", - "AlertRuleResourceCollection", - "AlertRuleResourcePatch", "AutoscaleNotification", "AutoscaleProfile", "AutoscaleSettingResource", @@ -78,9 +69,6 @@ "EventDataCollection", "HttpRequestInfo", "LocalizableString", - "LocationThresholdRuleCondition", - "ManagementEventAggregationCondition", - "ManagementEventRuleCondition", "MetricTrigger", "Operation", "OperationDisplay", @@ -88,32 +76,21 @@ "Recurrence", "RecurrentSchedule", "Resource", - "RuleAction", - "RuleCondition", - "RuleDataSource", - "RuleEmailAction", - "RuleManagementEventClaimsDataSource", - "RuleManagementEventDataSource", - "RuleMetricDataSource", - "RuleWebhookAction", "ScaleAction", "ScaleCapacity", "ScaleRule", "ScaleRuleMetricDimension", "SenderAuthorization", - "ThresholdRuleCondition", "TimeWindow", "WebhookNotification", "ComparisonOperationType", - "ConditionOperator", "EventLevel", "MetricStatisticType", "RecurrenceFrequency", "ScaleDirection", "ScaleRuleMetricDimensionOperationType", "ScaleType", - "TimeAggregationOperator", "TimeAggregationType", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/models/_models_py3.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/models/_models_py3.py index 82dc0158f211..b6e993cf7339 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/models/_models_py3.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/models/_models_py3.py @@ -1,5 +1,5 @@ -# coding=utf-8 # 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. @@ -13,286 +13,15 @@ from ... import _serialization if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from .. import models as _models -class Resource(_serialization.Model): - """An azure resource object. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to Azure. - - :ivar id: Azure resource Id. - :vartype id: str - :ivar name: Azure resource name. - :vartype name: str - :ivar type: Azure resource type. - :vartype type: str - :ivar location: Resource location. Required. - :vartype location: str - :ivar tags: Resource tags. - :vartype tags: dict[str, str] - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "location": {"required": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "location": {"key": "location", "type": "str"}, - "tags": {"key": "tags", "type": "{str}"}, - } - - def __init__(self, *, location: str, tags: Optional[Dict[str, str]] = None, **kwargs: Any) -> None: - """ - :keyword location: Resource location. Required. - :paramtype location: str - :keyword tags: Resource tags. - :paramtype tags: dict[str, str] - """ - super().__init__(**kwargs) - self.id = None - self.name = None - self.type = None - self.location = location - self.tags = tags - - -class AlertRuleResource(Resource): # pylint: disable=too-many-instance-attributes - """The alert rule resource. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to Azure. - - :ivar id: Azure resource Id. - :vartype id: str - :ivar name: Azure resource name. - :vartype name: str - :ivar type: Azure resource type. - :vartype type: str - :ivar location: Resource location. Required. - :vartype location: str - :ivar tags: Resource tags. - :vartype tags: dict[str, str] - :ivar name_properties_name: the name of the alert rule. Required. - :vartype name_properties_name: str - :ivar description: the description of the alert rule that will be included in the alert email. - :vartype description: str - :ivar provisioning_state: the provisioning state. - :vartype provisioning_state: str - :ivar is_enabled: the flag that indicates whether the alert rule is enabled. Required. - :vartype is_enabled: bool - :ivar condition: the condition that results in the alert rule being activated. Required. - :vartype condition: ~azure.mgmt.monitor.v2015_04_01.models.RuleCondition - :ivar action: action that is performed when the alert rule becomes active, and when an alert - condition is resolved. - :vartype action: ~azure.mgmt.monitor.v2015_04_01.models.RuleAction - :ivar actions: the array of actions that are performed when the alert rule becomes active, and - when an alert condition is resolved. - :vartype actions: list[~azure.mgmt.monitor.v2015_04_01.models.RuleAction] - :ivar last_updated_time: Last time the rule was updated in ISO8601 format. - :vartype last_updated_time: ~datetime.datetime - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "location": {"required": True}, - "name_properties_name": {"required": True}, - "is_enabled": {"required": True}, - "condition": {"required": True}, - "last_updated_time": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "location": {"key": "location", "type": "str"}, - "tags": {"key": "tags", "type": "{str}"}, - "name_properties_name": {"key": "properties.name", "type": "str"}, - "description": {"key": "properties.description", "type": "str"}, - "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, - "is_enabled": {"key": "properties.isEnabled", "type": "bool"}, - "condition": {"key": "properties.condition", "type": "RuleCondition"}, - "action": {"key": "properties.action", "type": "RuleAction"}, - "actions": {"key": "properties.actions", "type": "[RuleAction]"}, - "last_updated_time": {"key": "properties.lastUpdatedTime", "type": "iso-8601"}, - } - - def __init__( - self, - *, - location: str, - name_properties_name: str, - is_enabled: bool, - condition: "_models.RuleCondition", - tags: Optional[Dict[str, str]] = None, - description: Optional[str] = None, - provisioning_state: Optional[str] = None, - action: Optional["_models.RuleAction"] = None, - actions: Optional[List["_models.RuleAction"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword location: Resource location. Required. - :paramtype location: str - :keyword tags: Resource tags. - :paramtype tags: dict[str, str] - :keyword name_properties_name: the name of the alert rule. Required. - :paramtype name_properties_name: str - :keyword description: the description of the alert rule that will be included in the alert - email. - :paramtype description: str - :keyword provisioning_state: the provisioning state. - :paramtype provisioning_state: str - :keyword is_enabled: the flag that indicates whether the alert rule is enabled. Required. - :paramtype is_enabled: bool - :keyword condition: the condition that results in the alert rule being activated. Required. - :paramtype condition: ~azure.mgmt.monitor.v2015_04_01.models.RuleCondition - :keyword action: action that is performed when the alert rule becomes active, and when an alert - condition is resolved. - :paramtype action: ~azure.mgmt.monitor.v2015_04_01.models.RuleAction - :keyword actions: the array of actions that are performed when the alert rule becomes active, - and when an alert condition is resolved. - :paramtype actions: list[~azure.mgmt.monitor.v2015_04_01.models.RuleAction] - """ - super().__init__(location=location, tags=tags, **kwargs) - self.name_properties_name = name_properties_name - self.description = description - self.provisioning_state = provisioning_state - self.is_enabled = is_enabled - self.condition = condition - self.action = action - self.actions = actions - self.last_updated_time = None - - -class AlertRuleResourceCollection(_serialization.Model): - """Represents a collection of alert rule resources. - - :ivar value: the values for the alert rule resources. - :vartype value: list[~azure.mgmt.monitor.v2015_04_01.models.AlertRuleResource] - """ - - _attribute_map = { - "value": {"key": "value", "type": "[AlertRuleResource]"}, - } - - def __init__(self, *, value: Optional[List["_models.AlertRuleResource"]] = None, **kwargs: Any) -> None: - """ - :keyword value: the values for the alert rule resources. - :paramtype value: list[~azure.mgmt.monitor.v2015_04_01.models.AlertRuleResource] - """ - super().__init__(**kwargs) - self.value = value - - -class AlertRuleResourcePatch(_serialization.Model): - """The alert rule object for patch operations. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar tags: Resource tags. - :vartype tags: dict[str, str] - :ivar name: the name of the alert rule. - :vartype name: str - :ivar description: the description of the alert rule that will be included in the alert email. - :vartype description: str - :ivar provisioning_state: the provisioning state. - :vartype provisioning_state: str - :ivar is_enabled: the flag that indicates whether the alert rule is enabled. - :vartype is_enabled: bool - :ivar condition: the condition that results in the alert rule being activated. - :vartype condition: ~azure.mgmt.monitor.v2015_04_01.models.RuleCondition - :ivar action: action that is performed when the alert rule becomes active, and when an alert - condition is resolved. - :vartype action: ~azure.mgmt.monitor.v2015_04_01.models.RuleAction - :ivar actions: the array of actions that are performed when the alert rule becomes active, and - when an alert condition is resolved. - :vartype actions: list[~azure.mgmt.monitor.v2015_04_01.models.RuleAction] - :ivar last_updated_time: Last time the rule was updated in ISO8601 format. - :vartype last_updated_time: ~datetime.datetime - """ - - _validation = { - "last_updated_time": {"readonly": True}, - } - - _attribute_map = { - "tags": {"key": "tags", "type": "{str}"}, - "name": {"key": "properties.name", "type": "str"}, - "description": {"key": "properties.description", "type": "str"}, - "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, - "is_enabled": {"key": "properties.isEnabled", "type": "bool"}, - "condition": {"key": "properties.condition", "type": "RuleCondition"}, - "action": {"key": "properties.action", "type": "RuleAction"}, - "actions": {"key": "properties.actions", "type": "[RuleAction]"}, - "last_updated_time": {"key": "properties.lastUpdatedTime", "type": "iso-8601"}, - } - - def __init__( - self, - *, - tags: Optional[Dict[str, str]] = None, - name: Optional[str] = None, - description: Optional[str] = None, - provisioning_state: Optional[str] = None, - is_enabled: Optional[bool] = None, - condition: Optional["_models.RuleCondition"] = None, - action: Optional["_models.RuleAction"] = None, - actions: Optional[List["_models.RuleAction"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword tags: Resource tags. - :paramtype tags: dict[str, str] - :keyword name: the name of the alert rule. - :paramtype name: str - :keyword description: the description of the alert rule that will be included in the alert - email. - :paramtype description: str - :keyword provisioning_state: the provisioning state. - :paramtype provisioning_state: str - :keyword is_enabled: the flag that indicates whether the alert rule is enabled. - :paramtype is_enabled: bool - :keyword condition: the condition that results in the alert rule being activated. - :paramtype condition: ~azure.mgmt.monitor.v2015_04_01.models.RuleCondition - :keyword action: action that is performed when the alert rule becomes active, and when an alert - condition is resolved. - :paramtype action: ~azure.mgmt.monitor.v2015_04_01.models.RuleAction - :keyword actions: the array of actions that are performed when the alert rule becomes active, - and when an alert condition is resolved. - :paramtype actions: list[~azure.mgmt.monitor.v2015_04_01.models.RuleAction] - """ - super().__init__(**kwargs) - self.tags = tags - self.name = name - self.description = description - self.provisioning_state = provisioning_state - self.is_enabled = is_enabled - self.condition = condition - self.action = action - self.actions = actions - self.last_updated_time = None - - class AutoscaleNotification(_serialization.Model): """Autoscale notification. 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 operation: the operation associated with the notification and its value must be "scale". Required. Default value is "Scale". @@ -336,7 +65,7 @@ def __init__( class AutoscaleProfile(_serialization.Model): """Autoscale profile. - 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 name of the profile. Required. :vartype name: str @@ -400,12 +129,61 @@ def __init__( self.recurrence = recurrence -class AutoscaleSettingResource(Resource): # pylint: disable=too-many-instance-attributes +class Resource(_serialization.Model): + """An azure resource object. + + 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 id: Azure resource Id. + :vartype id: str + :ivar name: Azure resource name. + :vartype name: str + :ivar type: Azure resource type. + :vartype type: str + :ivar location: Resource location. Required. + :vartype location: str + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "location": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + } + + def __init__(self, *, location: str, tags: Optional[Dict[str, str]] = None, **kwargs: Any) -> None: + """ + :keyword location: Resource location. Required. + :paramtype location: str + :keyword tags: Resource tags. + :paramtype tags: dict[str, str] + """ + super().__init__(**kwargs) + self.id = None + self.name = None + self.type = None + self.location = location + self.tags = tags + + +class AutoscaleSettingResource(Resource): """The autoscale setting 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: Azure resource Id. :vartype id: str @@ -504,7 +282,7 @@ def __init__( class AutoscaleSettingResourceCollection(_serialization.Model): """Represents a collection of autoscale setting resources. - 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 value: the values for the autoscale setting resources. Required. :vartype value: list[~azure.mgmt.monitor.v2015_04_01.models.AutoscaleSettingResource] @@ -689,7 +467,7 @@ class EventCategoryCollection(_serialization.Model): """A collection of event categories. Currently possible values are: Administrative, Security, ServiceHealth, Alert, Recommendation, Policy. - 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 value: the list that includes the Azure event categories. Required. :vartype value: list[~azure.mgmt.monitor.v2015_04_01.models.LocalizableString] @@ -712,7 +490,7 @@ def __init__(self, *, value: List["_models.LocalizableString"], **kwargs: Any) - self.value = value -class EventData(_serialization.Model): # pylint: disable=too-many-instance-attributes +class EventData(_serialization.Model): """The Azure event log entries are of type EventData. Variables are only populated by the server, and will be ignored when sending a request. @@ -873,7 +651,7 @@ def __init__(self, **kwargs: Any) -> None: # pylint: disable=too-many-locals class EventDataCollection(_serialization.Model): """Represents collection of events. - 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 value: this list that includes the Azure audit logs. Required. :vartype value: list[~azure.mgmt.monitor.v2015_04_01.models.EventData] @@ -951,7 +729,7 @@ def __init__( class LocalizableString(_serialization.Model): """The localizable string class. - 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 value: the invariant value. Required. :vartype value: str @@ -980,213 +758,10 @@ def __init__(self, *, value: str, localized_value: Optional[str] = None, **kwarg self.localized_value = localized_value -class RuleCondition(_serialization.Model): - """The condition that results in the alert rule being activated. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - LocationThresholdRuleCondition, ManagementEventRuleCondition, ThresholdRuleCondition - - All required parameters must be populated in order to send to Azure. - - :ivar odata_type: specifies the type of condition. This can be one of three types: - ManagementEventRuleCondition (occurrences of management events), LocationThresholdRuleCondition - (based on the number of failures of a web test), and ThresholdRuleCondition (based on the - threshold of a metric). Required. - :vartype odata_type: str - :ivar data_source: the resource from which the rule collects its data. For this type dataSource - will always be of type RuleMetricDataSource. - :vartype data_source: ~azure.mgmt.monitor.v2015_04_01.models.RuleDataSource - """ - - _validation = { - "odata_type": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "odata\\.type", "type": "str"}, - "data_source": {"key": "dataSource", "type": "RuleDataSource"}, - } - - _subtype_map = { - "odata_type": { - "Microsoft.Azure.Management.Insights.Models.LocationThresholdRuleCondition": "LocationThresholdRuleCondition", - "Microsoft.Azure.Management.Insights.Models.ManagementEventRuleCondition": "ManagementEventRuleCondition", - "Microsoft.Azure.Management.Insights.Models.ThresholdRuleCondition": "ThresholdRuleCondition", - } - } - - def __init__(self, *, data_source: Optional["_models.RuleDataSource"] = None, **kwargs: Any) -> None: - """ - :keyword data_source: the resource from which the rule collects its data. For this type - dataSource will always be of type RuleMetricDataSource. - :paramtype data_source: ~azure.mgmt.monitor.v2015_04_01.models.RuleDataSource - """ - super().__init__(**kwargs) - self.odata_type: Optional[str] = None - self.data_source = data_source - - -class LocationThresholdRuleCondition(RuleCondition): - """A rule condition based on a certain number of locations failing. - - All required parameters must be populated in order to send to Azure. - - :ivar odata_type: specifies the type of condition. This can be one of three types: - ManagementEventRuleCondition (occurrences of management events), LocationThresholdRuleCondition - (based on the number of failures of a web test), and ThresholdRuleCondition (based on the - threshold of a metric). Required. - :vartype odata_type: str - :ivar data_source: the resource from which the rule collects its data. For this type dataSource - will always be of type RuleMetricDataSource. - :vartype data_source: ~azure.mgmt.monitor.v2015_04_01.models.RuleDataSource - :ivar window_size: the period of time (in ISO 8601 duration format) that is used to monitor - alert activity based on the threshold. If specified then it must be between 5 minutes and 1 - day. - :vartype window_size: ~datetime.timedelta - :ivar failed_location_count: the number of locations that must fail to activate the alert. - Required. - :vartype failed_location_count: int - """ - - _validation = { - "odata_type": {"required": True}, - "failed_location_count": {"required": True, "minimum": 0}, - } - - _attribute_map = { - "odata_type": {"key": "odata\\.type", "type": "str"}, - "data_source": {"key": "dataSource", "type": "RuleDataSource"}, - "window_size": {"key": "windowSize", "type": "duration"}, - "failed_location_count": {"key": "failedLocationCount", "type": "int"}, - } - - def __init__( - self, - *, - failed_location_count: int, - data_source: Optional["_models.RuleDataSource"] = None, - window_size: Optional[datetime.timedelta] = None, - **kwargs: Any - ) -> None: - """ - :keyword data_source: the resource from which the rule collects its data. For this type - dataSource will always be of type RuleMetricDataSource. - :paramtype data_source: ~azure.mgmt.monitor.v2015_04_01.models.RuleDataSource - :keyword window_size: the period of time (in ISO 8601 duration format) that is used to monitor - alert activity based on the threshold. If specified then it must be between 5 minutes and 1 - day. - :paramtype window_size: ~datetime.timedelta - :keyword failed_location_count: the number of locations that must fail to activate the alert. - Required. - :paramtype failed_location_count: int - """ - super().__init__(data_source=data_source, **kwargs) - self.odata_type: str = "Microsoft.Azure.Management.Insights.Models.LocationThresholdRuleCondition" - self.window_size = window_size - self.failed_location_count = failed_location_count - - -class ManagementEventAggregationCondition(_serialization.Model): - """How the data that is collected should be combined over time. - - :ivar operator: the condition operator. Known values are: "GreaterThan", "GreaterThanOrEqual", - "LessThan", and "LessThanOrEqual". - :vartype operator: str or ~azure.mgmt.monitor.v2015_04_01.models.ConditionOperator - :ivar threshold: The threshold value that activates the alert. - :vartype threshold: float - :ivar window_size: the period of time (in ISO 8601 duration format) that is used to monitor - alert activity based on the threshold. If specified then it must be between 5 minutes and 1 - day. - :vartype window_size: ~datetime.timedelta - """ - - _attribute_map = { - "operator": {"key": "operator", "type": "str"}, - "threshold": {"key": "threshold", "type": "float"}, - "window_size": {"key": "windowSize", "type": "duration"}, - } - - def __init__( - self, - *, - operator: Optional[Union[str, "_models.ConditionOperator"]] = None, - threshold: Optional[float] = None, - window_size: Optional[datetime.timedelta] = None, - **kwargs: Any - ) -> None: - """ - :keyword operator: the condition operator. Known values are: "GreaterThan", - "GreaterThanOrEqual", "LessThan", and "LessThanOrEqual". - :paramtype operator: str or ~azure.mgmt.monitor.v2015_04_01.models.ConditionOperator - :keyword threshold: The threshold value that activates the alert. - :paramtype threshold: float - :keyword window_size: the period of time (in ISO 8601 duration format) that is used to monitor - alert activity based on the threshold. If specified then it must be between 5 minutes and 1 - day. - :paramtype window_size: ~datetime.timedelta - """ - super().__init__(**kwargs) - self.operator = operator - self.threshold = threshold - self.window_size = window_size - - -class ManagementEventRuleCondition(RuleCondition): - """A management event rule condition. - - All required parameters must be populated in order to send to Azure. - - :ivar odata_type: specifies the type of condition. This can be one of three types: - ManagementEventRuleCondition (occurrences of management events), LocationThresholdRuleCondition - (based on the number of failures of a web test), and ThresholdRuleCondition (based on the - threshold of a metric). Required. - :vartype odata_type: str - :ivar data_source: the resource from which the rule collects its data. For this type dataSource - will always be of type RuleMetricDataSource. - :vartype data_source: ~azure.mgmt.monitor.v2015_04_01.models.RuleDataSource - :ivar aggregation: How the data that is collected should be combined over time and when the - alert is activated. Note that for management event alerts aggregation is optional – if it is - not provided then any event will cause the alert to activate. - :vartype aggregation: - ~azure.mgmt.monitor.v2015_04_01.models.ManagementEventAggregationCondition - """ - - _validation = { - "odata_type": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "odata\\.type", "type": "str"}, - "data_source": {"key": "dataSource", "type": "RuleDataSource"}, - "aggregation": {"key": "aggregation", "type": "ManagementEventAggregationCondition"}, - } - - def __init__( - self, - *, - data_source: Optional["_models.RuleDataSource"] = None, - aggregation: Optional["_models.ManagementEventAggregationCondition"] = None, - **kwargs: Any - ) -> None: - """ - :keyword data_source: the resource from which the rule collects its data. For this type - dataSource will always be of type RuleMetricDataSource. - :paramtype data_source: ~azure.mgmt.monitor.v2015_04_01.models.RuleDataSource - :keyword aggregation: How the data that is collected should be combined over time and when the - alert is activated. Note that for management event alerts aggregation is optional – if it is - not provided then any event will cause the alert to activate. - :paramtype aggregation: - ~azure.mgmt.monitor.v2015_04_01.models.ManagementEventAggregationCondition - """ - super().__init__(data_source=data_source, **kwargs) - self.odata_type: str = "Microsoft.Azure.Management.Insights.Models.ManagementEventRuleCondition" - self.aggregation = aggregation - - -class MetricTrigger(_serialization.Model): # pylint: disable=too-many-instance-attributes +class MetricTrigger(_serialization.Model): """The trigger that results in a scaling action. - 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 metric_name: the name of the metric that defines what the rule monitors. Required. :vartype metric_name: str @@ -1218,7 +793,7 @@ class MetricTrigger(_serialization.Model): # pylint: disable=too-many-instance- :ivar threshold: the threshold of the metric that triggers the scale action. Required. :vartype threshold: float :ivar dimensions: List of dimension conditions. For example: - [{"DimensionName":"AppName","Operator":"Equals","Values":["App1"]},{"DimensionName":"Deployment","Operator":"Equals","Values":["default"]}]. + [{"DimensionName":"AppName","Operator":"Equals","Values":["App1"]},{"DimensionName":"Deployment","Operator":"Equals","Values":["default"]}]. # pylint: disable=line-too-long :vartype dimensions: list[~azure.mgmt.monitor.v2015_04_01.models.ScaleRuleMetricDimension] :ivar divide_per_instance: a value indicating whether metric should divide per instance. :vartype divide_per_instance: bool @@ -1299,7 +874,7 @@ def __init__( :keyword threshold: the threshold of the metric that triggers the scale action. Required. :paramtype threshold: float :keyword dimensions: List of dimension conditions. For example: - [{"DimensionName":"AppName","Operator":"Equals","Values":["App1"]},{"DimensionName":"Deployment","Operator":"Equals","Values":["default"]}]. + [{"DimensionName":"AppName","Operator":"Equals","Values":["App1"]},{"DimensionName":"Deployment","Operator":"Equals","Values":["default"]}]. # pylint: disable=line-too-long :paramtype dimensions: list[~azure.mgmt.monitor.v2015_04_01.models.ScaleRuleMetricDimension] :keyword divide_per_instance: a value indicating whether metric should divide per instance. :paramtype divide_per_instance: bool @@ -1419,7 +994,7 @@ class Recurrence(_serialization.Model): """The repeating times at which this profile begins. This element is not used if the FixedDate element is used. - 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 frequency: the recurrence frequency. How often the schedule profile should take effect. This value must be Week, meaning each week will have the same set of profiles. For example, to @@ -1466,7 +1041,7 @@ def __init__( class RecurrentSchedule(_serialization.Model): """The scheduling constraints for when the profile begins. - 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 time_zone: the timezone for the hours of the profile. Some examples of valid time zones are: Dateline Standard Time, UTC-11, Hawaiian Standard Time, Alaskan Standard Time, Pacific @@ -1572,425 +1147,10 @@ def __init__(self, *, time_zone: str, days: List[str], hours: List[int], minutes self.minutes = minutes -class RuleAction(_serialization.Model): - """The action that is performed when the alert rule becomes active, and when an alert condition is - resolved. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - RuleEmailAction, RuleWebhookAction - - All required parameters must be populated in order to send to Azure. - - :ivar odata_type: specifies the type of the action. There are two types of actions: - RuleEmailAction and RuleWebhookAction. Required. - :vartype odata_type: str - """ - - _validation = { - "odata_type": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "odata\\.type", "type": "str"}, - } - - _subtype_map = { - "odata_type": { - "Microsoft.Azure.Management.Insights.Models.RuleEmailAction": "RuleEmailAction", - "Microsoft.Azure.Management.Insights.Models.RuleWebhookAction": "RuleWebhookAction", - } - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.odata_type: Optional[str] = None - - -class RuleDataSource(_serialization.Model): - """The resource from which the rule collects its data. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - RuleManagementEventDataSource, RuleMetricDataSource - - All required parameters must be populated in order to send to Azure. - - :ivar odata_type: specifies the type of data source. There are two types of rule data sources: - RuleMetricDataSource and RuleManagementEventDataSource. Required. - :vartype odata_type: str - :ivar resource_uri: the resource identifier of the resource the rule monitors. **NOTE**\ : this - property cannot be updated for an existing rule. - :vartype resource_uri: str - :ivar legacy_resource_id: the legacy resource identifier of the resource the rule monitors. - **NOTE**\ : this property cannot be updated for an existing rule. - :vartype legacy_resource_id: str - :ivar resource_location: the location of the resource. - :vartype resource_location: str - :ivar metric_namespace: the namespace of the metric. - :vartype metric_namespace: str - """ - - _validation = { - "odata_type": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "odata\\.type", "type": "str"}, - "resource_uri": {"key": "resourceUri", "type": "str"}, - "legacy_resource_id": {"key": "legacyResourceId", "type": "str"}, - "resource_location": {"key": "resourceLocation", "type": "str"}, - "metric_namespace": {"key": "metricNamespace", "type": "str"}, - } - - _subtype_map = { - "odata_type": { - "Microsoft.Azure.Management.Insights.Models.RuleManagementEventDataSource": "RuleManagementEventDataSource", - "Microsoft.Azure.Management.Insights.Models.RuleMetricDataSource": "RuleMetricDataSource", - } - } - - def __init__( - self, - *, - resource_uri: Optional[str] = None, - legacy_resource_id: Optional[str] = None, - resource_location: Optional[str] = None, - metric_namespace: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword resource_uri: the resource identifier of the resource the rule monitors. **NOTE**\ : - this property cannot be updated for an existing rule. - :paramtype resource_uri: str - :keyword legacy_resource_id: the legacy resource identifier of the resource the rule monitors. - **NOTE**\ : this property cannot be updated for an existing rule. - :paramtype legacy_resource_id: str - :keyword resource_location: the location of the resource. - :paramtype resource_location: str - :keyword metric_namespace: the namespace of the metric. - :paramtype metric_namespace: str - """ - super().__init__(**kwargs) - self.odata_type: Optional[str] = None - self.resource_uri = resource_uri - self.legacy_resource_id = legacy_resource_id - self.resource_location = resource_location - self.metric_namespace = metric_namespace - - -class RuleEmailAction(RuleAction): - """Specifies the action to send email when the rule condition is evaluated. The discriminator is - always RuleEmailAction in this case. - - All required parameters must be populated in order to send to Azure. - - :ivar odata_type: specifies the type of the action. There are two types of actions: - RuleEmailAction and RuleWebhookAction. Required. - :vartype odata_type: str - :ivar send_to_service_owners: Whether the administrators (service and co-administrators) of the - service should be notified when the alert is activated. - :vartype send_to_service_owners: bool - :ivar custom_emails: the list of administrator's custom email addresses to notify of the - activation of the alert. - :vartype custom_emails: list[str] - """ - - _validation = { - "odata_type": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "odata\\.type", "type": "str"}, - "send_to_service_owners": {"key": "sendToServiceOwners", "type": "bool"}, - "custom_emails": {"key": "customEmails", "type": "[str]"}, - } - - def __init__( - self, *, send_to_service_owners: Optional[bool] = None, custom_emails: Optional[List[str]] = None, **kwargs: Any - ) -> None: - """ - :keyword send_to_service_owners: Whether the administrators (service and co-administrators) of - the service should be notified when the alert is activated. - :paramtype send_to_service_owners: bool - :keyword custom_emails: the list of administrator's custom email addresses to notify of the - activation of the alert. - :paramtype custom_emails: list[str] - """ - super().__init__(**kwargs) - self.odata_type: str = "Microsoft.Azure.Management.Insights.Models.RuleEmailAction" - self.send_to_service_owners = send_to_service_owners - self.custom_emails = custom_emails - - -class RuleManagementEventClaimsDataSource(_serialization.Model): - """The claims for a rule management event data source. - - :ivar email_address: the email address. - :vartype email_address: str - """ - - _attribute_map = { - "email_address": {"key": "emailAddress", "type": "str"}, - } - - def __init__(self, *, email_address: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword email_address: the email address. - :paramtype email_address: str - """ - super().__init__(**kwargs) - self.email_address = email_address - - -class RuleManagementEventDataSource(RuleDataSource): # pylint: disable=too-many-instance-attributes - """A rule management event data source. The discriminator fields is always - RuleManagementEventDataSource in this case. - - All required parameters must be populated in order to send to Azure. - - :ivar odata_type: specifies the type of data source. There are two types of rule data sources: - RuleMetricDataSource and RuleManagementEventDataSource. Required. - :vartype odata_type: str - :ivar resource_uri: the resource identifier of the resource the rule monitors. **NOTE**\ : this - property cannot be updated for an existing rule. - :vartype resource_uri: str - :ivar legacy_resource_id: the legacy resource identifier of the resource the rule monitors. - **NOTE**\ : this property cannot be updated for an existing rule. - :vartype legacy_resource_id: str - :ivar resource_location: the location of the resource. - :vartype resource_location: str - :ivar metric_namespace: the namespace of the metric. - :vartype metric_namespace: str - :ivar event_name: the event name. - :vartype event_name: str - :ivar event_source: the event source. - :vartype event_source: str - :ivar level: the level. - :vartype level: str - :ivar operation_name: The name of the operation that should be checked for. If no name is - provided, any operation will match. - :vartype operation_name: str - :ivar resource_group_name: the resource group name. - :vartype resource_group_name: str - :ivar resource_provider_name: the resource provider name. - :vartype resource_provider_name: str - :ivar status: The status of the operation that should be checked for. If no status is provided, - any status will match. - :vartype status: str - :ivar sub_status: the substatus. - :vartype sub_status: str - :ivar claims: the claims. - :vartype claims: ~azure.mgmt.monitor.v2015_04_01.models.RuleManagementEventClaimsDataSource - """ - - _validation = { - "odata_type": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "odata\\.type", "type": "str"}, - "resource_uri": {"key": "resourceUri", "type": "str"}, - "legacy_resource_id": {"key": "legacyResourceId", "type": "str"}, - "resource_location": {"key": "resourceLocation", "type": "str"}, - "metric_namespace": {"key": "metricNamespace", "type": "str"}, - "event_name": {"key": "eventName", "type": "str"}, - "event_source": {"key": "eventSource", "type": "str"}, - "level": {"key": "level", "type": "str"}, - "operation_name": {"key": "operationName", "type": "str"}, - "resource_group_name": {"key": "resourceGroupName", "type": "str"}, - "resource_provider_name": {"key": "resourceProviderName", "type": "str"}, - "status": {"key": "status", "type": "str"}, - "sub_status": {"key": "subStatus", "type": "str"}, - "claims": {"key": "claims", "type": "RuleManagementEventClaimsDataSource"}, - } - - def __init__( - self, - *, - resource_uri: Optional[str] = None, - legacy_resource_id: Optional[str] = None, - resource_location: Optional[str] = None, - metric_namespace: Optional[str] = None, - event_name: Optional[str] = None, - event_source: Optional[str] = None, - level: Optional[str] = None, - operation_name: Optional[str] = None, - resource_group_name: Optional[str] = None, - resource_provider_name: Optional[str] = None, - status: Optional[str] = None, - sub_status: Optional[str] = None, - claims: Optional["_models.RuleManagementEventClaimsDataSource"] = None, - **kwargs: Any - ) -> None: - """ - :keyword resource_uri: the resource identifier of the resource the rule monitors. **NOTE**\ : - this property cannot be updated for an existing rule. - :paramtype resource_uri: str - :keyword legacy_resource_id: the legacy resource identifier of the resource the rule monitors. - **NOTE**\ : this property cannot be updated for an existing rule. - :paramtype legacy_resource_id: str - :keyword resource_location: the location of the resource. - :paramtype resource_location: str - :keyword metric_namespace: the namespace of the metric. - :paramtype metric_namespace: str - :keyword event_name: the event name. - :paramtype event_name: str - :keyword event_source: the event source. - :paramtype event_source: str - :keyword level: the level. - :paramtype level: str - :keyword operation_name: The name of the operation that should be checked for. If no name is - provided, any operation will match. - :paramtype operation_name: str - :keyword resource_group_name: the resource group name. - :paramtype resource_group_name: str - :keyword resource_provider_name: the resource provider name. - :paramtype resource_provider_name: str - :keyword status: The status of the operation that should be checked for. If no status is - provided, any status will match. - :paramtype status: str - :keyword sub_status: the substatus. - :paramtype sub_status: str - :keyword claims: the claims. - :paramtype claims: ~azure.mgmt.monitor.v2015_04_01.models.RuleManagementEventClaimsDataSource - """ - super().__init__( - resource_uri=resource_uri, - legacy_resource_id=legacy_resource_id, - resource_location=resource_location, - metric_namespace=metric_namespace, - **kwargs - ) - self.odata_type: str = "Microsoft.Azure.Management.Insights.Models.RuleManagementEventDataSource" - self.event_name = event_name - self.event_source = event_source - self.level = level - self.operation_name = operation_name - self.resource_group_name = resource_group_name - self.resource_provider_name = resource_provider_name - self.status = status - self.sub_status = sub_status - self.claims = claims - - -class RuleMetricDataSource(RuleDataSource): - """A rule metric data source. The discriminator value is always RuleMetricDataSource in this case. - - All required parameters must be populated in order to send to Azure. - - :ivar odata_type: specifies the type of data source. There are two types of rule data sources: - RuleMetricDataSource and RuleManagementEventDataSource. Required. - :vartype odata_type: str - :ivar resource_uri: the resource identifier of the resource the rule monitors. **NOTE**\ : this - property cannot be updated for an existing rule. - :vartype resource_uri: str - :ivar legacy_resource_id: the legacy resource identifier of the resource the rule monitors. - **NOTE**\ : this property cannot be updated for an existing rule. - :vartype legacy_resource_id: str - :ivar resource_location: the location of the resource. - :vartype resource_location: str - :ivar metric_namespace: the namespace of the metric. - :vartype metric_namespace: str - :ivar metric_name: the name of the metric that defines what the rule monitors. - :vartype metric_name: str - """ - - _validation = { - "odata_type": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "odata\\.type", "type": "str"}, - "resource_uri": {"key": "resourceUri", "type": "str"}, - "legacy_resource_id": {"key": "legacyResourceId", "type": "str"}, - "resource_location": {"key": "resourceLocation", "type": "str"}, - "metric_namespace": {"key": "metricNamespace", "type": "str"}, - "metric_name": {"key": "metricName", "type": "str"}, - } - - def __init__( - self, - *, - resource_uri: Optional[str] = None, - legacy_resource_id: Optional[str] = None, - resource_location: Optional[str] = None, - metric_namespace: Optional[str] = None, - metric_name: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword resource_uri: the resource identifier of the resource the rule monitors. **NOTE**\ : - this property cannot be updated for an existing rule. - :paramtype resource_uri: str - :keyword legacy_resource_id: the legacy resource identifier of the resource the rule monitors. - **NOTE**\ : this property cannot be updated for an existing rule. - :paramtype legacy_resource_id: str - :keyword resource_location: the location of the resource. - :paramtype resource_location: str - :keyword metric_namespace: the namespace of the metric. - :paramtype metric_namespace: str - :keyword metric_name: the name of the metric that defines what the rule monitors. - :paramtype metric_name: str - """ - super().__init__( - resource_uri=resource_uri, - legacy_resource_id=legacy_resource_id, - resource_location=resource_location, - metric_namespace=metric_namespace, - **kwargs - ) - self.odata_type: str = "Microsoft.Azure.Management.Insights.Models.RuleMetricDataSource" - self.metric_name = metric_name - - -class RuleWebhookAction(RuleAction): - """Specifies the action to post to service when the rule condition is evaluated. The discriminator - is always RuleWebhookAction in this case. - - All required parameters must be populated in order to send to Azure. - - :ivar odata_type: specifies the type of the action. There are two types of actions: - RuleEmailAction and RuleWebhookAction. Required. - :vartype odata_type: str - :ivar service_uri: the service uri to Post the notification when the alert activates or - resolves. - :vartype service_uri: str - :ivar properties: the dictionary of custom properties to include with the post operation. These - data are appended to the webhook payload. - :vartype properties: dict[str, str] - """ - - _validation = { - "odata_type": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "odata\\.type", "type": "str"}, - "service_uri": {"key": "serviceUri", "type": "str"}, - "properties": {"key": "properties", "type": "{str}"}, - } - - def __init__( - self, *, service_uri: Optional[str] = None, properties: Optional[Dict[str, str]] = None, **kwargs: Any - ) -> None: - """ - :keyword service_uri: the service uri to Post the notification when the alert activates or - resolves. - :paramtype service_uri: str - :keyword properties: the dictionary of custom properties to include with the post operation. - These data are appended to the webhook payload. - :paramtype properties: dict[str, str] - """ - super().__init__(**kwargs) - self.odata_type: str = "Microsoft.Azure.Management.Insights.Models.RuleWebhookAction" - self.service_uri = service_uri - self.properties = properties - - class ScaleAction(_serialization.Model): """The parameters for the scaling action. - 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 direction: the scale direction. Whether the scaling action increases or decreases the number of instances. Required. Known values are: "None", "Increase", and "Decrease". @@ -2052,7 +1212,7 @@ def __init__( class ScaleCapacity(_serialization.Model): """The number of instances that can be used during this profile. - 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 minimum: the minimum number of instances for the resource. Required. :vartype minimum: str @@ -2098,7 +1258,7 @@ def __init__(self, *, minimum: str, maximum: str, default: str, **kwargs: Any) - class ScaleRule(_serialization.Model): """A rule that provide the triggers and parameters for the scaling action. - 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 metric_trigger: the trigger that results in a scaling action. Required. :vartype metric_trigger: ~azure.mgmt.monitor.v2015_04_01.models.MetricTrigger @@ -2133,7 +1293,7 @@ def __init__( class ScaleRuleMetricDimension(_serialization.Model): """Specifies an auto scale rule metric dimension. - 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 dimension_name: Name of the dimension. Required. :vartype dimension_name: str @@ -2219,91 +1379,10 @@ def __init__( self.scope = scope -class ThresholdRuleCondition(RuleCondition): - """A rule condition based on a metric crossing a threshold. - - All required parameters must be populated in order to send to Azure. - - :ivar odata_type: specifies the type of condition. This can be one of three types: - ManagementEventRuleCondition (occurrences of management events), LocationThresholdRuleCondition - (based on the number of failures of a web test), and ThresholdRuleCondition (based on the - threshold of a metric). Required. - :vartype odata_type: str - :ivar data_source: the resource from which the rule collects its data. For this type dataSource - will always be of type RuleMetricDataSource. - :vartype data_source: ~azure.mgmt.monitor.v2015_04_01.models.RuleDataSource - :ivar operator: the operator used to compare the data and the threshold. Required. Known values - are: "GreaterThan", "GreaterThanOrEqual", "LessThan", and "LessThanOrEqual". - :vartype operator: str or ~azure.mgmt.monitor.v2015_04_01.models.ConditionOperator - :ivar threshold: the threshold value that activates the alert. Required. - :vartype threshold: float - :ivar window_size: the period of time (in ISO 8601 duration format) that is used to monitor - alert activity based on the threshold. If specified then it must be between 5 minutes and 1 - day. - :vartype window_size: ~datetime.timedelta - :ivar time_aggregation: the time aggregation operator. How the data that are collected should - be combined over time. The default value is the PrimaryAggregationType of the Metric. Known - values are: "Average", "Minimum", "Maximum", "Total", and "Last". - :vartype time_aggregation: str or - ~azure.mgmt.monitor.v2015_04_01.models.TimeAggregationOperator - """ - - _validation = { - "odata_type": {"required": True}, - "operator": {"required": True}, - "threshold": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "odata\\.type", "type": "str"}, - "data_source": {"key": "dataSource", "type": "RuleDataSource"}, - "operator": {"key": "operator", "type": "str"}, - "threshold": {"key": "threshold", "type": "float"}, - "window_size": {"key": "windowSize", "type": "duration"}, - "time_aggregation": {"key": "timeAggregation", "type": "str"}, - } - - def __init__( - self, - *, - operator: Union[str, "_models.ConditionOperator"], - threshold: float, - data_source: Optional["_models.RuleDataSource"] = None, - window_size: Optional[datetime.timedelta] = None, - time_aggregation: Optional[Union[str, "_models.TimeAggregationOperator"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword data_source: the resource from which the rule collects its data. For this type - dataSource will always be of type RuleMetricDataSource. - :paramtype data_source: ~azure.mgmt.monitor.v2015_04_01.models.RuleDataSource - :keyword operator: the operator used to compare the data and the threshold. Required. Known - values are: "GreaterThan", "GreaterThanOrEqual", "LessThan", and "LessThanOrEqual". - :paramtype operator: str or ~azure.mgmt.monitor.v2015_04_01.models.ConditionOperator - :keyword threshold: the threshold value that activates the alert. Required. - :paramtype threshold: float - :keyword window_size: the period of time (in ISO 8601 duration format) that is used to monitor - alert activity based on the threshold. If specified then it must be between 5 minutes and 1 - day. - :paramtype window_size: ~datetime.timedelta - :keyword time_aggregation: the time aggregation operator. How the data that are collected - should be combined over time. The default value is the PrimaryAggregationType of the Metric. - Known values are: "Average", "Minimum", "Maximum", "Total", and "Last". - :paramtype time_aggregation: str or - ~azure.mgmt.monitor.v2015_04_01.models.TimeAggregationOperator - """ - super().__init__(data_source=data_source, **kwargs) - self.odata_type: str = "Microsoft.Azure.Management.Insights.Models.ThresholdRuleCondition" - self.operator = operator - self.threshold = threshold - self.window_size = window_size - self.time_aggregation = time_aggregation - - class TimeWindow(_serialization.Model): """A specific date-time for the profile. - 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 time_zone: the timezone of the start and end times for the profile. Some examples of valid time zones are: Dateline Standard Time, UTC-11, Hawaiian Standard Time, Alaskan Standard diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/models/_monitor_management_client_enums.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/models/_monitor_management_client_enums.py index c8326c1a0246..c510e8488d2d 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/models/_monitor_management_client_enums.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/models/_monitor_management_client_enums.py @@ -21,15 +21,6 @@ class ComparisonOperationType(str, Enum, metaclass=CaseInsensitiveEnumMeta): LESS_THAN_OR_EQUAL = "LessThanOrEqual" -class ConditionOperator(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Operators allowed in the rule condition.""" - - GREATER_THAN = "GreaterThan" - GREATER_THAN_OR_EQUAL = "GreaterThanOrEqual" - LESS_THAN = "LessThan" - LESS_THAN_OR_EQUAL = "LessThanOrEqual" - - class EventLevel(str, Enum, metaclass=CaseInsensitiveEnumMeta): """the event level.""" @@ -93,16 +84,6 @@ class ScaleType(str, Enum, metaclass=CaseInsensitiveEnumMeta): SERVICE_ALLOWED_NEXT_VALUE = "ServiceAllowedNextValue" -class TimeAggregationOperator(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Aggregation operators allowed in a rule.""" - - AVERAGE = "Average" - MINIMUM = "Minimum" - MAXIMUM = "Maximum" - TOTAL = "Total" - LAST = "Last" - - class TimeAggregationType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """time aggregation type. How the data that is collected should be combined over time. The default value is Average. diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/operations/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/operations/__init__.py index c3fc4cfffbbe..53c594e43fbc 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/operations/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/operations/__init__.py @@ -5,16 +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 ._activity_logs_operations import ActivityLogsOperations -from ._autoscale_settings_operations import AutoscaleSettingsOperations -from ._event_categories_operations import EventCategoriesOperations -from ._operations import Operations -from ._tenant_activity_logs_operations import TenantActivityLogsOperations -from ._alert_rules_operations import AlertRulesOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._activity_logs_operations import ActivityLogsOperations # type: ignore +from ._autoscale_settings_operations import AutoscaleSettingsOperations # type: ignore +from ._event_categories_operations import EventCategoriesOperations # type: ignore +from ._operations import Operations # type: ignore +from ._tenant_activity_logs_operations import TenantActivityLogsOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ @@ -23,7 +28,6 @@ "EventCategoriesOperations", "Operations", "TenantActivityLogsOperations", - "AlertRulesOperations", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/operations/_activity_logs_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/operations/_activity_logs_operations.py index 41448270c836..a0eb5f611113 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/operations/_activity_logs_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/operations/_activity_logs_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,7 +5,9 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +import urllib.parse from azure.core.exceptions import ( ClientAuthenticationError, @@ -18,16 +19,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, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -52,7 +55,7 @@ def build_list_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -84,6 +87,7 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list(self, filter: str, select: Optional[str] = None, **kwargs: Any) -> Iterable["_models.EventData"]: @@ -92,28 +96,27 @@ def list(self, filter: str, select: Optional[str] = None, **kwargs: Any) -> Iter :param filter: Reduces the set of data collected.:code:`
`This argument is required and it also requires at least the start date/time.:code:`
`The **$filter** argument is very restricted and allows only the following patterns.:code:`
`- *List events for a resource - group*\ : $filter=eventTimestamp ge '2014-07-16T04:36:37.6407898Z' and eventTimestamp le + group*\\ : $filter=eventTimestamp ge '2014-07-16T04:36:37.6407898Z' and eventTimestamp le '2014-07-20T04:36:37.6407898Z' and resourceGroupName eq 'resourceGroupName'.:code:`
`- *List - events for resource*\ : $filter=eventTimestamp ge '2014-07-16T04:36:37.6407898Z' and + events for resource*\\ : $filter=eventTimestamp ge '2014-07-16T04:36:37.6407898Z' and eventTimestamp le '2014-07-20T04:36:37.6407898Z' and resourceUri eq 'resourceURI'.:code:`
`- - *List events for a subscription in a time range*\ : $filter=eventTimestamp ge + *List events for a subscription in a time range*\\ : $filter=eventTimestamp ge '2014-07-16T04:36:37.6407898Z' and eventTimestamp le - '2014-07-20T04:36:37.6407898Z'.:code:`
`- *List events for a resource provider*\ : + '2014-07-20T04:36:37.6407898Z'.:code:`
`- *List events for a resource provider*\\ : $filter=eventTimestamp ge '2014-07-16T04:36:37.6407898Z' and eventTimestamp le '2014-07-20T04:36:37.6407898Z' and resourceProvider eq 'resourceProviderName'.:code:`
`- - *List events for a correlation Id*\ : $filter=eventTimestamp ge '2014-07-16T04:36:37.6407898Z' + *List events for a correlation Id*\\ : $filter=eventTimestamp ge '2014-07-16T04:36:37.6407898Z' and eventTimestamp le '2014-07-20T04:36:37.6407898Z' and correlationId eq - 'correlationID'.:code:`
`:code:`
`\ **NOTE**\ : No other syntax is allowed. Required. + 'correlationID'.:code:`
`:code:`
`\\ **NOTE**\\ : No other syntax is allowed. Required. :type filter: str :param select: Used to fetch events with only the given properties.:code:`
`The **$select** argument is a comma separated list of property names to be returned. Possible values are: - *authorization*\ , *claims*\ , *correlationId*\ , *description*\ , *eventDataId*\ , - *eventName*\ , *eventTimestamp*\ , *httpRequest*\ , *level*\ , *operationId*\ , - *operationName*\ , *properties*\ , *resourceGroupName*\ , *resourceProviderName*\ , - *resourceId*\ , *status*\ , *submissionTimestamp*\ , *subStatus*\ , *subscriptionId*. Default - value is None. + *authorization*\\ , *claims*\\ , *correlationId*\\ , *description*\\ , *eventDataId*\\ , + *eventName*\\ , *eventTimestamp*\\ , *httpRequest*\\ , *level*\\ , *operationId*\\ , + *operationName*\\ , *properties*\\ , *resourceGroupName*\\ , *resourceProviderName*\\ , + *resourceId*\\ , *status*\\ , *submissionTimestamp*\\ , *subStatus*\\ , *subscriptionId*. + Default value is None. :type select: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either EventData or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.monitor.v2015_04_01.models.EventData] :raises ~azure.core.exceptions.HttpResponseError: @@ -121,10 +124,10 @@ def list(self, filter: str, select: Optional[str] = None, **kwargs: Any) -> Iter _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2015-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2015-04-01")) cls: ClsType[_models.EventDataCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -135,24 +138,32 @@ def list(self, filter: str, select: Optional[str] = None, **kwargs: Any) -> Iter def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( subscription_id=self._config.subscription_id, filter=filter, select=select, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: - request = HttpRequest("GET", next_link) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + # 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._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("EventDataCollection", pipeline_response) @@ -162,11 +173,11 @@ def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -178,5 +189,3 @@ def get_next(next_link=None): return pipeline_response return ItemPaged(get_next, extract_data) - - list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/eventtypes/management/values"} diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/operations/_autoscale_settings_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/operations/_autoscale_settings_operations.py index 9f69f7172c88..4a051ff64704 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/operations/_autoscale_settings_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/operations/_autoscale_settings_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,7 +5,10 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload +import urllib.parse from azure.core.exceptions import ( ClientAuthenticationError, @@ -18,16 +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, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -54,7 +58,7 @@ def build_list_by_resource_group_request(resource_group_name: str, subscription_ "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -88,7 +92,7 @@ def build_create_or_update_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -123,7 +127,7 @@ def build_delete_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -156,7 +160,7 @@ def build_get_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -190,7 +194,7 @@ def build_update_request( "autoscaleSettingName": _SERIALIZER.url("autoscale_setting_name", autoscale_setting_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -216,7 +220,7 @@ def build_list_by_subscription_request(subscription_id: str, **kwargs: Any) -> H "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -245,6 +249,7 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list_by_resource_group( @@ -255,7 +260,6 @@ def list_by_resource_group( :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either AutoscaleSettingResource or the result of cls(response) :rtype: @@ -265,10 +269,10 @@ def list_by_resource_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2015-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2015-04-01")) cls: ClsType[_models.AutoscaleSettingResourceCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -279,23 +283,31 @@ 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_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: - request = HttpRequest("GET", next_link) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + # 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._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("AutoscaleSettingResourceCollection", pipeline_response) @@ -305,11 +317,11 @@ def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -322,10 +334,6 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/autoscalesettings" - } - @overload def create_or_update( self, @@ -348,7 +356,6 @@ def create_or_update( :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: AutoscaleSettingResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2015_04_01.models.AutoscaleSettingResource :raises ~azure.core.exceptions.HttpResponseError: @@ -359,7 +366,7 @@ def create_or_update( self, resource_group_name: str, autoscale_setting_name: str, - parameters: IO, + parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -372,11 +379,10 @@ def create_or_update( :param autoscale_setting_name: The autoscale setting name. Required. :type autoscale_setting_name: str :param parameters: Parameters supplied to the operation. Required. - :type parameters: IO + :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: AutoscaleSettingResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2015_04_01.models.AutoscaleSettingResource :raises ~azure.core.exceptions.HttpResponseError: @@ -387,7 +393,7 @@ def create_or_update( self, resource_group_name: str, autoscale_setting_name: str, - parameters: Union[_models.AutoscaleSettingResource, IO], + parameters: Union[_models.AutoscaleSettingResource, IO[bytes]], **kwargs: Any ) -> _models.AutoscaleSettingResource: """Creates or updates an autoscale setting. @@ -398,17 +404,13 @@ def create_or_update( :param autoscale_setting_name: The autoscale setting name. Required. :type autoscale_setting_name: str :param parameters: Parameters supplied to the operation. Is either a AutoscaleSettingResource - type or a IO type. Required. - :type parameters: ~azure.mgmt.monitor.v2015_04_01.models.AutoscaleSettingResource 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 + type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.monitor.v2015_04_01.models.AutoscaleSettingResource or IO[bytes] :return: AutoscaleSettingResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2015_04_01.models.AutoscaleSettingResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -419,19 +421,19 @@ def create_or_update( _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", "2015-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2015-04-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.AutoscaleSettingResource] = 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, "AutoscaleSettingResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, autoscale_setting_name=autoscale_setting_name, subscription_id=self._config.subscription_id, @@ -439,16 +441,14 @@ def create_or_update( 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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -458,21 +458,13 @@ def create_or_update( 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("AutoscaleSettingResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("AutoscaleSettingResource", pipeline_response) + deserialized = self._deserialize("AutoscaleSettingResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/autoscalesettings/{autoscaleSettingName}" - } - @distributed_trace def delete( # pylint: disable=inconsistent-return-statements self, resource_group_name: str, autoscale_setting_name: str, **kwargs: Any @@ -484,12 +476,11 @@ def delete( # pylint: disable=inconsistent-return-statements :type resource_group_name: str :param autoscale_setting_name: The autoscale setting name. Required. :type autoscale_setting_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, @@ -500,24 +491,22 @@ def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2015-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2015-04-01")) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, autoscale_setting_name=autoscale_setting_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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -528,11 +517,7 @@ def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/autoscalesettings/{autoscaleSettingName}" - } + return cls(pipeline_response, None, {}) # type: ignore @distributed_trace def get( @@ -545,12 +530,11 @@ def get( :type resource_group_name: str :param autoscale_setting_name: The autoscale setting name. Required. :type autoscale_setting_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: AutoscaleSettingResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2015_04_01.models.AutoscaleSettingResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -561,24 +545,22 @@ def get( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2015-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2015-04-01")) cls: ClsType[_models.AutoscaleSettingResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, autoscale_setting_name=autoscale_setting_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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -588,16 +570,12 @@ def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("AutoscaleSettingResource", pipeline_response) + deserialized = self._deserialize("AutoscaleSettingResource", 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.Insights/autoscalesettings/{autoscaleSettingName}" - } + return deserialized # type: ignore @overload def update( @@ -623,7 +601,6 @@ def update( :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: AutoscaleSettingResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2015_04_01.models.AutoscaleSettingResource :raises ~azure.core.exceptions.HttpResponseError: @@ -634,7 +611,7 @@ def update( self, resource_group_name: str, autoscale_setting_name: str, - autoscale_setting_resource: IO, + autoscale_setting_resource: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -648,11 +625,10 @@ def update( :param autoscale_setting_name: The autoscale setting name. Required. :type autoscale_setting_name: str :param autoscale_setting_resource: Parameters supplied to the operation. Required. - :type autoscale_setting_resource: IO + :type autoscale_setting_resource: 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: AutoscaleSettingResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2015_04_01.models.AutoscaleSettingResource :raises ~azure.core.exceptions.HttpResponseError: @@ -663,7 +639,7 @@ def update( self, resource_group_name: str, autoscale_setting_name: str, - autoscale_setting_resource: Union[_models.AutoscaleSettingResourcePatch, IO], + autoscale_setting_resource: Union[_models.AutoscaleSettingResourcePatch, IO[bytes]], **kwargs: Any ) -> _models.AutoscaleSettingResource: """Updates an existing AutoscaleSettingsResource. To update other fields use the CreateOrUpdate @@ -675,18 +651,14 @@ def update( :param autoscale_setting_name: The autoscale setting name. Required. :type autoscale_setting_name: str :param autoscale_setting_resource: Parameters supplied to the operation. Is either a - AutoscaleSettingResourcePatch type or a IO type. Required. + AutoscaleSettingResourcePatch type or a IO[bytes] type. Required. :type autoscale_setting_resource: - ~azure.mgmt.monitor.v2015_04_01.models.AutoscaleSettingResourcePatch 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 + ~azure.mgmt.monitor.v2015_04_01.models.AutoscaleSettingResourcePatch or IO[bytes] :return: AutoscaleSettingResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2015_04_01.models.AutoscaleSettingResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -697,19 +669,19 @@ def update( _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", "2015-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2015-04-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.AutoscaleSettingResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(autoscale_setting_resource, (IO, bytes)): + if isinstance(autoscale_setting_resource, (IOBase, bytes)): _content = autoscale_setting_resource else: _json = self._serialize.body(autoscale_setting_resource, "AutoscaleSettingResourcePatch") - request = build_update_request( + _request = build_update_request( resource_group_name=resource_group_name, autoscale_setting_name=autoscale_setting_name, subscription_id=self._config.subscription_id, @@ -717,16 +689,14 @@ def update( 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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -736,22 +706,17 @@ def update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("AutoscaleSettingResource", pipeline_response) + deserialized = self._deserialize("AutoscaleSettingResource", 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.Insights/autoscalesettings/{autoscaleSettingName}" - } + return deserialized # type: ignore @distributed_trace def list_by_subscription(self, **kwargs: Any) -> Iterable["_models.AutoscaleSettingResource"]: """Lists the autoscale settings for a subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either AutoscaleSettingResource or the result of cls(response) :rtype: @@ -761,10 +726,10 @@ def list_by_subscription(self, **kwargs: Any) -> Iterable["_models.AutoscaleSett _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2015-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2015-04-01")) cls: ClsType[_models.AutoscaleSettingResourceCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -775,22 +740,30 @@ def list_by_subscription(self, **kwargs: Any) -> Iterable["_models.AutoscaleSett def prepare_request(next_link=None): if not next_link: - request = build_list_by_subscription_request( + _request = build_list_by_subscription_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_subscription.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: - request = HttpRequest("GET", next_link) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + # 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._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("AutoscaleSettingResourceCollection", pipeline_response) @@ -800,11 +773,11 @@ def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -816,7 +789,3 @@ def get_next(next_link=None): return pipeline_response return ItemPaged(get_next, extract_data) - - list_by_subscription.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/autoscalesettings" - } diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/operations/_event_categories_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/operations/_event_categories_operations.py index a09308f98491..ddd87ce1cf6e 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/operations/_event_categories_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/operations/_event_categories_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,7 +5,9 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +import urllib.parse from azure.core.exceptions import ( ClientAuthenticationError, @@ -18,16 +19,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 +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -72,6 +75,7 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list(self, **kwargs: Any) -> Iterable["_models.LocalizableString"]: @@ -79,7 +83,6 @@ def list(self, **kwargs: Any) -> Iterable["_models.LocalizableString"]: Service.:code:`
`The current list includes the following: Administrative, Security, ServiceHealth, Alert, Recommendation, Policy. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either LocalizableString or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.monitor.v2015_04_01.models.LocalizableString] :raises ~azure.core.exceptions.HttpResponseError: @@ -87,10 +90,10 @@ def list(self, **kwargs: Any) -> Iterable["_models.LocalizableString"]: _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2015-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2015-04-01")) cls: ClsType[_models.EventCategoryCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -101,21 +104,29 @@ def list(self, **kwargs: Any) -> Iterable["_models.LocalizableString"]: 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) + _request.url = self._client.format_url(_request.url) else: - request = HttpRequest("GET", next_link) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + # 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._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("EventCategoryCollection", pipeline_response) @@ -125,11 +136,11 @@ def extract_data(pipeline_response): return None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -141,5 +152,3 @@ def get_next(next_link=None): return pipeline_response return ItemPaged(get_next, extract_data) - - list.metadata = {"url": "/providers/Microsoft.Insights/eventcategories"} diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/operations/_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/operations/_operations.py index 05ac4a16b7d4..b994a6b05967 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/operations/_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/operations/_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,7 @@ # 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 ( @@ -17,16 +17,18 @@ map_error, ) 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 +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -71,17 +73,17 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list(self, **kwargs: Any) -> _models.OperationListResult: """Lists all of the available operations from Microsoft.Insights provider. - :keyword callable cls: A custom type or function that will be passed the direct response :return: OperationListResult or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2015_04_01.models.OperationListResult :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -92,21 +94,19 @@ def list(self, **kwargs: Any) -> _models.OperationListResult: _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2015-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2015-04-01")) cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) - 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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -115,11 +115,9 @@ def list(self, **kwargs: Any) -> _models.OperationListResult: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize("OperationListResult", pipeline_response) + deserialized = self._deserialize("OperationListResult", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - list.metadata = {"url": "/providers/Microsoft.Insights/operations"} + return deserialized # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/operations/_tenant_activity_logs_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/operations/_tenant_activity_logs_operations.py index 60dea5639b33..776751fc1349 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/operations/_tenant_activity_logs_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/operations/_tenant_activity_logs_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,7 +5,9 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +import urllib.parse from azure.core.exceptions import ( ClientAuthenticationError, @@ -18,16 +19,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 +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -76,6 +79,7 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list( @@ -101,18 +105,17 @@ def list( ':code:``'.:code:`
`- List events for a correlation Id: api-version=2014-04-01&$filter=eventTimestamp ge '2014-07-16T04:36:37.6407898Z' and eventTimestamp le '2014-07-20T04:36:37.6407898Z' and eventChannels eq 'Admin, Operation' and - correlationId eq ':code:``'.:code:`
`\ **NOTE**\ : No other syntax is + correlationId eq ':code:``'.:code:`
`\\ **NOTE**\\ : No other syntax is allowed. Default value is None. :type filter: str :param select: Used to fetch events with only the given properties.:code:`
`The **$select** argument is a comma separated list of property names to be returned. Possible values are: - *authorization*\ , *claims*\ , *correlationId*\ , *description*\ , *eventDataId*\ , - *eventName*\ , *eventTimestamp*\ , *httpRequest*\ , *level*\ , *operationId*\ , - *operationName*\ , *properties*\ , *resourceGroupName*\ , *resourceProviderName*\ , - *resourceId*\ , *status*\ , *submissionTimestamp*\ , *subStatus*\ , *subscriptionId*. Default - value is None. + *authorization*\\ , *claims*\\ , *correlationId*\\ , *description*\\ , *eventDataId*\\ , + *eventName*\\ , *eventTimestamp*\\ , *httpRequest*\\ , *level*\\ , *operationId*\\ , + *operationName*\\ , *properties*\\ , *resourceGroupName*\\ , *resourceProviderName*\\ , + *resourceId*\\ , *status*\\ , *submissionTimestamp*\\ , *subStatus*\\ , *subscriptionId*. + Default value is None. :type select: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either EventData or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.monitor.v2015_04_01.models.EventData] :raises ~azure.core.exceptions.HttpResponseError: @@ -120,10 +123,10 @@ def list( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2015-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2015-04-01")) cls: ClsType[_models.EventDataCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -134,23 +137,31 @@ def list( def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( filter=filter, select=select, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: - request = HttpRequest("GET", next_link) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + # 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._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("EventDataCollection", pipeline_response) @@ -160,11 +171,11 @@ def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -176,5 +187,3 @@ def get_next(next_link=None): return pipeline_response return ItemPaged(get_next, extract_data) - - list.metadata = {"url": "/providers/Microsoft.Insights/eventtypes/management/values"} diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/__init__.py index 2c7733bfd566..42cc62301757 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/__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 ._monitor_management_client import MonitorManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._monitor_management_client import MonitorManagementClient # type: ignore from ._version import VERSION __version__ = VERSION try: from ._patch import __all__ as _patch_all - from ._patch import * # 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__ = [ "MonitorManagementClient", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/_configuration.py index 84225ab1970a..83086ea53872 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/_configuration.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/_configuration.py @@ -8,18 +8,16 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy from ._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MonitorManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class MonitorManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for MonitorManagementClient. Note that all parameters used to create this instance are saved as instance @@ -27,21 +25,22 @@ class MonitorManagementClientConfiguration(Configuration): # pylint: disable=to :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: The ID of the target subscription. Required. - :type subscription_id: str + :keyword api_version: Api Version. Default value is "2015-07-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(MonitorManagementClientConfiguration, self).__init__(**kwargs) + def __init__(self, credential: "TokenCredential", **kwargs: Any) -> None: + api_version: str = kwargs.pop("api_version", "2015-07-01") + if credential is None: raise ValueError("Parameter 'credential' must not be None.") - if subscription_id is None: - raise ValueError("Parameter 'subscription_id' must not be None.") self.credential = credential - self.subscription_id = subscription_id + self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-monitor/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -50,9 +49,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.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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/_metadata.json b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/_metadata.json index 9a7ac678d6b9..a2259ebac3f8 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/_metadata.json +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/_metadata.json @@ -1,6 +1,6 @@ { "chosen_version": "2015-07-01", - "total_api_version_list": ["2014-04-01", "2015-07-01"], + "total_api_version_list": ["2015-07-01"], "client": { "name": "MonitorManagementClient", "filename": "_monitor_management_client", @@ -8,10 +8,10 @@ "host_value": "\"https://management.azure.com\"", "parameterized_host_template": null, "azure_arm": true, - "has_lro_operations": false, + "has_public_lro_operations": false, "client_side_validation": false, - "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"sdkcore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMAutoResourceProviderRegistrationPolicy\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}, \"stdlib\": {\"typing_extensions\": [\"Self\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"sdkcore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"AsyncARMAutoResourceProviderRegistrationPolicy\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}, \"stdlib\": {\"typing_extensions\": [\"Self\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "global_parameters": { "sync": { @@ -21,13 +21,6 @@ "docstring_type": "~azure.core.credentials.TokenCredential", "required": true, "method_location": "positional" - }, - "subscription_id": { - "signature": "subscription_id: str,", - "description": "The ID of the target subscription. Required.", - "docstring_type": "str", - "required": true, - "method_location": "positional" } }, "async": { @@ -36,17 +29,11 @@ "description": "Credential needed for the client to connect to Azure. Required.", "docstring_type": "~azure.core.credentials_async.AsyncTokenCredential", "required": true - }, - "subscription_id": { - "signature": "subscription_id: str,", - "description": "The ID of the target subscription. Required.", - "docstring_type": "str", - "required": true } }, "constant": { }, - "call": "credential, subscription_id", + "call": "credential", "service_client_specific": { "sync": { "api_version": { @@ -101,13 +88,12 @@ "credential_scopes": ["https://management.azure.com/.default"], "credential_call_sync": "ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", "credential_call_async": "AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", - "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "sync_imports": "{\"regular\": {\"sdkcore\": {\"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"regular\": {\"sdkcore\": {\"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "operation_groups": { "service_diagnostic_settings": "ServiceDiagnosticSettingsOperations", "metric_definitions": "MetricDefinitionsOperations", - "alert_rules": "AlertRulesOperations", "operations": "Operations" } } diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/_monitor_management_client.py index f731fd10450f..0dd044147c5a 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/_monitor_management_client.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/_monitor_management_client.py @@ -8,26 +8,23 @@ from copy import deepcopy from typing import Any, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient +from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy from . import models as _models from .._serialization import Deserializer, Serializer from ._configuration import MonitorManagementClientConfiguration -from .operations import ( - AlertRulesOperations, - MetricDefinitionsOperations, - Operations, - ServiceDiagnosticSettingsOperations, -) +from .operations import MetricDefinitionsOperations, Operations, ServiceDiagnosticSettingsOperations if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MonitorManagementClient: # pylint: disable=client-accepts-api-version-keyword +class MonitorManagementClient: """Monitor Management Client. :ivar service_diagnostic_settings: ServiceDiagnosticSettingsOperations operations @@ -36,44 +33,54 @@ class MonitorManagementClient: # pylint: disable=client-accepts-api-version-key :ivar metric_definitions: MetricDefinitionsOperations operations :vartype metric_definitions: azure.mgmt.monitor.v2015_07_01.operations.MetricDefinitionsOperations - :ivar alert_rules: AlertRulesOperations operations - :vartype alert_rules: azure.mgmt.monitor.v2015_07_01.operations.AlertRulesOperations :ivar operations: Operations operations :vartype operations: azure.mgmt.monitor.v2015_07_01.operations.Operations :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: The ID of the target subscription. Required. - :type subscription_id: str :param base_url: Service URL. Default value is "https://management.azure.com". :type base_url: str + :keyword api_version: Api Version. Default value is "2015-07-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str """ def __init__( - self, - credential: "TokenCredential", - subscription_id: str, - base_url: str = "https://management.azure.com", - **kwargs: Any + self, credential: "TokenCredential", base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: - self._config = MonitorManagementClientConfiguration( - credential=credential, subscription_id=subscription_id, **kwargs - ) - self._client: ARMPipelineClient = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + self._config = MonitorManagementClientConfiguration(credential=credential, **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), + 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=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.service_diagnostic_settings = ServiceDiagnosticSettingsOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2015-07-01" ) self.metric_definitions = MetricDefinitionsOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2015-07-01" ) - self.alert_rules = AlertRulesOperations(self._client, self._config, self._serialize, self._deserialize) - self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) + self.operations = Operations(self._client, self._config, self._serialize, self._deserialize, "2015-07-01") - 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 @@ -93,12 +100,12 @@ 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) -> None: self._client.close() - def __enter__(self) -> "MonitorManagementClient": + def __enter__(self) -> Self: self._client.__enter__() return self diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/_vendor.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/_vendor.py deleted file mode 100644 index bd0df84f5319..000000000000 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/_vendor.py +++ /dev/null @@ -1,30 +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 typing import List, cast - -from azure.core.pipeline.transport import HttpRequest - - -def _convert_request(request, files=None): - data = request.content if not files else None - request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) - if files: - request.set_formdata_body(files) - return request - - -def _format_url_section(template, **kwargs): - components = template.split("/") - while components: - try: - return template.format(**kwargs) - except KeyError as key: - # Need the cast, as for some reasons "split" is typed as list[str | Any] - formatted_components = cast(List[str], template.split("/")) - components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] - template = "/".join(components) diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/_version.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/_version.py index 394ee7c0c03c..e5754a47ce68 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/_version.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "6.0.2" +VERSION = "1.0.0b1" diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/aio/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/aio/__init__.py index 2c151bb41c19..3df30ff42149 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/aio/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/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 ._monitor_management_client import MonitorManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._monitor_management_client import MonitorManagementClient # type: ignore try: from ._patch import __all__ as _patch_all - from ._patch import * # 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__ = [ "MonitorManagementClient", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/aio/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/aio/_configuration.py index ff77a05cbd87..a4d6bdb17265 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/aio/_configuration.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/aio/_configuration.py @@ -8,18 +8,16 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy from .._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MonitorManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class MonitorManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for MonitorManagementClient. Note that all parameters used to create this instance are saved as instance @@ -27,21 +25,22 @@ class MonitorManagementClientConfiguration(Configuration): # pylint: disable=to :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: The ID of the target subscription. Required. - :type subscription_id: str + :keyword api_version: Api Version. Default value is "2015-07-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(MonitorManagementClientConfiguration, self).__init__(**kwargs) + def __init__(self, credential: "AsyncTokenCredential", **kwargs: Any) -> None: + api_version: str = kwargs.pop("api_version", "2015-07-01") + if credential is None: raise ValueError("Parameter 'credential' must not be None.") - if subscription_id is None: - raise ValueError("Parameter 'subscription_id' must not be None.") self.credential = credential - self.subscription_id = subscription_id + self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-monitor/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -50,9 +49,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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/aio/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/aio/_monitor_management_client.py index 34c68d3a46a3..5da9b3009c59 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/aio/_monitor_management_client.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/aio/_monitor_management_client.py @@ -8,26 +8,23 @@ from copy import deepcopy from typing import Any, Awaitable, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient +from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy from .. import models as _models from ..._serialization import Deserializer, Serializer from ._configuration import MonitorManagementClientConfiguration -from .operations import ( - AlertRulesOperations, - MetricDefinitionsOperations, - Operations, - ServiceDiagnosticSettingsOperations, -) +from .operations import MetricDefinitionsOperations, Operations, ServiceDiagnosticSettingsOperations if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MonitorManagementClient: # pylint: disable=client-accepts-api-version-keyword +class MonitorManagementClient: """Monitor Management Client. :ivar service_diagnostic_settings: ServiceDiagnosticSettingsOperations operations @@ -36,44 +33,56 @@ class MonitorManagementClient: # pylint: disable=client-accepts-api-version-key :ivar metric_definitions: MetricDefinitionsOperations operations :vartype metric_definitions: azure.mgmt.monitor.v2015_07_01.aio.operations.MetricDefinitionsOperations - :ivar alert_rules: AlertRulesOperations operations - :vartype alert_rules: azure.mgmt.monitor.v2015_07_01.aio.operations.AlertRulesOperations :ivar operations: Operations operations :vartype operations: azure.mgmt.monitor.v2015_07_01.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: The ID of the target subscription. Required. - :type subscription_id: str :param base_url: Service URL. Default value is "https://management.azure.com". :type base_url: str + :keyword api_version: Api Version. Default value is "2015-07-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str """ def __init__( - self, - credential: "AsyncTokenCredential", - subscription_id: str, - base_url: str = "https://management.azure.com", - **kwargs: Any + self, credential: "AsyncTokenCredential", base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: - self._config = MonitorManagementClientConfiguration( - credential=credential, subscription_id=subscription_id, **kwargs - ) - self._client: AsyncARMPipelineClient = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + self._config = MonitorManagementClientConfiguration(credential=credential, **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=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.service_diagnostic_settings = ServiceDiagnosticSettingsOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2015-07-01" ) self.metric_definitions = MetricDefinitionsOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2015-07-01" ) - self.alert_rules = AlertRulesOperations(self._client, self._config, self._serialize, self._deserialize) - self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) + self.operations = Operations(self._client, self._config, self._serialize, self._deserialize, "2015-07-01") - 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 @@ -93,12 +102,12 @@ 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) -> "MonitorManagementClient": + async def __aenter__(self) -> Self: await self._client.__aenter__() return self diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/aio/operations/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/aio/operations/__init__.py index acff6da37ac2..091f67164165 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/aio/operations/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/aio/operations/__init__.py @@ -5,21 +5,25 @@ # 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 ._service_diagnostic_settings_operations import ServiceDiagnosticSettingsOperations -from ._metric_definitions_operations import MetricDefinitionsOperations -from ._alert_rules_operations import AlertRulesOperations -from ._operations import Operations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._service_diagnostic_settings_operations import ServiceDiagnosticSettingsOperations # type: ignore +from ._metric_definitions_operations import MetricDefinitionsOperations # type: ignore +from ._operations import Operations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ "ServiceDiagnosticSettingsOperations", "MetricDefinitionsOperations", - "AlertRulesOperations", "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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/aio/operations/_metric_definitions_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/aio/operations/_metric_definitions_operations.py index 51928f7de011..1bf95ea88ffc 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/aio/operations/_metric_definitions_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/aio/operations/_metric_definitions_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,7 +5,9 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( @@ -18,16 +19,18 @@ 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 ...operations._metric_definitions_operations import build_list_request +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -50,6 +53,7 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list( @@ -61,12 +65,11 @@ def list( :type resource_uri: str :param filter: Reduces the set of data collected by retrieving particular metric definitions from all the definitions available for the resource.:code:`
`For example, to get just the - definition for the 'CPU percentage' counter: $filter=name.value eq '\Processor(_Total)\% + definition for the 'CPU percentage' counter: $filter=name.value eq '\\Processor(_Total)\\% Processor Time'.:code:`
`Multiple metrics can be retrieved by joining together *'name eq - :code:``'* clauses separated by *or* logical operators.:code:`
`\ **NOTE**\ : No + :code:``'* clauses separated by *or* logical operators.:code:`
`\\ **NOTE**\\ : No other syntax is allowed. Default value is None. :type filter: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either MetricDefinition or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.monitor.v2015_07_01.models.MetricDefinition] @@ -75,10 +78,10 @@ def list( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2015-07-01")) cls: ClsType[_models.MetricDefinitionCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -89,23 +92,31 @@ def list( def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( resource_uri=resource_uri, filter=filter, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: - request = HttpRequest("GET", next_link) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + # 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._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 async def extract_data(pipeline_response): deserialized = self._deserialize("MetricDefinitionCollection", pipeline_response) @@ -115,11 +126,11 @@ async def extract_data(pipeline_response): return None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -131,5 +142,3 @@ async def get_next(next_link=None): return pipeline_response return AsyncItemPaged(get_next, extract_data) - - list.metadata = {"url": "/{resourceUri}/providers/Microsoft.Insights/metricDefinitions"} diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/aio/operations/_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/aio/operations/_operations.py index 05cc5136db3f..5cc862799a06 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/aio/operations/_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/aio/operations/_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,7 @@ # 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 ( @@ -17,16 +17,18 @@ 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_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._operations import build_list_request +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -49,17 +51,17 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace_async async def list(self, **kwargs: Any) -> _models.OperationListResult: """Lists all of the available operations from Microsoft.Insights provider. - :keyword callable cls: A custom type or function that will be passed the direct response :return: OperationListResult or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2015_07_01.models.OperationListResult :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -70,21 +72,19 @@ async def list(self, **kwargs: Any) -> _models.OperationListResult: _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2015-07-01")) cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) - 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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -94,11 +94,9 @@ async def list(self, **kwargs: Any) -> _models.OperationListResult: error = self._deserialize.failsafe_deserialize(_models.ErrorContract, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("OperationListResult", pipeline_response) + deserialized = self._deserialize("OperationListResult", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - list.metadata = {"url": "/providers/Microsoft.Insights/operations"} + return deserialized # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/aio/operations/_service_diagnostic_settings_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/aio/operations/_service_diagnostic_settings_operations.py index a7d0a3178b8f..a0b26d422a8d 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/aio/operations/_service_diagnostic_settings_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/aio/operations/_service_diagnostic_settings_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload from azure.core.exceptions import ( @@ -17,16 +18,18 @@ 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_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._service_diagnostic_settings_operations import build_create_or_update_request, build_get_request +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -49,6 +52,7 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace_async async def get(self, resource_uri: str, **kwargs: Any) -> _models.ServiceDiagnosticSettingsResource: @@ -56,12 +60,11 @@ async def get(self, resource_uri: str, **kwargs: Any) -> _models.ServiceDiagnost :param resource_uri: The identifier of the resource. Required. :type resource_uri: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ServiceDiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2015_07_01.models.ServiceDiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -72,22 +75,20 @@ async def get(self, resource_uri: str, **kwargs: Any) -> _models.ServiceDiagnost _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2015-07-01")) cls: ClsType[_models.ServiceDiagnosticSettingsResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_uri=resource_uri, api_version=api_version, - template_url=self.get.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -97,14 +98,12 @@ async def get(self, resource_uri: str, **kwargs: Any) -> _models.ServiceDiagnost error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ServiceDiagnosticSettingsResource", pipeline_response) + deserialized = self._deserialize("ServiceDiagnosticSettingsResource", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - get.metadata = {"url": "/{resourceUri}/providers/microsoft.insights/diagnosticSettings/service"} + return deserialized # type: ignore @overload async def create_or_update( @@ -124,7 +123,6 @@ async def create_or_update( :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: ServiceDiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2015_07_01.models.ServiceDiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: @@ -132,18 +130,17 @@ async def create_or_update( @overload async def create_or_update( - self, resource_uri: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + self, resource_uri: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any ) -> _models.ServiceDiagnosticSettingsResource: """Create or update new diagnostic settings for the specified resource. :param resource_uri: The identifier of the resource. Required. :type resource_uri: str :param parameters: Parameters supplied to the operation. Required. - :type parameters: IO + :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: ServiceDiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2015_07_01.models.ServiceDiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: @@ -151,25 +148,21 @@ async def create_or_update( @distributed_trace_async async def create_or_update( - self, resource_uri: str, parameters: Union[_models.ServiceDiagnosticSettingsResource, IO], **kwargs: Any + self, resource_uri: str, parameters: Union[_models.ServiceDiagnosticSettingsResource, IO[bytes]], **kwargs: Any ) -> _models.ServiceDiagnosticSettingsResource: """Create or update new diagnostic settings for the specified resource. :param resource_uri: The identifier of the resource. Required. :type resource_uri: str :param parameters: Parameters supplied to the operation. Is either a - ServiceDiagnosticSettingsResource type or a IO type. Required. + ServiceDiagnosticSettingsResource type or a IO[bytes] type. Required. :type parameters: ~azure.mgmt.monitor.v2015_07_01.models.ServiceDiagnosticSettingsResource 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 + IO[bytes] :return: ServiceDiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2015_07_01.models.ServiceDiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -180,34 +173,32 @@ async def create_or_update( _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", "2015-07-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2015-07-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ServiceDiagnosticSettingsResource] = 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, "ServiceDiagnosticSettingsResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_uri=resource_uri, 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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -216,11 +207,9 @@ async def create_or_update( map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize("ServiceDiagnosticSettingsResource", pipeline_response) + deserialized = self._deserialize("ServiceDiagnosticSettingsResource", 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": "/{resourceUri}/providers/microsoft.insights/diagnosticSettings/service"} + return deserialized # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/models/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/models/__init__.py index 20372e4e30d8..c2e3dcf1a5ad 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/models/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/models/__init__.py @@ -5,64 +5,52 @@ # 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 AlertRuleResource -from ._models_py3 import AlertRuleResourceCollection -from ._models_py3 import AlertRuleResourcePatch -from ._models_py3 import DimensionProperties -from ._models_py3 import ErrorContract -from ._models_py3 import ErrorResponse -from ._models_py3 import LocalizableString -from ._models_py3 import LocationThresholdRuleCondition -from ._models_py3 import LogSettings -from ._models_py3 import LogSpecification -from ._models_py3 import ManagementEventAggregationCondition -from ._models_py3 import ManagementEventRuleCondition -from ._models_py3 import MetricAvailability -from ._models_py3 import MetricAvailabilityLocation -from ._models_py3 import MetricDefinition -from ._models_py3 import MetricDefinitionCollection -from ._models_py3 import MetricSettings -from ._models_py3 import MetricSpecification -from ._models_py3 import Operation -from ._models_py3 import OperationDisplay -from ._models_py3 import OperationListResult -from ._models_py3 import Resource -from ._models_py3 import RetentionPolicy -from ._models_py3 import RuleAction -from ._models_py3 import RuleCondition -from ._models_py3 import RuleDataSource -from ._models_py3 import RuleEmailAction -from ._models_py3 import RuleManagementEventClaimsDataSource -from ._models_py3 import RuleManagementEventDataSource -from ._models_py3 import RuleMetricDataSource -from ._models_py3 import RuleWebhookAction -from ._models_py3 import ServiceDiagnosticSettingsResource -from ._models_py3 import ServiceSpecification -from ._models_py3 import TableInfoEntry -from ._models_py3 import ThresholdRuleCondition +from typing import TYPE_CHECKING -from ._monitor_management_client_enums import AggregationType -from ._monitor_management_client_enums import ConditionOperator -from ._monitor_management_client_enums import TimeAggregationOperator -from ._monitor_management_client_enums import Unit +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models_py3 import ( # type: ignore + DimensionProperties, + ErrorContract, + ErrorResponse, + LocalizableString, + LogSettings, + LogSpecification, + MetricAvailability, + MetricAvailabilityLocation, + MetricDefinition, + MetricDefinitionCollection, + MetricSettings, + MetricSpecification, + Operation, + OperationDisplay, + OperationListResult, + Resource, + RetentionPolicy, + ServiceDiagnosticSettingsResource, + ServiceSpecification, + TableInfoEntry, +) + +from ._monitor_management_client_enums import ( # type: ignore + AggregationType, + Unit, +) from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ - "AlertRuleResource", - "AlertRuleResourceCollection", - "AlertRuleResourcePatch", "DimensionProperties", "ErrorContract", "ErrorResponse", "LocalizableString", - "LocationThresholdRuleCondition", "LogSettings", "LogSpecification", - "ManagementEventAggregationCondition", - "ManagementEventRuleCondition", "MetricAvailability", "MetricAvailabilityLocation", "MetricDefinition", @@ -74,22 +62,11 @@ "OperationListResult", "Resource", "RetentionPolicy", - "RuleAction", - "RuleCondition", - "RuleDataSource", - "RuleEmailAction", - "RuleManagementEventClaimsDataSource", - "RuleManagementEventDataSource", - "RuleMetricDataSource", - "RuleWebhookAction", "ServiceDiagnosticSettingsResource", "ServiceSpecification", "TableInfoEntry", - "ThresholdRuleCondition", "AggregationType", - "ConditionOperator", - "TimeAggregationOperator", "Unit", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/models/_models_py3.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/models/_models_py3.py index 3f108a3518d5..ce438596f2dc 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/models/_models_py3.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/models/_models_py3.py @@ -1,5 +1,5 @@ -# coding=utf-8 # 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. @@ -16,284 +16,13 @@ if sys.version_info >= (3, 9): from collections.abc import MutableMapping else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports + from typing import MutableMapping # type: ignore if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from .. import models as _models JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object -class Resource(_serialization.Model): - """An azure resource object. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to Azure. - - :ivar id: Azure resource Id. - :vartype id: str - :ivar name: Azure resource name. - :vartype name: str - :ivar type: Azure resource type. - :vartype type: str - :ivar location: Resource location. Required. - :vartype location: str - :ivar tags: Resource tags. - :vartype tags: dict[str, str] - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "location": {"required": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "location": {"key": "location", "type": "str"}, - "tags": {"key": "tags", "type": "{str}"}, - } - - def __init__(self, *, location: str, tags: Optional[Dict[str, str]] = None, **kwargs: Any) -> None: - """ - :keyword location: Resource location. Required. - :paramtype location: str - :keyword tags: Resource tags. - :paramtype tags: dict[str, str] - """ - super().__init__(**kwargs) - self.id = None - self.name = None - self.type = None - self.location = location - self.tags = tags - - -class AlertRuleResource(Resource): # pylint: disable=too-many-instance-attributes - """The alert rule resource. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to Azure. - - :ivar id: Azure resource Id. - :vartype id: str - :ivar name: Azure resource name. - :vartype name: str - :ivar type: Azure resource type. - :vartype type: str - :ivar location: Resource location. Required. - :vartype location: str - :ivar tags: Resource tags. - :vartype tags: dict[str, str] - :ivar name_properties_name: the name of the alert rule. Required. - :vartype name_properties_name: str - :ivar description: the description of the alert rule that will be included in the alert email. - :vartype description: str - :ivar provisioning_state: the provisioning state. - :vartype provisioning_state: str - :ivar is_enabled: the flag that indicates whether the alert rule is enabled. Required. - :vartype is_enabled: bool - :ivar condition: the condition that results in the alert rule being activated. Required. - :vartype condition: ~azure.mgmt.monitor.v2015_07_01.models.RuleCondition - :ivar action: action that is performed when the alert rule becomes active, and when an alert - condition is resolved. - :vartype action: ~azure.mgmt.monitor.v2015_07_01.models.RuleAction - :ivar actions: the array of actions that are performed when the alert rule becomes active, and - when an alert condition is resolved. - :vartype actions: list[~azure.mgmt.monitor.v2015_07_01.models.RuleAction] - :ivar last_updated_time: Last time the rule was updated in ISO8601 format. - :vartype last_updated_time: ~datetime.datetime - """ - - _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "location": {"required": True}, - "name_properties_name": {"required": True}, - "is_enabled": {"required": True}, - "condition": {"required": True}, - "last_updated_time": {"readonly": True}, - } - - _attribute_map = { - "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "location": {"key": "location", "type": "str"}, - "tags": {"key": "tags", "type": "{str}"}, - "name_properties_name": {"key": "properties.name", "type": "str"}, - "description": {"key": "properties.description", "type": "str"}, - "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, - "is_enabled": {"key": "properties.isEnabled", "type": "bool"}, - "condition": {"key": "properties.condition", "type": "RuleCondition"}, - "action": {"key": "properties.action", "type": "RuleAction"}, - "actions": {"key": "properties.actions", "type": "[RuleAction]"}, - "last_updated_time": {"key": "properties.lastUpdatedTime", "type": "iso-8601"}, - } - - def __init__( - self, - *, - location: str, - name_properties_name: str, - is_enabled: bool, - condition: "_models.RuleCondition", - tags: Optional[Dict[str, str]] = None, - description: Optional[str] = None, - provisioning_state: Optional[str] = None, - action: Optional["_models.RuleAction"] = None, - actions: Optional[List["_models.RuleAction"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword location: Resource location. Required. - :paramtype location: str - :keyword tags: Resource tags. - :paramtype tags: dict[str, str] - :keyword name_properties_name: the name of the alert rule. Required. - :paramtype name_properties_name: str - :keyword description: the description of the alert rule that will be included in the alert - email. - :paramtype description: str - :keyword provisioning_state: the provisioning state. - :paramtype provisioning_state: str - :keyword is_enabled: the flag that indicates whether the alert rule is enabled. Required. - :paramtype is_enabled: bool - :keyword condition: the condition that results in the alert rule being activated. Required. - :paramtype condition: ~azure.mgmt.monitor.v2015_07_01.models.RuleCondition - :keyword action: action that is performed when the alert rule becomes active, and when an alert - condition is resolved. - :paramtype action: ~azure.mgmt.monitor.v2015_07_01.models.RuleAction - :keyword actions: the array of actions that are performed when the alert rule becomes active, - and when an alert condition is resolved. - :paramtype actions: list[~azure.mgmt.monitor.v2015_07_01.models.RuleAction] - """ - super().__init__(location=location, tags=tags, **kwargs) - self.name_properties_name = name_properties_name - self.description = description - self.provisioning_state = provisioning_state - self.is_enabled = is_enabled - self.condition = condition - self.action = action - self.actions = actions - self.last_updated_time = None - - -class AlertRuleResourceCollection(_serialization.Model): - """Represents a collection of alert rule resources. - - :ivar value: the values for the alert rule resources. - :vartype value: list[~azure.mgmt.monitor.v2015_07_01.models.AlertRuleResource] - """ - - _attribute_map = { - "value": {"key": "value", "type": "[AlertRuleResource]"}, - } - - def __init__(self, *, value: Optional[List["_models.AlertRuleResource"]] = None, **kwargs: Any) -> None: - """ - :keyword value: the values for the alert rule resources. - :paramtype value: list[~azure.mgmt.monitor.v2015_07_01.models.AlertRuleResource] - """ - super().__init__(**kwargs) - self.value = value - - -class AlertRuleResourcePatch(_serialization.Model): - """The alert rule object for patch operations. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar tags: Resource tags. - :vartype tags: dict[str, str] - :ivar name: the name of the alert rule. - :vartype name: str - :ivar description: the description of the alert rule that will be included in the alert email. - :vartype description: str - :ivar provisioning_state: the provisioning state. - :vartype provisioning_state: str - :ivar is_enabled: the flag that indicates whether the alert rule is enabled. - :vartype is_enabled: bool - :ivar condition: the condition that results in the alert rule being activated. - :vartype condition: ~azure.mgmt.monitor.v2015_07_01.models.RuleCondition - :ivar action: action that is performed when the alert rule becomes active, and when an alert - condition is resolved. - :vartype action: ~azure.mgmt.monitor.v2015_07_01.models.RuleAction - :ivar actions: the array of actions that are performed when the alert rule becomes active, and - when an alert condition is resolved. - :vartype actions: list[~azure.mgmt.monitor.v2015_07_01.models.RuleAction] - :ivar last_updated_time: Last time the rule was updated in ISO8601 format. - :vartype last_updated_time: ~datetime.datetime - """ - - _validation = { - "last_updated_time": {"readonly": True}, - } - - _attribute_map = { - "tags": {"key": "tags", "type": "{str}"}, - "name": {"key": "properties.name", "type": "str"}, - "description": {"key": "properties.description", "type": "str"}, - "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, - "is_enabled": {"key": "properties.isEnabled", "type": "bool"}, - "condition": {"key": "properties.condition", "type": "RuleCondition"}, - "action": {"key": "properties.action", "type": "RuleAction"}, - "actions": {"key": "properties.actions", "type": "[RuleAction]"}, - "last_updated_time": {"key": "properties.lastUpdatedTime", "type": "iso-8601"}, - } - - def __init__( - self, - *, - tags: Optional[Dict[str, str]] = None, - name: Optional[str] = None, - description: Optional[str] = None, - provisioning_state: Optional[str] = None, - is_enabled: Optional[bool] = None, - condition: Optional["_models.RuleCondition"] = None, - action: Optional["_models.RuleAction"] = None, - actions: Optional[List["_models.RuleAction"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword tags: Resource tags. - :paramtype tags: dict[str, str] - :keyword name: the name of the alert rule. - :paramtype name: str - :keyword description: the description of the alert rule that will be included in the alert - email. - :paramtype description: str - :keyword provisioning_state: the provisioning state. - :paramtype provisioning_state: str - :keyword is_enabled: the flag that indicates whether the alert rule is enabled. - :paramtype is_enabled: bool - :keyword condition: the condition that results in the alert rule being activated. - :paramtype condition: ~azure.mgmt.monitor.v2015_07_01.models.RuleCondition - :keyword action: action that is performed when the alert rule becomes active, and when an alert - condition is resolved. - :paramtype action: ~azure.mgmt.monitor.v2015_07_01.models.RuleAction - :keyword actions: the array of actions that are performed when the alert rule becomes active, - and when an alert condition is resolved. - :paramtype actions: list[~azure.mgmt.monitor.v2015_07_01.models.RuleAction] - """ - super().__init__(**kwargs) - self.tags = tags - self.name = name - self.description = description - self.provisioning_state = provisioning_state - self.is_enabled = is_enabled - self.condition = condition - self.action = action - self.actions = actions - self.last_updated_time = None - - class DimensionProperties(_serialization.Model): """Type of operation: get, read, delete, etc. @@ -401,7 +130,7 @@ def __init__(self, *, code: Optional[str] = None, message: Optional[str] = None, class LocalizableString(_serialization.Model): """The localizable string class. - 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 value: the invariant value. Required. :vartype value: str @@ -430,116 +159,10 @@ def __init__(self, *, value: str, localized_value: Optional[str] = None, **kwarg self.localized_value = localized_value -class RuleCondition(_serialization.Model): - """The condition that results in the alert rule being activated. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - LocationThresholdRuleCondition, ManagementEventRuleCondition, ThresholdRuleCondition - - All required parameters must be populated in order to send to Azure. - - :ivar odata_type: specifies the type of condition. This can be one of three types: - ManagementEventRuleCondition (occurrences of management events), LocationThresholdRuleCondition - (based on the number of failures of a web test), and ThresholdRuleCondition (based on the - threshold of a metric). Required. - :vartype odata_type: str - :ivar data_source: the resource from which the rule collects its data. For this type dataSource - will always be of type RuleMetricDataSource. - :vartype data_source: ~azure.mgmt.monitor.v2015_07_01.models.RuleDataSource - """ - - _validation = { - "odata_type": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "odata\\.type", "type": "str"}, - "data_source": {"key": "dataSource", "type": "RuleDataSource"}, - } - - _subtype_map = { - "odata_type": { - "Microsoft.Azure.Management.Insights.Models.LocationThresholdRuleCondition": "LocationThresholdRuleCondition", - "Microsoft.Azure.Management.Insights.Models.ManagementEventRuleCondition": "ManagementEventRuleCondition", - "Microsoft.Azure.Management.Insights.Models.ThresholdRuleCondition": "ThresholdRuleCondition", - } - } - - def __init__(self, *, data_source: Optional["_models.RuleDataSource"] = None, **kwargs: Any) -> None: - """ - :keyword data_source: the resource from which the rule collects its data. For this type - dataSource will always be of type RuleMetricDataSource. - :paramtype data_source: ~azure.mgmt.monitor.v2015_07_01.models.RuleDataSource - """ - super().__init__(**kwargs) - self.odata_type: Optional[str] = None - self.data_source = data_source - - -class LocationThresholdRuleCondition(RuleCondition): - """A rule condition based on a certain number of locations failing. - - All required parameters must be populated in order to send to Azure. - - :ivar odata_type: specifies the type of condition. This can be one of three types: - ManagementEventRuleCondition (occurrences of management events), LocationThresholdRuleCondition - (based on the number of failures of a web test), and ThresholdRuleCondition (based on the - threshold of a metric). Required. - :vartype odata_type: str - :ivar data_source: the resource from which the rule collects its data. For this type dataSource - will always be of type RuleMetricDataSource. - :vartype data_source: ~azure.mgmt.monitor.v2015_07_01.models.RuleDataSource - :ivar window_size: the period of time (in ISO 8601 duration format) that is used to monitor - alert activity based on the threshold. If specified then it must be between 5 minutes and 1 - day. - :vartype window_size: ~datetime.timedelta - :ivar failed_location_count: the number of locations that must fail to activate the alert. - Required. - :vartype failed_location_count: int - """ - - _validation = { - "odata_type": {"required": True}, - "failed_location_count": {"required": True, "minimum": 0}, - } - - _attribute_map = { - "odata_type": {"key": "odata\\.type", "type": "str"}, - "data_source": {"key": "dataSource", "type": "RuleDataSource"}, - "window_size": {"key": "windowSize", "type": "duration"}, - "failed_location_count": {"key": "failedLocationCount", "type": "int"}, - } - - def __init__( - self, - *, - failed_location_count: int, - data_source: Optional["_models.RuleDataSource"] = None, - window_size: Optional[datetime.timedelta] = None, - **kwargs: Any - ) -> None: - """ - :keyword data_source: the resource from which the rule collects its data. For this type - dataSource will always be of type RuleMetricDataSource. - :paramtype data_source: ~azure.mgmt.monitor.v2015_07_01.models.RuleDataSource - :keyword window_size: the period of time (in ISO 8601 duration format) that is used to monitor - alert activity based on the threshold. If specified then it must be between 5 minutes and 1 - day. - :paramtype window_size: ~datetime.timedelta - :keyword failed_location_count: the number of locations that must fail to activate the alert. - Required. - :paramtype failed_location_count: int - """ - super().__init__(data_source=data_source, **kwargs) - self.odata_type: str = "Microsoft.Azure.Management.Insights.Models.LocationThresholdRuleCondition" - self.window_size = window_size - self.failed_location_count = failed_location_count - - class LogSettings(_serialization.Model): """Part of MultiTenantDiagnosticSettings. Specifies the settings for a particular log. - 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 category: Name of a Diagnostic Log category for a resource type this setting is applied to. To obtain the list of Diagnostic Log categories for a resource, first perform a GET @@ -624,103 +247,6 @@ def __init__( self.blob_duration = blob_duration -class ManagementEventAggregationCondition(_serialization.Model): - """How the data that is collected should be combined over time. - - :ivar operator: the condition operator. Known values are: "GreaterThan", "GreaterThanOrEqual", - "LessThan", and "LessThanOrEqual". - :vartype operator: str or ~azure.mgmt.monitor.v2015_07_01.models.ConditionOperator - :ivar threshold: The threshold value that activates the alert. - :vartype threshold: float - :ivar window_size: the period of time (in ISO 8601 duration format) that is used to monitor - alert activity based on the threshold. If specified then it must be between 5 minutes and 1 - day. - :vartype window_size: ~datetime.timedelta - """ - - _attribute_map = { - "operator": {"key": "operator", "type": "str"}, - "threshold": {"key": "threshold", "type": "float"}, - "window_size": {"key": "windowSize", "type": "duration"}, - } - - def __init__( - self, - *, - operator: Optional[Union[str, "_models.ConditionOperator"]] = None, - threshold: Optional[float] = None, - window_size: Optional[datetime.timedelta] = None, - **kwargs: Any - ) -> None: - """ - :keyword operator: the condition operator. Known values are: "GreaterThan", - "GreaterThanOrEqual", "LessThan", and "LessThanOrEqual". - :paramtype operator: str or ~azure.mgmt.monitor.v2015_07_01.models.ConditionOperator - :keyword threshold: The threshold value that activates the alert. - :paramtype threshold: float - :keyword window_size: the period of time (in ISO 8601 duration format) that is used to monitor - alert activity based on the threshold. If specified then it must be between 5 minutes and 1 - day. - :paramtype window_size: ~datetime.timedelta - """ - super().__init__(**kwargs) - self.operator = operator - self.threshold = threshold - self.window_size = window_size - - -class ManagementEventRuleCondition(RuleCondition): - """A management event rule condition. - - All required parameters must be populated in order to send to Azure. - - :ivar odata_type: specifies the type of condition. This can be one of three types: - ManagementEventRuleCondition (occurrences of management events), LocationThresholdRuleCondition - (based on the number of failures of a web test), and ThresholdRuleCondition (based on the - threshold of a metric). Required. - :vartype odata_type: str - :ivar data_source: the resource from which the rule collects its data. For this type dataSource - will always be of type RuleMetricDataSource. - :vartype data_source: ~azure.mgmt.monitor.v2015_07_01.models.RuleDataSource - :ivar aggregation: How the data that is collected should be combined over time and when the - alert is activated. Note that for management event alerts aggregation is optional – if it is - not provided then any event will cause the alert to activate. - :vartype aggregation: - ~azure.mgmt.monitor.v2015_07_01.models.ManagementEventAggregationCondition - """ - - _validation = { - "odata_type": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "odata\\.type", "type": "str"}, - "data_source": {"key": "dataSource", "type": "RuleDataSource"}, - "aggregation": {"key": "aggregation", "type": "ManagementEventAggregationCondition"}, - } - - def __init__( - self, - *, - data_source: Optional["_models.RuleDataSource"] = None, - aggregation: Optional["_models.ManagementEventAggregationCondition"] = None, - **kwargs: Any - ) -> None: - """ - :keyword data_source: the resource from which the rule collects its data. For this type - dataSource will always be of type RuleMetricDataSource. - :paramtype data_source: ~azure.mgmt.monitor.v2015_07_01.models.RuleDataSource - :keyword aggregation: How the data that is collected should be combined over time and when the - alert is activated. Note that for management event alerts aggregation is optional – if it is - not provided then any event will cause the alert to activate. - :paramtype aggregation: - ~azure.mgmt.monitor.v2015_07_01.models.ManagementEventAggregationCondition - """ - super().__init__(data_source=data_source, **kwargs) - self.odata_type: str = "Microsoft.Azure.Management.Insights.Models.ManagementEventRuleCondition" - self.aggregation = aggregation - - class MetricAvailability(_serialization.Model): """Metric availability specifies the time grain (aggregation interval or frequency) and the retention period for that time grain. @@ -805,7 +331,7 @@ def __init__( self.partition_key = partition_key -class MetricDefinition(_serialization.Model): # pylint: disable=too-many-instance-attributes +class MetricDefinition(_serialization.Model): """Metric definition class specifies the metadata for a metric. :ivar resource_id: The resource identifier of the resource that emitted the metric. @@ -918,7 +444,7 @@ def __init__( class MetricDefinitionCollection(_serialization.Model): """Represents collection of metric definitions. - 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 for these metric definitions. :vartype id: str @@ -956,7 +482,7 @@ def __init__( class MetricSettings(_serialization.Model): """Part of MultiTenantDiagnosticSettings. Specifies the settings for a particular metric. - 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 time_grain: the timegrain of the metric in ISO8601 format. Required. :vartype time_grain: ~datetime.timedelta @@ -999,7 +525,7 @@ def __init__( self.retention_policy = retention_policy -class MetricSpecification(_serialization.Model): # pylint: disable=too-many-instance-attributes +class MetricSpecification(_serialization.Model): """Metric specification of operation. :ivar name: The name of the metric. @@ -1009,7 +535,7 @@ class MetricSpecification(_serialization.Model): # pylint: disable=too-many-ins :ivar display_description: Display description of the metric. :vartype display_description: str :ivar unit: The metric unit. Possible values include: - Count,Bytes,Seconds,Percent,CountPerSecond,BytesPerSecond,MilliSeconds,ByteSeconds,Unspecified,BitsPerSecond,Cores,MilliCores,NanoCores. + Count,Bytes,Seconds,Percent,CountPerSecond,BytesPerSecond,MilliSeconds,ByteSeconds,Unspecified,BitsPerSecond,Cores,MilliCores,NanoCores. # pylint: disable=line-too-long :vartype unit: str :ivar aggregation_type: The default metric aggregation type. Possible values include: Total,Average,Maximum,Minimum,Count. @@ -1074,7 +600,7 @@ def __init__( :keyword display_description: Display description of the metric. :paramtype display_description: str :keyword unit: The metric unit. Possible values include: - Count,Bytes,Seconds,Percent,CountPerSecond,BytesPerSecond,MilliSeconds,ByteSeconds,Unspecified,BitsPerSecond,Cores,MilliCores,NanoCores. + Count,Bytes,Seconds,Percent,CountPerSecond,BytesPerSecond,MilliSeconds,ByteSeconds,Unspecified,BitsPerSecond,Cores,MilliCores,NanoCores. # pylint: disable=line-too-long :paramtype unit: str :keyword aggregation_type: The default metric aggregation type. Possible values include: Total,Average,Maximum,Minimum,Count. @@ -1240,10 +766,59 @@ def __init__( self.next_link = next_link +class Resource(_serialization.Model): + """An azure resource object. + + 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 id: Azure resource Id. + :vartype id: str + :ivar name: Azure resource name. + :vartype name: str + :ivar type: Azure resource type. + :vartype type: str + :ivar location: Resource location. Required. + :vartype location: str + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "location": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + } + + def __init__(self, *, location: str, tags: Optional[Dict[str, str]] = None, **kwargs: Any) -> None: + """ + :keyword location: Resource location. Required. + :paramtype location: str + :keyword tags: Resource tags. + :paramtype tags: dict[str, str] + """ + super().__init__(**kwargs) + self.id = None + self.name = None + self.type = None + self.location = location + self.tags = tags + + class RetentionPolicy(_serialization.Model): """Specifies the retention policy for the log. - 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 enabled: a value indicating whether the retention policy is enabled. Required. :vartype enabled: bool @@ -1275,427 +850,12 @@ def __init__(self, *, enabled: bool, days: int, **kwargs: Any) -> None: self.days = days -class RuleAction(_serialization.Model): - """The action that is performed when the alert rule becomes active, and when an alert condition is - resolved. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - RuleEmailAction, RuleWebhookAction - - All required parameters must be populated in order to send to Azure. - - :ivar odata_type: specifies the type of the action. There are two types of actions: - RuleEmailAction and RuleWebhookAction. Required. - :vartype odata_type: str - """ - - _validation = { - "odata_type": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "odata\\.type", "type": "str"}, - } - - _subtype_map = { - "odata_type": { - "Microsoft.Azure.Management.Insights.Models.RuleEmailAction": "RuleEmailAction", - "Microsoft.Azure.Management.Insights.Models.RuleWebhookAction": "RuleWebhookAction", - } - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - self.odata_type: Optional[str] = None - - -class RuleDataSource(_serialization.Model): - """The resource from which the rule collects its data. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - RuleManagementEventDataSource, RuleMetricDataSource - - All required parameters must be populated in order to send to Azure. - - :ivar odata_type: specifies the type of data source. There are two types of rule data sources: - RuleMetricDataSource and RuleManagementEventDataSource. Required. - :vartype odata_type: str - :ivar resource_uri: the resource identifier of the resource the rule monitors. **NOTE**\ : this - property cannot be updated for an existing rule. - :vartype resource_uri: str - :ivar legacy_resource_id: the legacy resource identifier of the resource the rule monitors. - **NOTE**\ : this property cannot be updated for an existing rule. - :vartype legacy_resource_id: str - :ivar resource_location: the location of the resource. - :vartype resource_location: str - :ivar metric_namespace: the namespace of the metric. - :vartype metric_namespace: str - """ - - _validation = { - "odata_type": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "odata\\.type", "type": "str"}, - "resource_uri": {"key": "resourceUri", "type": "str"}, - "legacy_resource_id": {"key": "legacyResourceId", "type": "str"}, - "resource_location": {"key": "resourceLocation", "type": "str"}, - "metric_namespace": {"key": "metricNamespace", "type": "str"}, - } - - _subtype_map = { - "odata_type": { - "Microsoft.Azure.Management.Insights.Models.RuleManagementEventDataSource": "RuleManagementEventDataSource", - "Microsoft.Azure.Management.Insights.Models.RuleMetricDataSource": "RuleMetricDataSource", - } - } - - def __init__( - self, - *, - resource_uri: Optional[str] = None, - legacy_resource_id: Optional[str] = None, - resource_location: Optional[str] = None, - metric_namespace: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword resource_uri: the resource identifier of the resource the rule monitors. **NOTE**\ : - this property cannot be updated for an existing rule. - :paramtype resource_uri: str - :keyword legacy_resource_id: the legacy resource identifier of the resource the rule monitors. - **NOTE**\ : this property cannot be updated for an existing rule. - :paramtype legacy_resource_id: str - :keyword resource_location: the location of the resource. - :paramtype resource_location: str - :keyword metric_namespace: the namespace of the metric. - :paramtype metric_namespace: str - """ - super().__init__(**kwargs) - self.odata_type: Optional[str] = None - self.resource_uri = resource_uri - self.legacy_resource_id = legacy_resource_id - self.resource_location = resource_location - self.metric_namespace = metric_namespace - - -class RuleEmailAction(RuleAction): - """Specifies the action to send email when the rule condition is evaluated. The discriminator is - always RuleEmailAction in this case. - - All required parameters must be populated in order to send to Azure. - - :ivar odata_type: specifies the type of the action. There are two types of actions: - RuleEmailAction and RuleWebhookAction. Required. - :vartype odata_type: str - :ivar send_to_service_owners: Whether the administrators (service and co-administrators) of the - service should be notified when the alert is activated. - :vartype send_to_service_owners: bool - :ivar custom_emails: the list of administrator's custom email addresses to notify of the - activation of the alert. - :vartype custom_emails: list[str] - """ - - _validation = { - "odata_type": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "odata\\.type", "type": "str"}, - "send_to_service_owners": {"key": "sendToServiceOwners", "type": "bool"}, - "custom_emails": {"key": "customEmails", "type": "[str]"}, - } - - def __init__( - self, *, send_to_service_owners: Optional[bool] = None, custom_emails: Optional[List[str]] = None, **kwargs: Any - ) -> None: - """ - :keyword send_to_service_owners: Whether the administrators (service and co-administrators) of - the service should be notified when the alert is activated. - :paramtype send_to_service_owners: bool - :keyword custom_emails: the list of administrator's custom email addresses to notify of the - activation of the alert. - :paramtype custom_emails: list[str] - """ - super().__init__(**kwargs) - self.odata_type: str = "Microsoft.Azure.Management.Insights.Models.RuleEmailAction" - self.send_to_service_owners = send_to_service_owners - self.custom_emails = custom_emails - - -class RuleManagementEventClaimsDataSource(_serialization.Model): - """The claims for a rule management event data source. - - :ivar email_address: the email address. - :vartype email_address: str - """ - - _attribute_map = { - "email_address": {"key": "emailAddress", "type": "str"}, - } - - def __init__(self, *, email_address: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword email_address: the email address. - :paramtype email_address: str - """ - super().__init__(**kwargs) - self.email_address = email_address - - -class RuleManagementEventDataSource(RuleDataSource): # pylint: disable=too-many-instance-attributes - """A rule management event data source. The discriminator fields is always - RuleManagementEventDataSource in this case. - - All required parameters must be populated in order to send to Azure. - - :ivar odata_type: specifies the type of data source. There are two types of rule data sources: - RuleMetricDataSource and RuleManagementEventDataSource. Required. - :vartype odata_type: str - :ivar resource_uri: the resource identifier of the resource the rule monitors. **NOTE**\ : this - property cannot be updated for an existing rule. - :vartype resource_uri: str - :ivar legacy_resource_id: the legacy resource identifier of the resource the rule monitors. - **NOTE**\ : this property cannot be updated for an existing rule. - :vartype legacy_resource_id: str - :ivar resource_location: the location of the resource. - :vartype resource_location: str - :ivar metric_namespace: the namespace of the metric. - :vartype metric_namespace: str - :ivar event_name: the event name. - :vartype event_name: str - :ivar event_source: the event source. - :vartype event_source: str - :ivar level: the level. - :vartype level: str - :ivar operation_name: The name of the operation that should be checked for. If no name is - provided, any operation will match. - :vartype operation_name: str - :ivar resource_group_name: the resource group name. - :vartype resource_group_name: str - :ivar resource_provider_name: the resource provider name. - :vartype resource_provider_name: str - :ivar status: The status of the operation that should be checked for. If no status is provided, - any status will match. - :vartype status: str - :ivar sub_status: the substatus. - :vartype sub_status: str - :ivar claims: the claims. - :vartype claims: ~azure.mgmt.monitor.v2015_07_01.models.RuleManagementEventClaimsDataSource - """ - - _validation = { - "odata_type": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "odata\\.type", "type": "str"}, - "resource_uri": {"key": "resourceUri", "type": "str"}, - "legacy_resource_id": {"key": "legacyResourceId", "type": "str"}, - "resource_location": {"key": "resourceLocation", "type": "str"}, - "metric_namespace": {"key": "metricNamespace", "type": "str"}, - "event_name": {"key": "eventName", "type": "str"}, - "event_source": {"key": "eventSource", "type": "str"}, - "level": {"key": "level", "type": "str"}, - "operation_name": {"key": "operationName", "type": "str"}, - "resource_group_name": {"key": "resourceGroupName", "type": "str"}, - "resource_provider_name": {"key": "resourceProviderName", "type": "str"}, - "status": {"key": "status", "type": "str"}, - "sub_status": {"key": "subStatus", "type": "str"}, - "claims": {"key": "claims", "type": "RuleManagementEventClaimsDataSource"}, - } - - def __init__( - self, - *, - resource_uri: Optional[str] = None, - legacy_resource_id: Optional[str] = None, - resource_location: Optional[str] = None, - metric_namespace: Optional[str] = None, - event_name: Optional[str] = None, - event_source: Optional[str] = None, - level: Optional[str] = None, - operation_name: Optional[str] = None, - resource_group_name: Optional[str] = None, - resource_provider_name: Optional[str] = None, - status: Optional[str] = None, - sub_status: Optional[str] = None, - claims: Optional["_models.RuleManagementEventClaimsDataSource"] = None, - **kwargs: Any - ) -> None: - """ - :keyword resource_uri: the resource identifier of the resource the rule monitors. **NOTE**\ : - this property cannot be updated for an existing rule. - :paramtype resource_uri: str - :keyword legacy_resource_id: the legacy resource identifier of the resource the rule monitors. - **NOTE**\ : this property cannot be updated for an existing rule. - :paramtype legacy_resource_id: str - :keyword resource_location: the location of the resource. - :paramtype resource_location: str - :keyword metric_namespace: the namespace of the metric. - :paramtype metric_namespace: str - :keyword event_name: the event name. - :paramtype event_name: str - :keyword event_source: the event source. - :paramtype event_source: str - :keyword level: the level. - :paramtype level: str - :keyword operation_name: The name of the operation that should be checked for. If no name is - provided, any operation will match. - :paramtype operation_name: str - :keyword resource_group_name: the resource group name. - :paramtype resource_group_name: str - :keyword resource_provider_name: the resource provider name. - :paramtype resource_provider_name: str - :keyword status: The status of the operation that should be checked for. If no status is - provided, any status will match. - :paramtype status: str - :keyword sub_status: the substatus. - :paramtype sub_status: str - :keyword claims: the claims. - :paramtype claims: ~azure.mgmt.monitor.v2015_07_01.models.RuleManagementEventClaimsDataSource - """ - super().__init__( - resource_uri=resource_uri, - legacy_resource_id=legacy_resource_id, - resource_location=resource_location, - metric_namespace=metric_namespace, - **kwargs - ) - self.odata_type: str = "Microsoft.Azure.Management.Insights.Models.RuleManagementEventDataSource" - self.event_name = event_name - self.event_source = event_source - self.level = level - self.operation_name = operation_name - self.resource_group_name = resource_group_name - self.resource_provider_name = resource_provider_name - self.status = status - self.sub_status = sub_status - self.claims = claims - - -class RuleMetricDataSource(RuleDataSource): - """A rule metric data source. The discriminator value is always RuleMetricDataSource in this case. - - All required parameters must be populated in order to send to Azure. - - :ivar odata_type: specifies the type of data source. There are two types of rule data sources: - RuleMetricDataSource and RuleManagementEventDataSource. Required. - :vartype odata_type: str - :ivar resource_uri: the resource identifier of the resource the rule monitors. **NOTE**\ : this - property cannot be updated for an existing rule. - :vartype resource_uri: str - :ivar legacy_resource_id: the legacy resource identifier of the resource the rule monitors. - **NOTE**\ : this property cannot be updated for an existing rule. - :vartype legacy_resource_id: str - :ivar resource_location: the location of the resource. - :vartype resource_location: str - :ivar metric_namespace: the namespace of the metric. - :vartype metric_namespace: str - :ivar metric_name: the name of the metric that defines what the rule monitors. - :vartype metric_name: str - """ - - _validation = { - "odata_type": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "odata\\.type", "type": "str"}, - "resource_uri": {"key": "resourceUri", "type": "str"}, - "legacy_resource_id": {"key": "legacyResourceId", "type": "str"}, - "resource_location": {"key": "resourceLocation", "type": "str"}, - "metric_namespace": {"key": "metricNamespace", "type": "str"}, - "metric_name": {"key": "metricName", "type": "str"}, - } - - def __init__( - self, - *, - resource_uri: Optional[str] = None, - legacy_resource_id: Optional[str] = None, - resource_location: Optional[str] = None, - metric_namespace: Optional[str] = None, - metric_name: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword resource_uri: the resource identifier of the resource the rule monitors. **NOTE**\ : - this property cannot be updated for an existing rule. - :paramtype resource_uri: str - :keyword legacy_resource_id: the legacy resource identifier of the resource the rule monitors. - **NOTE**\ : this property cannot be updated for an existing rule. - :paramtype legacy_resource_id: str - :keyword resource_location: the location of the resource. - :paramtype resource_location: str - :keyword metric_namespace: the namespace of the metric. - :paramtype metric_namespace: str - :keyword metric_name: the name of the metric that defines what the rule monitors. - :paramtype metric_name: str - """ - super().__init__( - resource_uri=resource_uri, - legacy_resource_id=legacy_resource_id, - resource_location=resource_location, - metric_namespace=metric_namespace, - **kwargs - ) - self.odata_type: str = "Microsoft.Azure.Management.Insights.Models.RuleMetricDataSource" - self.metric_name = metric_name - - -class RuleWebhookAction(RuleAction): - """Specifies the action to post to service when the rule condition is evaluated. The discriminator - is always RuleWebhookAction in this case. - - All required parameters must be populated in order to send to Azure. - - :ivar odata_type: specifies the type of the action. There are two types of actions: - RuleEmailAction and RuleWebhookAction. Required. - :vartype odata_type: str - :ivar service_uri: the service uri to Post the notification when the alert activates or - resolves. - :vartype service_uri: str - :ivar properties: the dictionary of custom properties to include with the post operation. These - data are appended to the webhook payload. - :vartype properties: dict[str, str] - """ - - _validation = { - "odata_type": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "odata\\.type", "type": "str"}, - "service_uri": {"key": "serviceUri", "type": "str"}, - "properties": {"key": "properties", "type": "{str}"}, - } - - def __init__( - self, *, service_uri: Optional[str] = None, properties: Optional[Dict[str, str]] = None, **kwargs: Any - ) -> None: - """ - :keyword service_uri: the service uri to Post the notification when the alert activates or - resolves. - :paramtype service_uri: str - :keyword properties: the dictionary of custom properties to include with the post operation. - These data are appended to the webhook payload. - :paramtype properties: dict[str, str] - """ - super().__init__(**kwargs) - self.odata_type: str = "Microsoft.Azure.Management.Insights.Models.RuleWebhookAction" - self.service_uri = service_uri - self.properties = properties - - class ServiceDiagnosticSettingsResource(Resource): """Description of a service diagnostic setting. 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: Azure resource Id. :vartype id: str @@ -1720,7 +880,7 @@ class ServiceDiagnosticSettingsResource(Resource): :vartype logs: list[~azure.mgmt.monitor.v2015_07_01.models.LogSettings] :ivar workspace_id: The workspace ID (resource ID of a Log Analytics workspace) for a Log Analytics workspace to which you would like to send Diagnostic Logs. Example: - /subscriptions/4b9e8510-67ab-4e9a-95a9-e2f1e570ea9c/resourceGroups/insights-integration/providers/Microsoft.OperationalInsights/workspaces/viruela2. + /subscriptions/4b9e8510-67ab-4e9a-95a9-e2f1e570ea9c/resourceGroups/insights-integration/providers/Microsoft.OperationalInsights/workspaces/viruela2. # pylint: disable=line-too-long :vartype workspace_id: str """ @@ -1774,7 +934,7 @@ def __init__( :paramtype logs: list[~azure.mgmt.monitor.v2015_07_01.models.LogSettings] :keyword workspace_id: The workspace ID (resource ID of a Log Analytics workspace) for a Log Analytics workspace to which you would like to send Diagnostic Logs. Example: - /subscriptions/4b9e8510-67ab-4e9a-95a9-e2f1e570ea9c/resourceGroups/insights-integration/providers/Microsoft.OperationalInsights/workspaces/viruela2. + /subscriptions/4b9e8510-67ab-4e9a-95a9-e2f1e570ea9c/resourceGroups/insights-integration/providers/Microsoft.OperationalInsights/workspaces/viruela2. # pylint: disable=line-too-long :paramtype workspace_id: str """ super().__init__(location=location, tags=tags, **kwargs) @@ -1879,84 +1039,3 @@ def __init__( self.end_time = end_time self.sas_token = sas_token self.sas_token_expiration_time = sas_token_expiration_time - - -class ThresholdRuleCondition(RuleCondition): - """A rule condition based on a metric crossing a threshold. - - All required parameters must be populated in order to send to Azure. - - :ivar odata_type: specifies the type of condition. This can be one of three types: - ManagementEventRuleCondition (occurrences of management events), LocationThresholdRuleCondition - (based on the number of failures of a web test), and ThresholdRuleCondition (based on the - threshold of a metric). Required. - :vartype odata_type: str - :ivar data_source: the resource from which the rule collects its data. For this type dataSource - will always be of type RuleMetricDataSource. - :vartype data_source: ~azure.mgmt.monitor.v2015_07_01.models.RuleDataSource - :ivar operator: the operator used to compare the data and the threshold. Required. Known values - are: "GreaterThan", "GreaterThanOrEqual", "LessThan", and "LessThanOrEqual". - :vartype operator: str or ~azure.mgmt.monitor.v2015_07_01.models.ConditionOperator - :ivar threshold: the threshold value that activates the alert. Required. - :vartype threshold: float - :ivar window_size: the period of time (in ISO 8601 duration format) that is used to monitor - alert activity based on the threshold. If specified then it must be between 5 minutes and 1 - day. - :vartype window_size: ~datetime.timedelta - :ivar time_aggregation: the time aggregation operator. How the data that are collected should - be combined over time. The default value is the PrimaryAggregationType of the Metric. Known - values are: "Average", "Minimum", "Maximum", "Total", and "Last". - :vartype time_aggregation: str or - ~azure.mgmt.monitor.v2015_07_01.models.TimeAggregationOperator - """ - - _validation = { - "odata_type": {"required": True}, - "operator": {"required": True}, - "threshold": {"required": True}, - } - - _attribute_map = { - "odata_type": {"key": "odata\\.type", "type": "str"}, - "data_source": {"key": "dataSource", "type": "RuleDataSource"}, - "operator": {"key": "operator", "type": "str"}, - "threshold": {"key": "threshold", "type": "float"}, - "window_size": {"key": "windowSize", "type": "duration"}, - "time_aggregation": {"key": "timeAggregation", "type": "str"}, - } - - def __init__( - self, - *, - operator: Union[str, "_models.ConditionOperator"], - threshold: float, - data_source: Optional["_models.RuleDataSource"] = None, - window_size: Optional[datetime.timedelta] = None, - time_aggregation: Optional[Union[str, "_models.TimeAggregationOperator"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword data_source: the resource from which the rule collects its data. For this type - dataSource will always be of type RuleMetricDataSource. - :paramtype data_source: ~azure.mgmt.monitor.v2015_07_01.models.RuleDataSource - :keyword operator: the operator used to compare the data and the threshold. Required. Known - values are: "GreaterThan", "GreaterThanOrEqual", "LessThan", and "LessThanOrEqual". - :paramtype operator: str or ~azure.mgmt.monitor.v2015_07_01.models.ConditionOperator - :keyword threshold: the threshold value that activates the alert. Required. - :paramtype threshold: float - :keyword window_size: the period of time (in ISO 8601 duration format) that is used to monitor - alert activity based on the threshold. If specified then it must be between 5 minutes and 1 - day. - :paramtype window_size: ~datetime.timedelta - :keyword time_aggregation: the time aggregation operator. How the data that are collected - should be combined over time. The default value is the PrimaryAggregationType of the Metric. - Known values are: "Average", "Minimum", "Maximum", "Total", and "Last". - :paramtype time_aggregation: str or - ~azure.mgmt.monitor.v2015_07_01.models.TimeAggregationOperator - """ - super().__init__(data_source=data_source, **kwargs) - self.odata_type: str = "Microsoft.Azure.Management.Insights.Models.ThresholdRuleCondition" - self.operator = operator - self.threshold = threshold - self.window_size = window_size - self.time_aggregation = time_aggregation diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/models/_monitor_management_client_enums.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/models/_monitor_management_client_enums.py index 060b21d2666a..c660f951e33c 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/models/_monitor_management_client_enums.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/models/_monitor_management_client_enums.py @@ -21,25 +21,6 @@ class AggregationType(str, Enum, metaclass=CaseInsensitiveEnumMeta): TOTAL = "Total" -class ConditionOperator(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Operators allowed in the rule condition.""" - - GREATER_THAN = "GreaterThan" - GREATER_THAN_OR_EQUAL = "GreaterThanOrEqual" - LESS_THAN = "LessThan" - LESS_THAN_OR_EQUAL = "LessThanOrEqual" - - -class TimeAggregationOperator(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Aggregation operators allowed in a rule.""" - - AVERAGE = "Average" - MINIMUM = "Minimum" - MAXIMUM = "Maximum" - TOTAL = "Total" - LAST = "Last" - - class Unit(str, Enum, metaclass=CaseInsensitiveEnumMeta): """the unit of the metric.""" diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/operations/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/operations/__init__.py index acff6da37ac2..091f67164165 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/operations/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/operations/__init__.py @@ -5,21 +5,25 @@ # 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 ._service_diagnostic_settings_operations import ServiceDiagnosticSettingsOperations -from ._metric_definitions_operations import MetricDefinitionsOperations -from ._alert_rules_operations import AlertRulesOperations -from ._operations import Operations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._service_diagnostic_settings_operations import ServiceDiagnosticSettingsOperations # type: ignore +from ._metric_definitions_operations import MetricDefinitionsOperations # type: ignore +from ._operations import Operations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ "ServiceDiagnosticSettingsOperations", "MetricDefinitionsOperations", - "AlertRulesOperations", "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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/operations/_metric_definitions_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/operations/_metric_definitions_operations.py index 9e32aa773b3a..87ac7f46a67f 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/operations/_metric_definitions_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/operations/_metric_definitions_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,7 +5,9 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +import urllib.parse from azure.core.exceptions import ( ClientAuthenticationError, @@ -18,16 +19,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, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -48,7 +51,7 @@ def build_list_request(resource_uri: str, *, filter: Optional[str] = None, **kwa "resourceUri": _SERIALIZER.url("resource_uri", resource_uri, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -79,6 +82,7 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list( @@ -90,12 +94,11 @@ def list( :type resource_uri: str :param filter: Reduces the set of data collected by retrieving particular metric definitions from all the definitions available for the resource.:code:`
`For example, to get just the - definition for the 'CPU percentage' counter: $filter=name.value eq '\Processor(_Total)\% + definition for the 'CPU percentage' counter: $filter=name.value eq '\\Processor(_Total)\\% Processor Time'.:code:`
`Multiple metrics can be retrieved by joining together *'name eq - :code:``'* clauses separated by *or* logical operators.:code:`
`\ **NOTE**\ : No + :code:``'* clauses separated by *or* logical operators.:code:`
`\\ **NOTE**\\ : No other syntax is allowed. Default value is None. :type filter: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either MetricDefinition or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.monitor.v2015_07_01.models.MetricDefinition] :raises ~azure.core.exceptions.HttpResponseError: @@ -103,10 +106,10 @@ def list( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2015-07-01")) cls: ClsType[_models.MetricDefinitionCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -117,23 +120,31 @@ def list( def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( resource_uri=resource_uri, filter=filter, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: - request = HttpRequest("GET", next_link) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + # 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._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("MetricDefinitionCollection", pipeline_response) @@ -143,11 +154,11 @@ def extract_data(pipeline_response): return None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -159,5 +170,3 @@ def get_next(next_link=None): return pipeline_response return ItemPaged(get_next, extract_data) - - list.metadata = {"url": "/{resourceUri}/providers/Microsoft.Insights/metricDefinitions"} diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/operations/_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/operations/_operations.py index 37efc4af1b1f..0222d6744975 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/operations/_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/operations/_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,7 @@ # 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 ( @@ -17,16 +17,18 @@ map_error, ) 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 +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -71,17 +73,17 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list(self, **kwargs: Any) -> _models.OperationListResult: """Lists all of the available operations from Microsoft.Insights provider. - :keyword callable cls: A custom type or function that will be passed the direct response :return: OperationListResult or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2015_07_01.models.OperationListResult :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -92,21 +94,19 @@ def list(self, **kwargs: Any) -> _models.OperationListResult: _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2015-07-01")) cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) - 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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -116,11 +116,9 @@ def list(self, **kwargs: Any) -> _models.OperationListResult: error = self._deserialize.failsafe_deserialize(_models.ErrorContract, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("OperationListResult", pipeline_response) + deserialized = self._deserialize("OperationListResult", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - list.metadata = {"url": "/providers/Microsoft.Insights/operations"} + return deserialized # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/operations/_service_diagnostic_settings_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/operations/_service_diagnostic_settings_operations.py index f6e2ac932398..b55268f3ae60 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/operations/_service_diagnostic_settings_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_07_01/operations/_service_diagnostic_settings_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload from azure.core.exceptions import ( @@ -17,16 +18,18 @@ map_error, ) 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 +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -47,7 +50,7 @@ def build_get_request(resource_uri: str, **kwargs: Any) -> HttpRequest: "resourceUri": _SERIALIZER.url("resource_uri", resource_uri, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -72,7 +75,7 @@ def build_create_or_update_request(resource_uri: str, **kwargs: Any) -> HttpRequ "resourceUri": _SERIALIZER.url("resource_uri", resource_uri, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -103,6 +106,7 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def get(self, resource_uri: str, **kwargs: Any) -> _models.ServiceDiagnosticSettingsResource: @@ -110,12 +114,11 @@ def get(self, resource_uri: str, **kwargs: Any) -> _models.ServiceDiagnosticSett :param resource_uri: The identifier of the resource. Required. :type resource_uri: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ServiceDiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2015_07_01.models.ServiceDiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -126,22 +129,20 @@ def get(self, resource_uri: str, **kwargs: Any) -> _models.ServiceDiagnosticSett _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2015-07-01")) cls: ClsType[_models.ServiceDiagnosticSettingsResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_uri=resource_uri, api_version=api_version, - template_url=self.get.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -151,14 +152,12 @@ def get(self, resource_uri: str, **kwargs: Any) -> _models.ServiceDiagnosticSett error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ServiceDiagnosticSettingsResource", pipeline_response) + deserialized = self._deserialize("ServiceDiagnosticSettingsResource", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - get.metadata = {"url": "/{resourceUri}/providers/microsoft.insights/diagnosticSettings/service"} + return deserialized # type: ignore @overload def create_or_update( @@ -178,7 +177,6 @@ def create_or_update( :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: ServiceDiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2015_07_01.models.ServiceDiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: @@ -186,18 +184,17 @@ def create_or_update( @overload def create_or_update( - self, resource_uri: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + self, resource_uri: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any ) -> _models.ServiceDiagnosticSettingsResource: """Create or update new diagnostic settings for the specified resource. :param resource_uri: The identifier of the resource. Required. :type resource_uri: str :param parameters: Parameters supplied to the operation. Required. - :type parameters: IO + :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: ServiceDiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2015_07_01.models.ServiceDiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: @@ -205,25 +202,21 @@ def create_or_update( @distributed_trace def create_or_update( - self, resource_uri: str, parameters: Union[_models.ServiceDiagnosticSettingsResource, IO], **kwargs: Any + self, resource_uri: str, parameters: Union[_models.ServiceDiagnosticSettingsResource, IO[bytes]], **kwargs: Any ) -> _models.ServiceDiagnosticSettingsResource: """Create or update new diagnostic settings for the specified resource. :param resource_uri: The identifier of the resource. Required. :type resource_uri: str :param parameters: Parameters supplied to the operation. Is either a - ServiceDiagnosticSettingsResource type or a IO type. Required. + ServiceDiagnosticSettingsResource type or a IO[bytes] type. Required. :type parameters: ~azure.mgmt.monitor.v2015_07_01.models.ServiceDiagnosticSettingsResource 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 + IO[bytes] :return: ServiceDiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2015_07_01.models.ServiceDiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -234,34 +227,32 @@ def create_or_update( _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", "2015-07-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2015-07-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ServiceDiagnosticSettingsResource] = 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, "ServiceDiagnosticSettingsResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_uri=resource_uri, 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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -270,11 +261,9 @@ def create_or_update( map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize("ServiceDiagnosticSettingsResource", pipeline_response) + deserialized = self._deserialize("ServiceDiagnosticSettingsResource", 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": "/{resourceUri}/providers/microsoft.insights/diagnosticSettings/service"} + return deserialized # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/__init__.py index 2c7733bfd566..42cc62301757 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/__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 ._monitor_management_client import MonitorManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._monitor_management_client import MonitorManagementClient # type: ignore from ._version import VERSION __version__ = VERSION try: from ._patch import __all__ as _patch_all - from ._patch import * # 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__ = [ "MonitorManagementClient", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/_configuration.py index 45c019a2dd03..a285edcb271a 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/_configuration.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/_configuration.py @@ -8,18 +8,16 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy from ._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MonitorManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class MonitorManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for MonitorManagementClient. Note that all parameters used to create this instance are saved as instance @@ -35,7 +33,6 @@ class MonitorManagementClientConfiguration(Configuration): # pylint: disable=to """ def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: - super(MonitorManagementClientConfiguration, self).__init__(**kwargs) api_version: str = kwargs.pop("api_version", "2016-03-01") if credential is None: @@ -48,6 +45,7 @@ def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-monitor/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -56,9 +54,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.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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/_metadata.json b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/_metadata.json index 4a901aa6bb4a..c9a89ca65667 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/_metadata.json +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/_metadata.json @@ -8,10 +8,10 @@ "host_value": "\"https://management.azure.com\"", "parameterized_host_template": null, "azure_arm": true, - "has_lro_operations": false, + "has_public_lro_operations": false, "client_side_validation": false, - "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"sdkcore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMAutoResourceProviderRegistrationPolicy\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}, \"stdlib\": {\"typing_extensions\": [\"Self\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"sdkcore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"AsyncARMAutoResourceProviderRegistrationPolicy\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}, \"stdlib\": {\"typing_extensions\": [\"Self\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "global_parameters": { "sync": { @@ -101,8 +101,8 @@ "credential_scopes": ["https://management.azure.com/.default"], "credential_call_sync": "ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", "credential_call_async": "AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", - "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "sync_imports": "{\"regular\": {\"sdkcore\": {\"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"regular\": {\"sdkcore\": {\"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "operation_groups": { "alert_rule_incidents": "AlertRuleIncidentsOperations", diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/_monitor_management_client.py index 7102648640c1..ce330eb92738 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/_monitor_management_client.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/_monitor_management_client.py @@ -8,9 +8,12 @@ from copy import deepcopy from typing import Any, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient +from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy from . import models as _models from .._serialization import Deserializer, Serializer @@ -23,11 +26,10 @@ ) if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MonitorManagementClient: # pylint: disable=client-accepts-api-version-keyword +class MonitorManagementClient: """Monitor Management Client. :ivar alert_rule_incidents: AlertRuleIncidentsOperations operations @@ -61,22 +63,44 @@ def __init__( self._config = MonitorManagementClientConfiguration( credential=credential, subscription_id=subscription_id, **kwargs ) - self._client: ARMPipelineClient = ARMPipelineClient(base_url=base_url, config=self._config, **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), + 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=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.alert_rule_incidents = AlertRuleIncidentsOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2016-03-01" + ) + self.alert_rules = AlertRulesOperations( + self._client, self._config, self._serialize, self._deserialize, "2016-03-01" + ) + self.log_profiles = LogProfilesOperations( + self._client, self._config, self._serialize, self._deserialize, "2016-03-01" ) - self.alert_rules = AlertRulesOperations(self._client, self._config, self._serialize, self._deserialize) - self.log_profiles = LogProfilesOperations(self._client, self._config, self._serialize, self._deserialize) self.metric_definitions = MetricDefinitionsOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2016-03-01" ) - 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 @@ -96,12 +120,12 @@ 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) -> None: self._client.close() - def __enter__(self) -> "MonitorManagementClient": + def __enter__(self) -> Self: self._client.__enter__() return self diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/_vendor.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/_vendor.py deleted file mode 100644 index bd0df84f5319..000000000000 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/_vendor.py +++ /dev/null @@ -1,30 +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 typing import List, cast - -from azure.core.pipeline.transport import HttpRequest - - -def _convert_request(request, files=None): - data = request.content if not files else None - request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) - if files: - request.set_formdata_body(files) - return request - - -def _format_url_section(template, **kwargs): - components = template.split("/") - while components: - try: - return template.format(**kwargs) - except KeyError as key: - # Need the cast, as for some reasons "split" is typed as list[str | Any] - formatted_components = cast(List[str], template.split("/")) - components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] - template = "/".join(components) diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/_version.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/_version.py index 394ee7c0c03c..e5754a47ce68 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/_version.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "6.0.2" +VERSION = "1.0.0b1" diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/aio/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/aio/__init__.py index 2c151bb41c19..3df30ff42149 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/aio/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/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 ._monitor_management_client import MonitorManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._monitor_management_client import MonitorManagementClient # type: ignore try: from ._patch import __all__ as _patch_all - from ._patch import * # 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__ = [ "MonitorManagementClient", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/aio/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/aio/_configuration.py index b092b2cb7239..3257a0c4cc02 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/aio/_configuration.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/aio/_configuration.py @@ -8,18 +8,16 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy from .._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MonitorManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class MonitorManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for MonitorManagementClient. Note that all parameters used to create this instance are saved as instance @@ -35,7 +33,6 @@ class MonitorManagementClientConfiguration(Configuration): # pylint: disable=to """ def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: - super(MonitorManagementClientConfiguration, self).__init__(**kwargs) api_version: str = kwargs.pop("api_version", "2016-03-01") if credential is None: @@ -48,6 +45,7 @@ def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **k self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-monitor/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -56,9 +54,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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/aio/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/aio/_monitor_management_client.py index dcb044338740..0c1714d6c5d0 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/aio/_monitor_management_client.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/aio/_monitor_management_client.py @@ -8,9 +8,12 @@ from copy import deepcopy from typing import Any, Awaitable, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient +from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy from .. import models as _models from ..._serialization import Deserializer, Serializer @@ -23,11 +26,10 @@ ) if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MonitorManagementClient: # pylint: disable=client-accepts-api-version-keyword +class MonitorManagementClient: """Monitor Management Client. :ivar alert_rule_incidents: AlertRuleIncidentsOperations operations @@ -61,22 +63,46 @@ def __init__( self._config = MonitorManagementClientConfiguration( credential=credential, subscription_id=subscription_id, **kwargs ) - self._client: AsyncARMPipelineClient = AsyncARMPipelineClient(base_url=base_url, config=self._config, **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=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.alert_rule_incidents = AlertRuleIncidentsOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2016-03-01" + ) + self.alert_rules = AlertRulesOperations( + self._client, self._config, self._serialize, self._deserialize, "2016-03-01" + ) + self.log_profiles = LogProfilesOperations( + self._client, self._config, self._serialize, self._deserialize, "2016-03-01" ) - self.alert_rules = AlertRulesOperations(self._client, self._config, self._serialize, self._deserialize) - self.log_profiles = LogProfilesOperations(self._client, self._config, self._serialize, self._deserialize) self.metric_definitions = MetricDefinitionsOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2016-03-01" ) - 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 @@ -96,12 +122,12 @@ 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) -> "MonitorManagementClient": + async def __aenter__(self) -> Self: await self._client.__aenter__() return self diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/aio/operations/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/aio/operations/__init__.py index 185356695cfa..8c7e395a7953 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/aio/operations/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/aio/operations/__init__.py @@ -5,14 +5,20 @@ # 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 ._alert_rule_incidents_operations import AlertRuleIncidentsOperations -from ._alert_rules_operations import AlertRulesOperations -from ._log_profiles_operations import LogProfilesOperations -from ._metric_definitions_operations import MetricDefinitionsOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._alert_rule_incidents_operations import AlertRuleIncidentsOperations # type: ignore +from ._alert_rules_operations import AlertRulesOperations # type: ignore +from ._log_profiles_operations import LogProfilesOperations # type: ignore +from ._metric_definitions_operations import MetricDefinitionsOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ @@ -21,5 +27,5 @@ "LogProfilesOperations", "MetricDefinitionsOperations", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/aio/operations/_alert_rule_incidents_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/aio/operations/_alert_rule_incidents_operations.py index 88163d63ffd3..7fe2f4817749 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/aio/operations/_alert_rule_incidents_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/aio/operations/_alert_rule_incidents_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,7 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar import urllib.parse @@ -19,17 +19,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.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._alert_rule_incidents_operations import build_get_request, build_list_by_alert_rule_request +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -52,6 +54,7 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace_async async def get( @@ -66,12 +69,11 @@ async def get( :type rule_name: str :param incident_name: The name of the incident to retrieve. Required. :type incident_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: Incident or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2016_03_01.models.Incident :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -82,25 +84,23 @@ async def get( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2016-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2016-03-01")) cls: ClsType[_models.Incident] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, rule_name=rule_name, incident_name=incident_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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -110,16 +110,12 @@ async def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("Incident", pipeline_response) + deserialized = self._deserialize("Incident", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - get.metadata = { - "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/microsoft.insights/alertrules/{ruleName}/incidents/{incidentName}" - } + return deserialized # type: ignore @distributed_trace def list_by_alert_rule( @@ -132,7 +128,6 @@ def list_by_alert_rule( :type resource_group_name: str :param rule_name: The name of the rule. Required. :type rule_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Incident or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.monitor.v2016_03_01.models.Incident] @@ -141,10 +136,10 @@ def list_by_alert_rule( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2016-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2016-03-01")) cls: ClsType[_models.IncidentListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -155,17 +150,15 @@ def list_by_alert_rule( def prepare_request(next_link=None): if not next_link: - request = build_list_by_alert_rule_request( + _request = build_list_by_alert_rule_request( resource_group_name=resource_group_name, rule_name=rule_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_alert_rule.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -176,14 +169,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("IncidentListResult", pipeline_response) @@ -193,11 +185,11 @@ async def extract_data(pipeline_response): return None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -208,7 +200,3 @@ async def get_next(next_link=None): return pipeline_response return AsyncItemPaged(get_next, extract_data) - - list_by_alert_rule.metadata = { - "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/microsoft.insights/alertrules/{ruleName}/incidents" - } diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/aio/operations/_alert_rules_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/aio/operations/_alert_rules_operations.py index 7b923b3df73b..823d2301b506 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/aio/operations/_alert_rules_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/aio/operations/_alert_rules_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload import urllib.parse @@ -19,15 +20,13 @@ 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 ...operations._alert_rules_operations import ( build_create_or_update_request, build_delete_request, @@ -37,6 +36,10 @@ build_update_request, ) +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -59,6 +62,7 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @overload async def create_or_update( @@ -82,7 +86,6 @@ async def create_or_update( :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: AlertRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2016_03_01.models.AlertRuleResource :raises ~azure.core.exceptions.HttpResponseError: @@ -93,7 +96,7 @@ async def create_or_update( self, resource_group_name: str, rule_name: str, - parameters: IO, + parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -106,11 +109,10 @@ async def create_or_update( :param rule_name: The name of the rule. Required. :type rule_name: str :param parameters: The parameters of the rule to create or update. Required. - :type parameters: IO + :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: AlertRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2016_03_01.models.AlertRuleResource :raises ~azure.core.exceptions.HttpResponseError: @@ -118,7 +120,11 @@ async def create_or_update( @distributed_trace_async async def create_or_update( - self, resource_group_name: str, rule_name: str, parameters: Union[_models.AlertRuleResource, IO], **kwargs: Any + self, + resource_group_name: str, + rule_name: str, + parameters: Union[_models.AlertRuleResource, IO[bytes]], + **kwargs: Any ) -> _models.AlertRuleResource: """Creates or updates a classic metric alert rule. @@ -128,17 +134,13 @@ async def create_or_update( :param rule_name: The name of the rule. Required. :type rule_name: str :param parameters: The parameters of the rule to create or update. Is either a - AlertRuleResource type or a IO type. Required. - :type parameters: ~azure.mgmt.monitor.v2016_03_01.models.AlertRuleResource 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 + AlertRuleResource type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.monitor.v2016_03_01.models.AlertRuleResource or IO[bytes] :return: AlertRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2016_03_01.models.AlertRuleResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -149,19 +151,19 @@ async def create_or_update( _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", "2016-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2016-03-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.AlertRuleResource] = 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, "AlertRuleResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, rule_name=rule_name, subscription_id=self._config.subscription_id, @@ -169,16 +171,14 @@ async def create_or_update( 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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -188,25 +188,15 @@ async def create_or_update( 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("AlertRuleResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("AlertRuleResource", pipeline_response) + deserialized = self._deserialize("AlertRuleResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/alertrules/{ruleName}" - } - @distributed_trace_async - async def delete( # pylint: disable=inconsistent-return-statements - self, resource_group_name: str, rule_name: str, **kwargs: Any - ) -> None: + async def delete(self, resource_group_name: str, rule_name: str, **kwargs: Any) -> None: """Deletes a classic metric alert rule. :param resource_group_name: The name of the resource group. The name is case insensitive. @@ -214,12 +204,11 @@ async def delete( # pylint: disable=inconsistent-return-statements :type resource_group_name: str :param rule_name: The name of the rule. Required. :type 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, @@ -230,24 +219,22 @@ async def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2016-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2016-03-01")) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, rule_name=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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -258,11 +245,7 @@ async def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/alertrules/{ruleName}" - } + return cls(pipeline_response, None, {}) # type: ignore @distributed_trace_async async def get(self, resource_group_name: str, rule_name: str, **kwargs: Any) -> _models.AlertRuleResource: @@ -273,12 +256,11 @@ async def get(self, resource_group_name: str, rule_name: str, **kwargs: Any) -> :type resource_group_name: str :param rule_name: The name of the rule. Required. :type rule_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: AlertRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2016_03_01.models.AlertRuleResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -289,24 +271,22 @@ async def get(self, resource_group_name: str, rule_name: str, **kwargs: Any) -> _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2016-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2016-03-01")) cls: ClsType[_models.AlertRuleResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, rule_name=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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -316,16 +296,12 @@ async def get(self, resource_group_name: str, rule_name: str, **kwargs: Any) -> error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("AlertRuleResource", pipeline_response) + deserialized = self._deserialize("AlertRuleResource", 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.Insights/alertrules/{ruleName}" - } + return deserialized # type: ignore @overload async def update( @@ -350,7 +326,6 @@ async def update( :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: AlertRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2016_03_01.models.AlertRuleResource :raises ~azure.core.exceptions.HttpResponseError: @@ -361,7 +336,7 @@ async def update( self, resource_group_name: str, rule_name: str, - alert_rules_resource: IO, + alert_rules_resource: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -375,11 +350,10 @@ async def update( :param rule_name: The name of the rule. Required. :type rule_name: str :param alert_rules_resource: Parameters supplied to the operation. Required. - :type alert_rules_resource: IO + :type alert_rules_resource: 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: AlertRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2016_03_01.models.AlertRuleResource :raises ~azure.core.exceptions.HttpResponseError: @@ -390,7 +364,7 @@ async def update( self, resource_group_name: str, rule_name: str, - alert_rules_resource: Union[_models.AlertRuleResourcePatch, IO], + alert_rules_resource: Union[_models.AlertRuleResourcePatch, IO[bytes]], **kwargs: Any ) -> _models.AlertRuleResource: """Updates an existing classic metric AlertRuleResource. To update other fields use the @@ -402,17 +376,14 @@ async def update( :param rule_name: The name of the rule. Required. :type rule_name: str :param alert_rules_resource: Parameters supplied to the operation. Is either a - AlertRuleResourcePatch type or a IO type. Required. - :type alert_rules_resource: ~azure.mgmt.monitor.v2016_03_01.models.AlertRuleResourcePatch 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 + AlertRuleResourcePatch type or a IO[bytes] type. Required. + :type alert_rules_resource: ~azure.mgmt.monitor.v2016_03_01.models.AlertRuleResourcePatch or + IO[bytes] :return: AlertRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2016_03_01.models.AlertRuleResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -423,19 +394,19 @@ async def update( _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", "2016-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2016-03-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.AlertRuleResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(alert_rules_resource, (IO, bytes)): + if isinstance(alert_rules_resource, (IOBase, bytes)): _content = alert_rules_resource else: _json = self._serialize.body(alert_rules_resource, "AlertRuleResourcePatch") - request = build_update_request( + _request = build_update_request( resource_group_name=resource_group_name, rule_name=rule_name, subscription_id=self._config.subscription_id, @@ -443,16 +414,14 @@ async def update( 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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -462,21 +431,13 @@ async def update( 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("AlertRuleResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("AlertRuleResource", pipeline_response) + deserialized = self._deserialize("AlertRuleResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/alertrules/{ruleName}" - } - @distributed_trace def list_by_resource_group( self, resource_group_name: str, **kwargs: Any @@ -486,7 +447,6 @@ def list_by_resource_group( :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either AlertRuleResource or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.monitor.v2016_03_01.models.AlertRuleResource] @@ -495,10 +455,10 @@ def list_by_resource_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2016-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2016-03-01")) cls: ClsType[_models.AlertRuleResourceCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -509,16 +469,14 @@ 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_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -529,14 +487,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("AlertRuleResourceCollection", pipeline_response) @@ -546,11 +503,11 @@ async def extract_data(pipeline_response): return None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -563,15 +520,10 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/alertrules" - } - @distributed_trace def list_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.AlertRuleResource"]: """List the classic metric alert rules within a subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either AlertRuleResource or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.monitor.v2016_03_01.models.AlertRuleResource] @@ -580,10 +532,10 @@ def list_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.AlertRul _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2016-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2016-03-01")) cls: ClsType[_models.AlertRuleResourceCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -594,15 +546,13 @@ def list_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.AlertRul def prepare_request(next_link=None): if not next_link: - request = build_list_by_subscription_request( + _request = build_list_by_subscription_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_subscription.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -613,14 +563,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("AlertRuleResourceCollection", pipeline_response) @@ -630,11 +579,11 @@ async def extract_data(pipeline_response): return None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -646,5 +595,3 @@ async def get_next(next_link=None): return pipeline_response return AsyncItemPaged(get_next, extract_data) - - list_by_subscription.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/alertrules"} diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/aio/operations/_log_profiles_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/aio/operations/_log_profiles_operations.py index ecabbf2f5591..5739fc8abeee 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/aio/operations/_log_profiles_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/aio/operations/_log_profiles_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload import urllib.parse @@ -19,15 +20,13 @@ 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 ...operations._log_profiles_operations import ( build_create_or_update_request, build_delete_request, @@ -36,6 +35,10 @@ build_update_request, ) +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -58,21 +61,19 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace_async - async def delete( # pylint: disable=inconsistent-return-statements - self, log_profile_name: str, **kwargs: Any - ) -> None: + async def delete(self, log_profile_name: str, **kwargs: Any) -> None: """Deletes the log profile. :param log_profile_name: The name of the log profile. Required. :type log_profile_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, @@ -83,23 +84,21 @@ async def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2016-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2016-03-01")) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( log_profile_name=log_profile_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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -109,11 +108,7 @@ async def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/logprofiles/{logProfileName}" - } + return cls(pipeline_response, None, {}) # type: ignore @distributed_trace_async async def get(self, log_profile_name: str, **kwargs: Any) -> _models.LogProfileResource: @@ -121,12 +116,11 @@ async def get(self, log_profile_name: str, **kwargs: Any) -> _models.LogProfileR :param log_profile_name: The name of the log profile. Required. :type log_profile_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: LogProfileResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2016_03_01.models.LogProfileResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -137,23 +131,21 @@ async def get(self, log_profile_name: str, **kwargs: Any) -> _models.LogProfileR _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2016-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2016-03-01")) cls: ClsType[_models.LogProfileResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( log_profile_name=log_profile_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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -163,14 +155,12 @@ async def get(self, log_profile_name: str, **kwargs: Any) -> _models.LogProfileR error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("LogProfileResource", pipeline_response) + deserialized = self._deserialize("LogProfileResource", 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}/providers/Microsoft.Insights/logprofiles/{logProfileName}"} + return deserialized # type: ignore @overload async def create_or_update( @@ -190,7 +180,6 @@ async def create_or_update( :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: LogProfileResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2016_03_01.models.LogProfileResource :raises ~azure.core.exceptions.HttpResponseError: @@ -198,18 +187,17 @@ async def create_or_update( @overload async def create_or_update( - self, log_profile_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + self, log_profile_name: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any ) -> _models.LogProfileResource: """Create or update a log profile in Azure Monitoring REST API. :param log_profile_name: The name of the log profile. Required. :type log_profile_name: str :param parameters: Parameters supplied to the operation. Required. - :type parameters: IO + :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: LogProfileResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2016_03_01.models.LogProfileResource :raises ~azure.core.exceptions.HttpResponseError: @@ -217,24 +205,20 @@ async def create_or_update( @distributed_trace_async async def create_or_update( - self, log_profile_name: str, parameters: Union[_models.LogProfileResource, IO], **kwargs: Any + self, log_profile_name: str, parameters: Union[_models.LogProfileResource, IO[bytes]], **kwargs: Any ) -> _models.LogProfileResource: """Create or update a log profile in Azure Monitoring REST API. :param log_profile_name: The name of the log profile. Required. :type log_profile_name: str :param parameters: Parameters supplied to the operation. Is either a LogProfileResource type or - a IO type. Required. - :type parameters: ~azure.mgmt.monitor.v2016_03_01.models.LogProfileResource 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 + a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.monitor.v2016_03_01.models.LogProfileResource or IO[bytes] :return: LogProfileResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2016_03_01.models.LogProfileResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -245,35 +229,33 @@ async def create_or_update( _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", "2016-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2016-03-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.LogProfileResource] = 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, "LogProfileResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( log_profile_name=log_profile_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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -282,16 +264,12 @@ async def create_or_update( map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize("LogProfileResource", pipeline_response) + deserialized = self._deserialize("LogProfileResource", 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}/providers/Microsoft.Insights/logprofiles/{logProfileName}" - } + return deserialized # type: ignore @overload async def update( @@ -311,7 +289,6 @@ async def update( :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: LogProfileResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2016_03_01.models.LogProfileResource :raises ~azure.core.exceptions.HttpResponseError: @@ -319,18 +296,22 @@ async def update( @overload async def update( - self, log_profile_name: str, log_profiles_resource: IO, *, content_type: str = "application/json", **kwargs: Any + self, + log_profile_name: str, + log_profiles_resource: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any ) -> _models.LogProfileResource: """Updates an existing LogProfilesResource. To update other fields use the CreateOrUpdate method. :param log_profile_name: The name of the log profile. Required. :type log_profile_name: str :param log_profiles_resource: Parameters supplied to the operation. Required. - :type log_profiles_resource: IO + :type log_profiles_resource: 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: LogProfileResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2016_03_01.models.LogProfileResource :raises ~azure.core.exceptions.HttpResponseError: @@ -338,25 +319,24 @@ async def update( @distributed_trace_async async def update( - self, log_profile_name: str, log_profiles_resource: Union[_models.LogProfileResourcePatch, IO], **kwargs: Any + self, + log_profile_name: str, + log_profiles_resource: Union[_models.LogProfileResourcePatch, IO[bytes]], + **kwargs: Any ) -> _models.LogProfileResource: """Updates an existing LogProfilesResource. To update other fields use the CreateOrUpdate method. :param log_profile_name: The name of the log profile. Required. :type log_profile_name: str :param log_profiles_resource: Parameters supplied to the operation. Is either a - LogProfileResourcePatch type or a IO type. Required. + LogProfileResourcePatch type or a IO[bytes] type. Required. :type log_profiles_resource: ~azure.mgmt.monitor.v2016_03_01.models.LogProfileResourcePatch 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 + IO[bytes] :return: LogProfileResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2016_03_01.models.LogProfileResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -367,35 +347,33 @@ async def update( _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", "2016-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2016-03-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.LogProfileResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(log_profiles_resource, (IO, bytes)): + if isinstance(log_profiles_resource, (IOBase, bytes)): _content = log_profiles_resource else: _json = self._serialize.body(log_profiles_resource, "LogProfileResourcePatch") - request = build_update_request( + _request = build_update_request( log_profile_name=log_profile_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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -405,22 +383,17 @@ async def update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("LogProfileResource", pipeline_response) + deserialized = self._deserialize("LogProfileResource", 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}/providers/Microsoft.Insights/logprofiles/{logProfileName}" - } + return deserialized # type: ignore @distributed_trace def list(self, **kwargs: Any) -> AsyncIterable["_models.LogProfileResource"]: """List the log profiles. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either LogProfileResource or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.monitor.v2016_03_01.models.LogProfileResource] @@ -429,10 +402,10 @@ def list(self, **kwargs: Any) -> AsyncIterable["_models.LogProfileResource"]: _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2016-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2016-03-01")) cls: ClsType[_models.LogProfileCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -443,15 +416,13 @@ def list(self, **kwargs: Any) -> AsyncIterable["_models.LogProfileResource"]: def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _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) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -462,14 +433,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("LogProfileCollection", pipeline_response) @@ -479,11 +449,11 @@ async def extract_data(pipeline_response): return None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -494,5 +464,3 @@ async def get_next(next_link=None): return pipeline_response return AsyncItemPaged(get_next, extract_data) - - list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/logprofiles"} diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/aio/operations/_metric_definitions_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/aio/operations/_metric_definitions_operations.py index d8a60beccbd5..ef70782f2234 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/aio/operations/_metric_definitions_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/aio/operations/_metric_definitions_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,7 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar import urllib.parse @@ -19,16 +19,18 @@ 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 ...operations._metric_definitions_operations import build_list_request +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -51,6 +53,7 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list( @@ -62,12 +65,11 @@ def list( :type resource_uri: str :param filter: Reduces the set of data collected by retrieving particular metric definitions from all the definitions available for the resource.:code:`
`For example, to get just the - definition for the 'CPU percentage' counter: $filter=name.value eq '\Processor(_Total)\% + definition for the 'CPU percentage' counter: $filter=name.value eq '\\Processor(_Total)\\% Processor Time'.:code:`
`Multiple metrics can be retrieved by joining together *'name eq - :code:``'* clauses separated by *or* logical operators.:code:`
`\ **NOTE**\ : No + :code:``'* clauses separated by *or* logical operators.:code:`
`\\ **NOTE**\\ : No other syntax is allowed. Default value is None. :type filter: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either MetricDefinition or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.monitor.v2016_03_01.models.MetricDefinition] @@ -76,10 +78,10 @@ def list( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2016-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2016-03-01")) cls: ClsType[_models.MetricDefinitionCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -90,16 +92,14 @@ def list( def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( resource_uri=resource_uri, filter=filter, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -110,14 +110,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("MetricDefinitionCollection", pipeline_response) @@ -127,11 +126,11 @@ async def extract_data(pipeline_response): return None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -143,5 +142,3 @@ async def get_next(next_link=None): return pipeline_response return AsyncItemPaged(get_next, extract_data) - - list.metadata = {"url": "/{resourceUri}/providers/microsoft.insights/metricDefinitions"} diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/models/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/models/__init__.py index 07226e45344b..4a59ca29ba15 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/models/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/models/__init__.py @@ -5,41 +5,52 @@ # 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 AlertRuleResource -from ._models_py3 import AlertRuleResourceCollection -from ._models_py3 import AlertRuleResourcePatch -from ._models_py3 import ErrorResponse -from ._models_py3 import Incident -from ._models_py3 import IncidentListResult -from ._models_py3 import LocalizableString -from ._models_py3 import LocationThresholdRuleCondition -from ._models_py3 import LogProfileCollection -from ._models_py3 import LogProfileResource -from ._models_py3 import LogProfileResourcePatch -from ._models_py3 import ManagementEventAggregationCondition -from ._models_py3 import ManagementEventRuleCondition -from ._models_py3 import MetricAvailability -from ._models_py3 import MetricDefinition -from ._models_py3 import MetricDefinitionCollection -from ._models_py3 import Resource -from ._models_py3 import RetentionPolicy -from ._models_py3 import RuleAction -from ._models_py3 import RuleCondition -from ._models_py3 import RuleDataSource -from ._models_py3 import RuleEmailAction -from ._models_py3 import RuleManagementEventClaimsDataSource -from ._models_py3 import RuleManagementEventDataSource -from ._models_py3 import RuleMetricDataSource -from ._models_py3 import RuleWebhookAction -from ._models_py3 import ThresholdRuleCondition +from typing import TYPE_CHECKING -from ._monitor_management_client_enums import AggregationType -from ._monitor_management_client_enums import ConditionOperator -from ._monitor_management_client_enums import TimeAggregationOperator -from ._monitor_management_client_enums import Unit +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models_py3 import ( # type: ignore + AlertRuleResource, + AlertRuleResourceCollection, + AlertRuleResourcePatch, + ErrorResponse, + Incident, + IncidentListResult, + LocalizableString, + LocationThresholdRuleCondition, + LogProfileCollection, + LogProfileResource, + LogProfileResourcePatch, + ManagementEventAggregationCondition, + ManagementEventRuleCondition, + MetricAvailability, + MetricDefinition, + MetricDefinitionCollection, + Resource, + RetentionPolicy, + RuleAction, + RuleCondition, + RuleDataSource, + RuleEmailAction, + RuleManagementEventClaimsDataSource, + RuleManagementEventDataSource, + RuleMetricDataSource, + RuleWebhookAction, + ThresholdRuleCondition, +) + +from ._monitor_management_client_enums import ( # type: ignore + AggregationType, + ConditionOperator, + TimeAggregationOperator, + Unit, +) from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ @@ -75,5 +86,5 @@ "TimeAggregationOperator", "Unit", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/models/_models_py3.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/models/_models_py3.py index 9085894db256..343aa7398213 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/models/_models_py3.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/models/_models_py3.py @@ -1,5 +1,5 @@ -# coding=utf-8 # 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. @@ -13,7 +13,6 @@ from ... import _serialization if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from .. import models as _models @@ -22,7 +21,7 @@ class Resource(_serialization.Model): 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: Azure resource Id. :vartype id: str @@ -66,12 +65,12 @@ def __init__(self, *, location: str, tags: Optional[Dict[str, str]] = None, **kw self.tags = tags -class AlertRuleResource(Resource): # pylint: disable=too-many-instance-attributes +class AlertRuleResource(Resource): """The alert rule 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: Azure resource Id. :vartype id: str @@ -380,7 +379,7 @@ def __init__(self, *, value: Optional[List["_models.Incident"]] = None, **kwargs class LocalizableString(_serialization.Model): """The localizable string class. - 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 value: the invariant value. Required. :vartype value: str @@ -415,7 +414,7 @@ class RuleCondition(_serialization.Model): You probably want to use the sub-classes and not this class directly. Known sub-classes are: LocationThresholdRuleCondition, ManagementEventRuleCondition, ThresholdRuleCondition - 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 odata_type: specifies the type of condition. This can be one of three types: ManagementEventRuleCondition (occurrences of management events), LocationThresholdRuleCondition @@ -458,7 +457,7 @@ def __init__(self, *, data_source: Optional["_models.RuleDataSource"] = None, ** class LocationThresholdRuleCondition(RuleCondition): """A rule condition based on a certain number of locations failing. - 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 odata_type: specifies the type of condition. This can be one of three types: ManagementEventRuleCondition (occurrences of management events), LocationThresholdRuleCondition @@ -518,7 +517,7 @@ def __init__( class LogProfileCollection(_serialization.Model): """Represents a collection of log profiles. - 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 value: the values of the log profiles. Required. :vartype value: list[~azure.mgmt.monitor.v2016_03_01.models.LogProfileResource] @@ -546,7 +545,7 @@ class LogProfileResource(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: Azure resource Id. :vartype id: str @@ -757,7 +756,7 @@ def __init__( class ManagementEventRuleCondition(RuleCondition): """A management event rule condition. - 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 odata_type: specifies the type of condition. This can be one of three types: ManagementEventRuleCondition (occurrences of management events), LocationThresholdRuleCondition @@ -919,7 +918,7 @@ def __init__( class MetricDefinitionCollection(_serialization.Model): """Represents collection of metric definitions. - 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 value: the values for the metric definitions. Required. :vartype value: list[~azure.mgmt.monitor.v2016_03_01.models.MetricDefinition] @@ -945,7 +944,7 @@ def __init__(self, *, value: List["_models.MetricDefinition"], **kwargs: Any) -> class RetentionPolicy(_serialization.Model): """Specifies the retention policy for the log. - 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 enabled: a value indicating whether the retention policy is enabled. Required. :vartype enabled: bool @@ -984,7 +983,7 @@ class RuleAction(_serialization.Model): You probably want to use the sub-classes and not this class directly. Known sub-classes are: RuleEmailAction, RuleWebhookAction - 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 odata_type: specifies the type of the action. There are two types of actions: RuleEmailAction and RuleWebhookAction. Required. @@ -1018,16 +1017,16 @@ class RuleDataSource(_serialization.Model): You probably want to use the sub-classes and not this class directly. Known sub-classes are: RuleManagementEventDataSource, RuleMetricDataSource - 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 odata_type: specifies the type of data source. There are two types of rule data sources: RuleMetricDataSource and RuleManagementEventDataSource. Required. :vartype odata_type: str - :ivar resource_uri: the resource identifier of the resource the rule monitors. **NOTE**\ : this - property cannot be updated for an existing rule. + :ivar resource_uri: the resource identifier of the resource the rule monitors. **NOTE**\\ : + this property cannot be updated for an existing rule. :vartype resource_uri: str :ivar legacy_resource_id: the legacy resource identifier of the resource the rule monitors. - **NOTE**\ : this property cannot be updated for an existing rule. + **NOTE**\\ : this property cannot be updated for an existing rule. :vartype legacy_resource_id: str :ivar resource_location: the location of the resource. :vartype resource_location: str @@ -1064,11 +1063,11 @@ def __init__( **kwargs: Any ) -> None: """ - :keyword resource_uri: the resource identifier of the resource the rule monitors. **NOTE**\ : + :keyword resource_uri: the resource identifier of the resource the rule monitors. **NOTE**\\ : this property cannot be updated for an existing rule. :paramtype resource_uri: str :keyword legacy_resource_id: the legacy resource identifier of the resource the rule monitors. - **NOTE**\ : this property cannot be updated for an existing rule. + **NOTE**\\ : this property cannot be updated for an existing rule. :paramtype legacy_resource_id: str :keyword resource_location: the location of the resource. :paramtype resource_location: str @@ -1087,7 +1086,7 @@ class RuleEmailAction(RuleAction): """Specifies the action to send email when the rule condition is evaluated. The discriminator is always RuleEmailAction in this case. - 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 odata_type: specifies the type of the action. There are two types of actions: RuleEmailAction and RuleWebhookAction. Required. @@ -1147,20 +1146,20 @@ def __init__(self, *, email_address: Optional[str] = None, **kwargs: Any) -> Non self.email_address = email_address -class RuleManagementEventDataSource(RuleDataSource): # pylint: disable=too-many-instance-attributes +class RuleManagementEventDataSource(RuleDataSource): """A rule management event data source. The discriminator fields is always RuleManagementEventDataSource in this case. - 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 odata_type: specifies the type of data source. There are two types of rule data sources: RuleMetricDataSource and RuleManagementEventDataSource. Required. :vartype odata_type: str - :ivar resource_uri: the resource identifier of the resource the rule monitors. **NOTE**\ : this - property cannot be updated for an existing rule. + :ivar resource_uri: the resource identifier of the resource the rule monitors. **NOTE**\\ : + this property cannot be updated for an existing rule. :vartype resource_uri: str :ivar legacy_resource_id: the legacy resource identifier of the resource the rule monitors. - **NOTE**\ : this property cannot be updated for an existing rule. + **NOTE**\\ : this property cannot be updated for an existing rule. :vartype legacy_resource_id: str :ivar resource_location: the location of the resource. :vartype resource_location: str @@ -1228,11 +1227,11 @@ def __init__( **kwargs: Any ) -> None: """ - :keyword resource_uri: the resource identifier of the resource the rule monitors. **NOTE**\ : + :keyword resource_uri: the resource identifier of the resource the rule monitors. **NOTE**\\ : this property cannot be updated for an existing rule. :paramtype resource_uri: str :keyword legacy_resource_id: the legacy resource identifier of the resource the rule monitors. - **NOTE**\ : this property cannot be updated for an existing rule. + **NOTE**\\ : this property cannot be updated for an existing rule. :paramtype legacy_resource_id: str :keyword resource_location: the location of the resource. :paramtype resource_location: str @@ -1281,16 +1280,16 @@ def __init__( class RuleMetricDataSource(RuleDataSource): """A rule metric data source. The discriminator value is always RuleMetricDataSource in this case. - 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 odata_type: specifies the type of data source. There are two types of rule data sources: RuleMetricDataSource and RuleManagementEventDataSource. Required. :vartype odata_type: str - :ivar resource_uri: the resource identifier of the resource the rule monitors. **NOTE**\ : this - property cannot be updated for an existing rule. + :ivar resource_uri: the resource identifier of the resource the rule monitors. **NOTE**\\ : + this property cannot be updated for an existing rule. :vartype resource_uri: str :ivar legacy_resource_id: the legacy resource identifier of the resource the rule monitors. - **NOTE**\ : this property cannot be updated for an existing rule. + **NOTE**\\ : this property cannot be updated for an existing rule. :vartype legacy_resource_id: str :ivar resource_location: the location of the resource. :vartype resource_location: str @@ -1324,11 +1323,11 @@ def __init__( **kwargs: Any ) -> None: """ - :keyword resource_uri: the resource identifier of the resource the rule monitors. **NOTE**\ : + :keyword resource_uri: the resource identifier of the resource the rule monitors. **NOTE**\\ : this property cannot be updated for an existing rule. :paramtype resource_uri: str :keyword legacy_resource_id: the legacy resource identifier of the resource the rule monitors. - **NOTE**\ : this property cannot be updated for an existing rule. + **NOTE**\\ : this property cannot be updated for an existing rule. :paramtype legacy_resource_id: str :keyword resource_location: the location of the resource. :paramtype resource_location: str @@ -1352,7 +1351,7 @@ class RuleWebhookAction(RuleAction): """Specifies the action to post to service when the rule condition is evaluated. The discriminator is always RuleWebhookAction in this case. - 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 odata_type: specifies the type of the action. There are two types of actions: RuleEmailAction and RuleWebhookAction. Required. @@ -1395,7 +1394,7 @@ def __init__( class ThresholdRuleCondition(RuleCondition): """A rule condition based on a metric crossing a threshold. - 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 odata_type: specifies the type of condition. This can be one of three types: ManagementEventRuleCondition (occurrences of management events), LocationThresholdRuleCondition diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/operations/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/operations/__init__.py index 185356695cfa..8c7e395a7953 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/operations/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/operations/__init__.py @@ -5,14 +5,20 @@ # 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 ._alert_rule_incidents_operations import AlertRuleIncidentsOperations -from ._alert_rules_operations import AlertRulesOperations -from ._log_profiles_operations import LogProfilesOperations -from ._metric_definitions_operations import MetricDefinitionsOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._alert_rule_incidents_operations import AlertRuleIncidentsOperations # type: ignore +from ._alert_rules_operations import AlertRulesOperations # type: ignore +from ._log_profiles_operations import LogProfilesOperations # type: ignore +from ._metric_definitions_operations import MetricDefinitionsOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ @@ -21,5 +27,5 @@ "LogProfilesOperations", "MetricDefinitionsOperations", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/operations/_alert_rule_incidents_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/operations/_alert_rule_incidents_operations.py index d088008c787c..a03b86d411d8 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/operations/_alert_rule_incidents_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/operations/_alert_rule_incidents_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,7 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, Callable, Dict, Iterable, Optional, TypeVar import urllib.parse @@ -19,16 +19,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, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -59,7 +61,7 @@ def build_get_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -92,7 +94,7 @@ def build_list_by_alert_rule_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -121,6 +123,7 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def get(self, resource_group_name: str, rule_name: str, incident_name: str, **kwargs: Any) -> _models.Incident: @@ -133,12 +136,11 @@ def get(self, resource_group_name: str, rule_name: str, incident_name: str, **kw :type rule_name: str :param incident_name: The name of the incident to retrieve. Required. :type incident_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: Incident or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2016_03_01.models.Incident :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -149,25 +151,23 @@ def get(self, resource_group_name: str, rule_name: str, incident_name: str, **kw _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2016-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2016-03-01")) cls: ClsType[_models.Incident] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, rule_name=rule_name, incident_name=incident_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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -177,16 +177,12 @@ def get(self, resource_group_name: str, rule_name: str, incident_name: str, **kw error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("Incident", pipeline_response) + deserialized = self._deserialize("Incident", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - get.metadata = { - "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/microsoft.insights/alertrules/{ruleName}/incidents/{incidentName}" - } + return deserialized # type: ignore @distributed_trace def list_by_alert_rule( @@ -199,7 +195,6 @@ def list_by_alert_rule( :type resource_group_name: str :param rule_name: The name of the rule. Required. :type rule_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Incident or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.monitor.v2016_03_01.models.Incident] :raises ~azure.core.exceptions.HttpResponseError: @@ -207,10 +202,10 @@ def list_by_alert_rule( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2016-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2016-03-01")) cls: ClsType[_models.IncidentListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -221,17 +216,15 @@ def list_by_alert_rule( def prepare_request(next_link=None): if not next_link: - request = build_list_by_alert_rule_request( + _request = build_list_by_alert_rule_request( resource_group_name=resource_group_name, rule_name=rule_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_alert_rule.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -242,14 +235,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("IncidentListResult", pipeline_response) @@ -259,11 +251,11 @@ def extract_data(pipeline_response): return None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -274,7 +266,3 @@ def get_next(next_link=None): return pipeline_response return ItemPaged(get_next, extract_data) - - list_by_alert_rule.metadata = { - "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/microsoft.insights/alertrules/{ruleName}/incidents" - } diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/operations/_alert_rules_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/operations/_alert_rules_operations.py index 7b83bb3f1825..421f7662c521 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/operations/_alert_rules_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/operations/_alert_rules_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload import urllib.parse @@ -19,16 +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, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -59,7 +62,7 @@ def build_create_or_update_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -92,7 +95,7 @@ def build_delete_request(resource_group_name: str, rule_name: str, subscription_ "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -123,7 +126,7 @@ def build_get_request(resource_group_name: str, rule_name: str, subscription_id: "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -155,7 +158,7 @@ def build_update_request(resource_group_name: str, rule_name: str, subscription_ "ruleName": _SERIALIZER.url("rule_name", rule_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -187,7 +190,7 @@ def build_list_by_resource_group_request(resource_group_name: str, subscription_ "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -211,7 +214,7 @@ def build_list_by_subscription_request(subscription_id: str, **kwargs: Any) -> H "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -240,6 +243,7 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @overload def create_or_update( @@ -263,7 +267,6 @@ def create_or_update( :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: AlertRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2016_03_01.models.AlertRuleResource :raises ~azure.core.exceptions.HttpResponseError: @@ -274,7 +277,7 @@ def create_or_update( self, resource_group_name: str, rule_name: str, - parameters: IO, + parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -287,11 +290,10 @@ def create_or_update( :param rule_name: The name of the rule. Required. :type rule_name: str :param parameters: The parameters of the rule to create or update. Required. - :type parameters: IO + :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: AlertRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2016_03_01.models.AlertRuleResource :raises ~azure.core.exceptions.HttpResponseError: @@ -299,7 +301,11 @@ def create_or_update( @distributed_trace def create_or_update( - self, resource_group_name: str, rule_name: str, parameters: Union[_models.AlertRuleResource, IO], **kwargs: Any + self, + resource_group_name: str, + rule_name: str, + parameters: Union[_models.AlertRuleResource, IO[bytes]], + **kwargs: Any ) -> _models.AlertRuleResource: """Creates or updates a classic metric alert rule. @@ -309,17 +315,13 @@ def create_or_update( :param rule_name: The name of the rule. Required. :type rule_name: str :param parameters: The parameters of the rule to create or update. Is either a - AlertRuleResource type or a IO type. Required. - :type parameters: ~azure.mgmt.monitor.v2016_03_01.models.AlertRuleResource 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 + AlertRuleResource type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.monitor.v2016_03_01.models.AlertRuleResource or IO[bytes] :return: AlertRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2016_03_01.models.AlertRuleResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -330,19 +332,19 @@ def create_or_update( _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", "2016-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2016-03-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.AlertRuleResource] = 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, "AlertRuleResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, rule_name=rule_name, subscription_id=self._config.subscription_id, @@ -350,16 +352,14 @@ def create_or_update( 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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -369,21 +369,13 @@ def create_or_update( 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("AlertRuleResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("AlertRuleResource", pipeline_response) + deserialized = self._deserialize("AlertRuleResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/alertrules/{ruleName}" - } - @distributed_trace def delete( # pylint: disable=inconsistent-return-statements self, resource_group_name: str, rule_name: str, **kwargs: Any @@ -395,12 +387,11 @@ def delete( # pylint: disable=inconsistent-return-statements :type resource_group_name: str :param rule_name: The name of the rule. Required. :type 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, @@ -411,24 +402,22 @@ def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2016-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2016-03-01")) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, rule_name=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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -439,11 +428,7 @@ def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/alertrules/{ruleName}" - } + return cls(pipeline_response, None, {}) # type: ignore @distributed_trace def get(self, resource_group_name: str, rule_name: str, **kwargs: Any) -> _models.AlertRuleResource: @@ -454,12 +439,11 @@ def get(self, resource_group_name: str, rule_name: str, **kwargs: Any) -> _model :type resource_group_name: str :param rule_name: The name of the rule. Required. :type rule_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: AlertRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2016_03_01.models.AlertRuleResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -470,24 +454,22 @@ def get(self, resource_group_name: str, rule_name: str, **kwargs: Any) -> _model _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2016-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2016-03-01")) cls: ClsType[_models.AlertRuleResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, rule_name=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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -497,16 +479,12 @@ def get(self, resource_group_name: str, rule_name: str, **kwargs: Any) -> _model error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("AlertRuleResource", pipeline_response) + deserialized = self._deserialize("AlertRuleResource", 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.Insights/alertrules/{ruleName}" - } + return deserialized # type: ignore @overload def update( @@ -531,7 +509,6 @@ def update( :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: AlertRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2016_03_01.models.AlertRuleResource :raises ~azure.core.exceptions.HttpResponseError: @@ -542,7 +519,7 @@ def update( self, resource_group_name: str, rule_name: str, - alert_rules_resource: IO, + alert_rules_resource: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -556,11 +533,10 @@ def update( :param rule_name: The name of the rule. Required. :type rule_name: str :param alert_rules_resource: Parameters supplied to the operation. Required. - :type alert_rules_resource: IO + :type alert_rules_resource: 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: AlertRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2016_03_01.models.AlertRuleResource :raises ~azure.core.exceptions.HttpResponseError: @@ -571,7 +547,7 @@ def update( self, resource_group_name: str, rule_name: str, - alert_rules_resource: Union[_models.AlertRuleResourcePatch, IO], + alert_rules_resource: Union[_models.AlertRuleResourcePatch, IO[bytes]], **kwargs: Any ) -> _models.AlertRuleResource: """Updates an existing classic metric AlertRuleResource. To update other fields use the @@ -583,17 +559,14 @@ def update( :param rule_name: The name of the rule. Required. :type rule_name: str :param alert_rules_resource: Parameters supplied to the operation. Is either a - AlertRuleResourcePatch type or a IO type. Required. - :type alert_rules_resource: ~azure.mgmt.monitor.v2016_03_01.models.AlertRuleResourcePatch 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 + AlertRuleResourcePatch type or a IO[bytes] type. Required. + :type alert_rules_resource: ~azure.mgmt.monitor.v2016_03_01.models.AlertRuleResourcePatch or + IO[bytes] :return: AlertRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2016_03_01.models.AlertRuleResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -604,19 +577,19 @@ def update( _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", "2016-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2016-03-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.AlertRuleResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(alert_rules_resource, (IO, bytes)): + if isinstance(alert_rules_resource, (IOBase, bytes)): _content = alert_rules_resource else: _json = self._serialize.body(alert_rules_resource, "AlertRuleResourcePatch") - request = build_update_request( + _request = build_update_request( resource_group_name=resource_group_name, rule_name=rule_name, subscription_id=self._config.subscription_id, @@ -624,16 +597,14 @@ def update( 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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -643,21 +614,13 @@ def update( 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("AlertRuleResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("AlertRuleResource", pipeline_response) + deserialized = self._deserialize("AlertRuleResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/alertrules/{ruleName}" - } - @distributed_trace def list_by_resource_group(self, resource_group_name: str, **kwargs: Any) -> Iterable["_models.AlertRuleResource"]: """List the classic metric alert rules within a resource group. @@ -665,7 +628,6 @@ def list_by_resource_group(self, resource_group_name: str, **kwargs: Any) -> Ite :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either AlertRuleResource or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.monitor.v2016_03_01.models.AlertRuleResource] :raises ~azure.core.exceptions.HttpResponseError: @@ -673,10 +635,10 @@ def list_by_resource_group(self, resource_group_name: str, **kwargs: Any) -> Ite _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2016-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2016-03-01")) cls: ClsType[_models.AlertRuleResourceCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -687,16 +649,14 @@ 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_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -707,14 +667,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("AlertRuleResourceCollection", pipeline_response) @@ -724,11 +683,11 @@ def extract_data(pipeline_response): return None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -741,15 +700,10 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/alertrules" - } - @distributed_trace def list_by_subscription(self, **kwargs: Any) -> Iterable["_models.AlertRuleResource"]: """List the classic metric alert rules within a subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either AlertRuleResource or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.monitor.v2016_03_01.models.AlertRuleResource] :raises ~azure.core.exceptions.HttpResponseError: @@ -757,10 +711,10 @@ def list_by_subscription(self, **kwargs: Any) -> Iterable["_models.AlertRuleReso _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2016-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2016-03-01")) cls: ClsType[_models.AlertRuleResourceCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -771,15 +725,13 @@ def list_by_subscription(self, **kwargs: Any) -> Iterable["_models.AlertRuleReso def prepare_request(next_link=None): if not next_link: - request = build_list_by_subscription_request( + _request = build_list_by_subscription_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_subscription.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -790,14 +742,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("AlertRuleResourceCollection", pipeline_response) @@ -807,11 +758,11 @@ def extract_data(pipeline_response): return None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -823,5 +774,3 @@ def get_next(next_link=None): return pipeline_response return ItemPaged(get_next, extract_data) - - list_by_subscription.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/alertrules"} diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/operations/_log_profiles_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/operations/_log_profiles_operations.py index 2f8ac57fc9e2..13a2b2fdd89a 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/operations/_log_profiles_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/operations/_log_profiles_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload import urllib.parse @@ -19,16 +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, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -49,7 +52,7 @@ def build_delete_request(log_profile_name: str, subscription_id: str, **kwargs: "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -73,7 +76,7 @@ def build_get_request(log_profile_name: str, subscription_id: str, **kwargs: Any "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -101,7 +104,7 @@ def build_create_or_update_request(log_profile_name: str, subscription_id: str, "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -131,7 +134,7 @@ def build_update_request(log_profile_name: str, subscription_id: str, **kwargs: "logProfileName": _SERIALIZER.url("log_profile_name", log_profile_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -157,7 +160,7 @@ def build_list_request(subscription_id: str, **kwargs: Any) -> HttpRequest: "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -186,6 +189,7 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def delete(self, log_profile_name: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements @@ -193,12 +197,11 @@ def delete(self, log_profile_name: str, **kwargs: Any) -> None: # pylint: disab :param log_profile_name: The name of the log profile. Required. :type log_profile_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, @@ -209,23 +212,21 @@ def delete(self, log_profile_name: str, **kwargs: Any) -> None: # pylint: disab _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2016-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2016-03-01")) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( log_profile_name=log_profile_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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -235,11 +236,7 @@ def delete(self, log_profile_name: str, **kwargs: Any) -> None: # pylint: disab raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/logprofiles/{logProfileName}" - } + return cls(pipeline_response, None, {}) # type: ignore @distributed_trace def get(self, log_profile_name: str, **kwargs: Any) -> _models.LogProfileResource: @@ -247,12 +244,11 @@ def get(self, log_profile_name: str, **kwargs: Any) -> _models.LogProfileResourc :param log_profile_name: The name of the log profile. Required. :type log_profile_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: LogProfileResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2016_03_01.models.LogProfileResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -263,23 +259,21 @@ def get(self, log_profile_name: str, **kwargs: Any) -> _models.LogProfileResourc _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2016-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2016-03-01")) cls: ClsType[_models.LogProfileResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( log_profile_name=log_profile_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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -289,14 +283,12 @@ def get(self, log_profile_name: str, **kwargs: Any) -> _models.LogProfileResourc error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("LogProfileResource", pipeline_response) + deserialized = self._deserialize("LogProfileResource", 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}/providers/Microsoft.Insights/logprofiles/{logProfileName}"} + return deserialized # type: ignore @overload def create_or_update( @@ -316,7 +308,6 @@ def create_or_update( :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: LogProfileResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2016_03_01.models.LogProfileResource :raises ~azure.core.exceptions.HttpResponseError: @@ -324,18 +315,17 @@ def create_or_update( @overload def create_or_update( - self, log_profile_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + self, log_profile_name: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any ) -> _models.LogProfileResource: """Create or update a log profile in Azure Monitoring REST API. :param log_profile_name: The name of the log profile. Required. :type log_profile_name: str :param parameters: Parameters supplied to the operation. Required. - :type parameters: IO + :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: LogProfileResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2016_03_01.models.LogProfileResource :raises ~azure.core.exceptions.HttpResponseError: @@ -343,24 +333,20 @@ def create_or_update( @distributed_trace def create_or_update( - self, log_profile_name: str, parameters: Union[_models.LogProfileResource, IO], **kwargs: Any + self, log_profile_name: str, parameters: Union[_models.LogProfileResource, IO[bytes]], **kwargs: Any ) -> _models.LogProfileResource: """Create or update a log profile in Azure Monitoring REST API. :param log_profile_name: The name of the log profile. Required. :type log_profile_name: str :param parameters: Parameters supplied to the operation. Is either a LogProfileResource type or - a IO type. Required. - :type parameters: ~azure.mgmt.monitor.v2016_03_01.models.LogProfileResource 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 + a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.monitor.v2016_03_01.models.LogProfileResource or IO[bytes] :return: LogProfileResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2016_03_01.models.LogProfileResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -371,35 +357,33 @@ def create_or_update( _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", "2016-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2016-03-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.LogProfileResource] = 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, "LogProfileResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( log_profile_name=log_profile_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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -408,16 +392,12 @@ def create_or_update( map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize("LogProfileResource", pipeline_response) + deserialized = self._deserialize("LogProfileResource", 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}/providers/Microsoft.Insights/logprofiles/{logProfileName}" - } + return deserialized # type: ignore @overload def update( @@ -437,7 +417,6 @@ def update( :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: LogProfileResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2016_03_01.models.LogProfileResource :raises ~azure.core.exceptions.HttpResponseError: @@ -445,18 +424,22 @@ def update( @overload def update( - self, log_profile_name: str, log_profiles_resource: IO, *, content_type: str = "application/json", **kwargs: Any + self, + log_profile_name: str, + log_profiles_resource: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any ) -> _models.LogProfileResource: """Updates an existing LogProfilesResource. To update other fields use the CreateOrUpdate method. :param log_profile_name: The name of the log profile. Required. :type log_profile_name: str :param log_profiles_resource: Parameters supplied to the operation. Required. - :type log_profiles_resource: IO + :type log_profiles_resource: 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: LogProfileResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2016_03_01.models.LogProfileResource :raises ~azure.core.exceptions.HttpResponseError: @@ -464,25 +447,24 @@ def update( @distributed_trace def update( - self, log_profile_name: str, log_profiles_resource: Union[_models.LogProfileResourcePatch, IO], **kwargs: Any + self, + log_profile_name: str, + log_profiles_resource: Union[_models.LogProfileResourcePatch, IO[bytes]], + **kwargs: Any ) -> _models.LogProfileResource: """Updates an existing LogProfilesResource. To update other fields use the CreateOrUpdate method. :param log_profile_name: The name of the log profile. Required. :type log_profile_name: str :param log_profiles_resource: Parameters supplied to the operation. Is either a - LogProfileResourcePatch type or a IO type. Required. + LogProfileResourcePatch type or a IO[bytes] type. Required. :type log_profiles_resource: ~azure.mgmt.monitor.v2016_03_01.models.LogProfileResourcePatch 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 + IO[bytes] :return: LogProfileResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2016_03_01.models.LogProfileResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -493,35 +475,33 @@ def update( _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", "2016-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2016-03-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.LogProfileResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(log_profiles_resource, (IO, bytes)): + if isinstance(log_profiles_resource, (IOBase, bytes)): _content = log_profiles_resource else: _json = self._serialize.body(log_profiles_resource, "LogProfileResourcePatch") - request = build_update_request( + _request = build_update_request( log_profile_name=log_profile_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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -531,22 +511,17 @@ def update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("LogProfileResource", pipeline_response) + deserialized = self._deserialize("LogProfileResource", 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}/providers/Microsoft.Insights/logprofiles/{logProfileName}" - } + return deserialized # type: ignore @distributed_trace def list(self, **kwargs: Any) -> Iterable["_models.LogProfileResource"]: """List the log profiles. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either LogProfileResource or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.monitor.v2016_03_01.models.LogProfileResource] :raises ~azure.core.exceptions.HttpResponseError: @@ -554,10 +529,10 @@ def list(self, **kwargs: Any) -> Iterable["_models.LogProfileResource"]: _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2016-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2016-03-01")) cls: ClsType[_models.LogProfileCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -568,15 +543,13 @@ def list(self, **kwargs: Any) -> Iterable["_models.LogProfileResource"]: def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _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) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -587,14 +560,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("LogProfileCollection", pipeline_response) @@ -604,11 +576,11 @@ def extract_data(pipeline_response): return None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -619,5 +591,3 @@ def get_next(next_link=None): return pipeline_response return ItemPaged(get_next, extract_data) - - list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/logprofiles"} diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/operations/_metric_definitions_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/operations/_metric_definitions_operations.py index 03b71f5a9106..39ceac183e4d 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/operations/_metric_definitions_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_03_01/operations/_metric_definitions_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,7 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, Callable, Dict, Iterable, Optional, TypeVar import urllib.parse @@ -19,16 +19,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, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -49,7 +51,7 @@ def build_list_request(resource_uri: str, *, filter: Optional[str] = None, **kwa "resourceUri": _SERIALIZER.url("resource_uri", resource_uri, "str", skip_quote=True), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -80,6 +82,7 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list( @@ -91,12 +94,11 @@ def list( :type resource_uri: str :param filter: Reduces the set of data collected by retrieving particular metric definitions from all the definitions available for the resource.:code:`
`For example, to get just the - definition for the 'CPU percentage' counter: $filter=name.value eq '\Processor(_Total)\% + definition for the 'CPU percentage' counter: $filter=name.value eq '\\Processor(_Total)\\% Processor Time'.:code:`
`Multiple metrics can be retrieved by joining together *'name eq - :code:``'* clauses separated by *or* logical operators.:code:`
`\ **NOTE**\ : No + :code:``'* clauses separated by *or* logical operators.:code:`
`\\ **NOTE**\\ : No other syntax is allowed. Default value is None. :type filter: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either MetricDefinition or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.monitor.v2016_03_01.models.MetricDefinition] :raises ~azure.core.exceptions.HttpResponseError: @@ -104,10 +106,10 @@ def list( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2016-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2016-03-01")) cls: ClsType[_models.MetricDefinitionCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -118,16 +120,14 @@ def list( def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( resource_uri=resource_uri, filter=filter, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -138,14 +138,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("MetricDefinitionCollection", pipeline_response) @@ -155,11 +154,11 @@ def extract_data(pipeline_response): return None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -171,5 +170,3 @@ def get_next(next_link=None): return pipeline_response return ItemPaged(get_next, extract_data) - - list.metadata = {"url": "/{resourceUri}/providers/microsoft.insights/metricDefinitions"} diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_09_01/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_09_01/__init__.py index 2c7733bfd566..42cc62301757 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_09_01/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_09_01/__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 ._monitor_management_client import MonitorManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._monitor_management_client import MonitorManagementClient # type: ignore from ._version import VERSION __version__ = VERSION try: from ._patch import __all__ as _patch_all - from ._patch import * # 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__ = [ "MonitorManagementClient", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_09_01/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_09_01/_configuration.py index 562b6f4def40..28eccdbee471 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_09_01/_configuration.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_09_01/_configuration.py @@ -8,18 +8,16 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy from ._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MonitorManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class MonitorManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for MonitorManagementClient. Note that all parameters used to create this instance are saved as instance @@ -33,7 +31,6 @@ class MonitorManagementClientConfiguration(Configuration): # pylint: disable=to """ def __init__(self, credential: "TokenCredential", **kwargs: Any) -> None: - super(MonitorManagementClientConfiguration, self).__init__(**kwargs) api_version: str = kwargs.pop("api_version", "2016-09-01") if credential is None: @@ -43,6 +40,7 @@ def __init__(self, credential: "TokenCredential", **kwargs: Any) -> None: self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-monitor/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -51,9 +49,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.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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_09_01/_metadata.json b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_09_01/_metadata.json index 43644548c2d7..603eaca5a6e9 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_09_01/_metadata.json +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_09_01/_metadata.json @@ -8,10 +8,10 @@ "host_value": "\"https://management.azure.com\"", "parameterized_host_template": null, "azure_arm": true, - "has_lro_operations": false, + "has_public_lro_operations": false, "client_side_validation": false, - "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"sdkcore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMAutoResourceProviderRegistrationPolicy\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}, \"stdlib\": {\"typing_extensions\": [\"Self\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"sdkcore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"AsyncARMAutoResourceProviderRegistrationPolicy\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}, \"stdlib\": {\"typing_extensions\": [\"Self\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "global_parameters": { "sync": { @@ -88,8 +88,8 @@ "credential_scopes": ["https://management.azure.com/.default"], "credential_call_sync": "ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", "credential_call_async": "AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", - "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "sync_imports": "{\"regular\": {\"sdkcore\": {\"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"regular\": {\"sdkcore\": {\"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "operation_groups": { "metrics": "MetricsOperations", diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_09_01/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_09_01/_monitor_management_client.py index d892cfe15515..b0f6d0072daa 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_09_01/_monitor_management_client.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_09_01/_monitor_management_client.py @@ -8,9 +8,12 @@ from copy import deepcopy from typing import Any, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient +from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy from . import models as _models from .._serialization import Deserializer, Serializer @@ -18,11 +21,10 @@ from .operations import MetricsOperations, ServiceDiagnosticSettingsOperations if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MonitorManagementClient: # pylint: disable=client-accepts-api-version-keyword +class MonitorManagementClient: """Monitor Management Client. :ivar metrics: MetricsOperations operations @@ -43,18 +45,36 @@ def __init__( self, credential: "TokenCredential", base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: self._config = MonitorManagementClientConfiguration(credential=credential, **kwargs) - self._client: ARMPipelineClient = ARMPipelineClient(base_url=base_url, config=self._config, **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), + 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=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.metrics = MetricsOperations(self._client, self._config, self._serialize, self._deserialize) + self.metrics = MetricsOperations(self._client, self._config, self._serialize, self._deserialize, "2016-09-01") self.service_diagnostic_settings = ServiceDiagnosticSettingsOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2016-09-01" ) - 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 @@ -74,12 +94,12 @@ 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) -> None: self._client.close() - def __enter__(self) -> "MonitorManagementClient": + def __enter__(self) -> Self: self._client.__enter__() return self diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_09_01/_vendor.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_09_01/_vendor.py deleted file mode 100644 index bd0df84f5319..000000000000 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_09_01/_vendor.py +++ /dev/null @@ -1,30 +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 typing import List, cast - -from azure.core.pipeline.transport import HttpRequest - - -def _convert_request(request, files=None): - data = request.content if not files else None - request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) - if files: - request.set_formdata_body(files) - return request - - -def _format_url_section(template, **kwargs): - components = template.split("/") - while components: - try: - return template.format(**kwargs) - except KeyError as key: - # Need the cast, as for some reasons "split" is typed as list[str | Any] - formatted_components = cast(List[str], template.split("/")) - components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] - template = "/".join(components) diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_09_01/_version.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_09_01/_version.py index 394ee7c0c03c..e5754a47ce68 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_09_01/_version.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_09_01/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "6.0.2" +VERSION = "1.0.0b1" diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_09_01/aio/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_09_01/aio/__init__.py index 2c151bb41c19..3df30ff42149 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_09_01/aio/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_09_01/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 ._monitor_management_client import MonitorManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._monitor_management_client import MonitorManagementClient # type: ignore try: from ._patch import __all__ as _patch_all - from ._patch import * # 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__ = [ "MonitorManagementClient", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_09_01/aio/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_09_01/aio/_configuration.py index fe8724826315..8eae27c0d566 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_09_01/aio/_configuration.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_09_01/aio/_configuration.py @@ -8,18 +8,16 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy from .._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MonitorManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class MonitorManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for MonitorManagementClient. Note that all parameters used to create this instance are saved as instance @@ -33,7 +31,6 @@ class MonitorManagementClientConfiguration(Configuration): # pylint: disable=to """ def __init__(self, credential: "AsyncTokenCredential", **kwargs: Any) -> None: - super(MonitorManagementClientConfiguration, self).__init__(**kwargs) api_version: str = kwargs.pop("api_version", "2016-09-01") if credential is None: @@ -43,6 +40,7 @@ def __init__(self, credential: "AsyncTokenCredential", **kwargs: Any) -> None: self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-monitor/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -51,9 +49,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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_09_01/aio/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_09_01/aio/_monitor_management_client.py index 7b1d43f0764e..1f2a8c7aae93 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_09_01/aio/_monitor_management_client.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_09_01/aio/_monitor_management_client.py @@ -8,9 +8,12 @@ from copy import deepcopy from typing import Any, Awaitable, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient +from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy from .. import models as _models from ..._serialization import Deserializer, Serializer @@ -18,11 +21,10 @@ from .operations import MetricsOperations, ServiceDiagnosticSettingsOperations if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MonitorManagementClient: # pylint: disable=client-accepts-api-version-keyword +class MonitorManagementClient: """Monitor Management Client. :ivar metrics: MetricsOperations operations @@ -43,18 +45,38 @@ def __init__( self, credential: "AsyncTokenCredential", base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: self._config = MonitorManagementClientConfiguration(credential=credential, **kwargs) - self._client: AsyncARMPipelineClient = AsyncARMPipelineClient(base_url=base_url, config=self._config, **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=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.metrics = MetricsOperations(self._client, self._config, self._serialize, self._deserialize) + self.metrics = MetricsOperations(self._client, self._config, self._serialize, self._deserialize, "2016-09-01") self.service_diagnostic_settings = ServiceDiagnosticSettingsOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2016-09-01" ) - 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 @@ -74,12 +96,12 @@ 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) -> "MonitorManagementClient": + async def __aenter__(self) -> Self: await self._client.__aenter__() return self diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_09_01/aio/operations/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_09_01/aio/operations/__init__.py index ba50816b0687..bd6427d8b11d 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_09_01/aio/operations/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_09_01/aio/operations/__init__.py @@ -5,17 +5,23 @@ # 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 ._metrics_operations import MetricsOperations -from ._service_diagnostic_settings_operations import ServiceDiagnosticSettingsOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._metrics_operations import MetricsOperations # type: ignore +from ._service_diagnostic_settings_operations import ServiceDiagnosticSettingsOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ "MetricsOperations", "ServiceDiagnosticSettingsOperations", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_09_01/aio/operations/_metrics_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_09_01/aio/operations/_metrics_operations.py index bdce1709ba5b..ad228dd3839f 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_09_01/aio/operations/_metrics_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_09_01/aio/operations/_metrics_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,7 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar import urllib.parse @@ -19,16 +19,18 @@ 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 ...operations._metrics_operations import build_list_request +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -51,6 +53,7 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list(self, resource_uri: str, filter: Optional[str] = None, **kwargs: Any) -> AsyncIterable["_models.Metric"]: @@ -61,10 +64,10 @@ def list(self, resource_uri: str, filter: Optional[str] = None, **kwargs: Any) - :param filter: Reduces the set of data collected.:code:`
`The filter is optional. If present it must contain a list of metric names to retrieve of the form: *(name.value eq 'metricName' [or name.value eq 'metricName' or ...])*. Optionally, the filter can contain conditions for the - following attributes *aggregationType*\ , *startTime*\ , *endTime*\ , and *timeGrain* of the - form *attributeName operator value*. Where operator is one of *ne*\ , *eq*\ , *gt*\ , + following attributes *aggregationType*\\ , *startTime*\\ , *endTime*\\ , and *timeGrain* of the + form *attributeName operator value*. Where operator is one of *ne*\\ , *eq*\\ , *gt*\\ , *lt*.:code:`
`Several conditions can be combined with parentheses and logical operators, - e.g: *and*\ , *or*.:code:`
`Some example filter expressions are::code:`
`- + e.g: *and*\\ , *or*.:code:`
`Some example filter expressions are::code:`
`- $filter=(name.value eq 'RunsSucceeded') and aggregationType eq 'Total' and startTime eq 2016-02-20 and endTime eq 2016-02-21 and timeGrain eq duration'PT1M',:code:`
`- $filter=(name.value eq 'RunsSucceeded') and (aggregationType eq 'Total' or aggregationType eq @@ -72,12 +75,11 @@ def list(self, resource_uri: str, filter: Optional[str] = None, **kwargs: Any) - duration'PT1H',:code:`
`- $filter=(name.value eq 'ActionsCompleted' or name.value eq 'RunsSucceeded') and (aggregationType eq 'Total' or aggregationType eq 'Average') and startTime eq 2016-02-20 and endTime eq 2016-02-21 and timeGrain eq - duration'PT1M'.:code:`
`:code:`
`\ **NOTE**\ : When a metrics query comes in with + duration'PT1M'.:code:`
`:code:`
`\\ **NOTE**\\ : When a metrics query comes in with multiple metrics, but with no aggregation types defined, the service will pick the Primary aggregation type of the first metrics to be used as the default aggregation type for all the metrics. Default value is None. :type filter: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Metric or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.monitor.v2016_09_01.models.Metric] :raises ~azure.core.exceptions.HttpResponseError: @@ -85,10 +87,10 @@ def list(self, resource_uri: str, filter: Optional[str] = None, **kwargs: Any) - _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2016-09-01")) cls: ClsType[_models.MetricCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -99,16 +101,14 @@ def list(self, resource_uri: str, filter: Optional[str] = None, **kwargs: Any) - def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( resource_uri=resource_uri, filter=filter, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -119,14 +119,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("MetricCollection", pipeline_response) @@ -136,11 +135,11 @@ async def extract_data(pipeline_response): return None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -152,5 +151,3 @@ async def get_next(next_link=None): return pipeline_response return AsyncItemPaged(get_next, extract_data) - - list.metadata = {"url": "/{resourceUri}/providers/microsoft.insights/metrics"} diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_09_01/aio/operations/_service_diagnostic_settings_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_09_01/aio/operations/_service_diagnostic_settings_operations.py index 73cfe0f9daac..43fc86b9cdf2 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_09_01/aio/operations/_service_diagnostic_settings_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_09_01/aio/operations/_service_diagnostic_settings_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload from azure.core.exceptions import ( @@ -17,20 +18,22 @@ 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_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._service_diagnostic_settings_operations import ( build_create_or_update_request, build_get_request, build_update_request, ) +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -53,20 +56,20 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace_async async def get(self, resource_uri: str, **kwargs: Any) -> _models.ServiceDiagnosticSettingsResource: - """Gets the active diagnostic settings for the specified resource. **WARNING**\ : This method will - be deprecated in future releases. + """Gets the active diagnostic settings for the specified resource. **WARNING**\\ : This method + will be deprecated in future releases. :param resource_uri: The identifier of the resource. Required. :type resource_uri: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ServiceDiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2016_09_01.models.ServiceDiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -77,22 +80,20 @@ async def get(self, resource_uri: str, **kwargs: Any) -> _models.ServiceDiagnost _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2016-09-01")) cls: ClsType[_models.ServiceDiagnosticSettingsResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_uri=resource_uri, api_version=api_version, - template_url=self.get.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -102,14 +103,12 @@ async def get(self, resource_uri: str, **kwargs: Any) -> _models.ServiceDiagnost error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ServiceDiagnosticSettingsResource", pipeline_response) + deserialized = self._deserialize("ServiceDiagnosticSettingsResource", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get.metadata = {"url": "/{resourceUri}/providers/microsoft.insights/diagnosticSettings/service"} + return deserialized # type: ignore @overload async def create_or_update( @@ -120,8 +119,8 @@ async def create_or_update( content_type: str = "application/json", **kwargs: Any ) -> _models.ServiceDiagnosticSettingsResource: - """Create or update new diagnostic settings for the specified resource. **WARNING**\ : This method - will be deprecated in future releases. + """Create or update new diagnostic settings for the specified resource. **WARNING**\\ : This + method will be deprecated in future releases. :param resource_uri: The identifier of the resource. Required. :type resource_uri: str @@ -130,7 +129,6 @@ async def create_or_update( :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: ServiceDiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2016_09_01.models.ServiceDiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: @@ -138,19 +136,18 @@ async def create_or_update( @overload async def create_or_update( - self, resource_uri: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + self, resource_uri: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any ) -> _models.ServiceDiagnosticSettingsResource: - """Create or update new diagnostic settings for the specified resource. **WARNING**\ : This method - will be deprecated in future releases. + """Create or update new diagnostic settings for the specified resource. **WARNING**\\ : This + method will be deprecated in future releases. :param resource_uri: The identifier of the resource. Required. :type resource_uri: str :param parameters: Parameters supplied to the operation. Required. - :type parameters: IO + :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: ServiceDiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2016_09_01.models.ServiceDiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: @@ -158,26 +155,22 @@ async def create_or_update( @distributed_trace_async async def create_or_update( - self, resource_uri: str, parameters: Union[_models.ServiceDiagnosticSettingsResource, IO], **kwargs: Any + self, resource_uri: str, parameters: Union[_models.ServiceDiagnosticSettingsResource, IO[bytes]], **kwargs: Any ) -> _models.ServiceDiagnosticSettingsResource: - """Create or update new diagnostic settings for the specified resource. **WARNING**\ : This method - will be deprecated in future releases. + """Create or update new diagnostic settings for the specified resource. **WARNING**\\ : This + method will be deprecated in future releases. :param resource_uri: The identifier of the resource. Required. :type resource_uri: str :param parameters: Parameters supplied to the operation. Is either a - ServiceDiagnosticSettingsResource type or a IO type. Required. + ServiceDiagnosticSettingsResource type or a IO[bytes] type. Required. :type parameters: ~azure.mgmt.monitor.v2016_09_01.models.ServiceDiagnosticSettingsResource 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 + IO[bytes] :return: ServiceDiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2016_09_01.models.ServiceDiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -188,34 +181,32 @@ async def create_or_update( _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", "2016-09-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2016-09-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ServiceDiagnosticSettingsResource] = 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, "ServiceDiagnosticSettingsResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_uri=resource_uri, 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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -224,14 +215,12 @@ async def create_or_update( map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize("ServiceDiagnosticSettingsResource", pipeline_response) + deserialized = self._deserialize("ServiceDiagnosticSettingsResource", 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": "/{resourceUri}/providers/microsoft.insights/diagnosticSettings/service"} + return deserialized # type: ignore @overload async def update( @@ -243,7 +232,7 @@ async def update( **kwargs: Any ) -> _models.ServiceDiagnosticSettingsResource: """Updates an existing ServiceDiagnosticSettingsResource. To update other fields use the - CreateOrUpdate method. **WARNING**\ : This method will be deprecated in future releases. + CreateOrUpdate method. **WARNING**\\ : This method will be deprecated in future releases. :param resource_uri: The identifier of the resource. Required. :type resource_uri: str @@ -253,7 +242,6 @@ async def update( :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: ServiceDiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2016_09_01.models.ServiceDiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: @@ -263,22 +251,21 @@ async def update( async def update( self, resource_uri: str, - service_diagnostic_settings_resource: IO, + service_diagnostic_settings_resource: IO[bytes], *, content_type: str = "application/json", **kwargs: Any ) -> _models.ServiceDiagnosticSettingsResource: """Updates an existing ServiceDiagnosticSettingsResource. To update other fields use the - CreateOrUpdate method. **WARNING**\ : This method will be deprecated in future releases. + CreateOrUpdate method. **WARNING**\\ : This method will be deprecated in future releases. :param resource_uri: The identifier of the resource. Required. :type resource_uri: str :param service_diagnostic_settings_resource: Parameters supplied to the operation. Required. - :type service_diagnostic_settings_resource: IO + :type service_diagnostic_settings_resource: 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: ServiceDiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2016_09_01.models.ServiceDiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: @@ -288,27 +275,23 @@ async def update( async def update( self, resource_uri: str, - service_diagnostic_settings_resource: Union[_models.ServiceDiagnosticSettingsResourcePatch, IO], + service_diagnostic_settings_resource: Union[_models.ServiceDiagnosticSettingsResourcePatch, IO[bytes]], **kwargs: Any ) -> _models.ServiceDiagnosticSettingsResource: """Updates an existing ServiceDiagnosticSettingsResource. To update other fields use the - CreateOrUpdate method. **WARNING**\ : This method will be deprecated in future releases. + CreateOrUpdate method. **WARNING**\\ : This method will be deprecated in future releases. :param resource_uri: The identifier of the resource. Required. :type resource_uri: str :param service_diagnostic_settings_resource: Parameters supplied to the operation. Is either a - ServiceDiagnosticSettingsResourcePatch type or a IO type. Required. + ServiceDiagnosticSettingsResourcePatch type or a IO[bytes] type. Required. :type service_diagnostic_settings_resource: - ~azure.mgmt.monitor.v2016_09_01.models.ServiceDiagnosticSettingsResourcePatch 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 + ~azure.mgmt.monitor.v2016_09_01.models.ServiceDiagnosticSettingsResourcePatch or IO[bytes] :return: ServiceDiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2016_09_01.models.ServiceDiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -319,34 +302,32 @@ async def update( _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", "2016-09-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2016-09-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ServiceDiagnosticSettingsResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(service_diagnostic_settings_resource, (IO, bytes)): + if isinstance(service_diagnostic_settings_resource, (IOBase, bytes)): _content = service_diagnostic_settings_resource else: _json = self._serialize.body(service_diagnostic_settings_resource, "ServiceDiagnosticSettingsResourcePatch") - request = build_update_request( + _request = build_update_request( resource_uri=resource_uri, 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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -356,11 +337,9 @@ async def update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ServiceDiagnosticSettingsResource", pipeline_response) + deserialized = self._deserialize("ServiceDiagnosticSettingsResource", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - update.metadata = {"url": "/{resourceUri}/providers/microsoft.insights/diagnosticSettings/service"} + return deserialized # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_09_01/models/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_09_01/models/__init__.py index 6404a337a3f8..5ca74df020b2 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_09_01/models/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_09_01/models/__init__.py @@ -5,22 +5,33 @@ # 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 ErrorResponse -from ._models_py3 import LocalizableString -from ._models_py3 import LogSettings -from ._models_py3 import Metric -from ._models_py3 import MetricCollection -from ._models_py3 import MetricSettings -from ._models_py3 import MetricValue -from ._models_py3 import Resource -from ._models_py3 import RetentionPolicy -from ._models_py3 import ServiceDiagnosticSettingsResource -from ._models_py3 import ServiceDiagnosticSettingsResourcePatch +from typing import TYPE_CHECKING -from ._monitor_management_client_enums import Unit +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models_py3 import ( # type: ignore + ErrorResponse, + LocalizableString, + LogSettings, + Metric, + MetricCollection, + MetricSettings, + MetricValue, + Resource, + RetentionPolicy, + ServiceDiagnosticSettingsResource, + ServiceDiagnosticSettingsResourcePatch, +) + +from ._monitor_management_client_enums import ( # type: ignore + Unit, +) from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ @@ -37,5 +48,5 @@ "ServiceDiagnosticSettingsResourcePatch", "Unit", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_09_01/models/_models_py3.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_09_01/models/_models_py3.py index 21c5db38e5b1..85bb48bd7380 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_09_01/models/_models_py3.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_09_01/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. @@ -13,7 +12,6 @@ from ... import _serialization if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from .. import models as _models @@ -46,7 +44,7 @@ def __init__(self, *, code: Optional[str] = None, message: Optional[str] = None, class LocalizableString(_serialization.Model): """The localizable string class. - 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 value: the invariant value. Required. :vartype value: str @@ -78,7 +76,7 @@ def __init__(self, *, value: str, localized_value: Optional[str] = None, **kwarg class LogSettings(_serialization.Model): """Part of MultiTenantDiagnosticSettings. Specifies the settings for a particular log. - 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 category: Name of a Diagnostic Log category for a resource type this setting is applied to. To obtain the list of Diagnostic Log categories for a resource, first perform a GET @@ -127,7 +125,7 @@ def __init__( class Metric(_serialization.Model): """A set of metric values in a time range. - 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: the id, resourceId, of the metric. :vartype id: str @@ -194,7 +192,7 @@ def __init__( class MetricCollection(_serialization.Model): """The collection of metric value sets. - 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 value: the value of the collection. Required. :vartype value: list[~azure.mgmt.monitor.v2016_09_01.models.Metric] @@ -220,7 +218,7 @@ def __init__(self, *, value: List["_models.Metric"], **kwargs: Any) -> None: class MetricSettings(_serialization.Model): """Part of MultiTenantDiagnosticSettings. Specifies the settings for a particular metric. - 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 time_grain: the timegrain of the metric in ISO8601 format. Required. :vartype time_grain: ~datetime.timedelta @@ -266,7 +264,7 @@ def __init__( class MetricValue(_serialization.Model): """Represents a metric value. - 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 time_stamp: the timestamp for the metric value in ISO 8601 format. Required. :vartype time_stamp: ~datetime.datetime @@ -336,7 +334,7 @@ class Resource(_serialization.Model): 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: Azure resource Id. :vartype id: str @@ -383,7 +381,7 @@ def __init__(self, *, location: str, tags: Optional[Dict[str, str]] = None, **kw class RetentionPolicy(_serialization.Model): """Specifies the retention policy for the log. - 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 enabled: a value indicating whether the retention policy is enabled. Required. :vartype enabled: bool @@ -415,12 +413,12 @@ def __init__(self, *, enabled: bool, days: int, **kwargs: Any) -> None: self.days = days -class ServiceDiagnosticSettingsResource(Resource): # pylint: disable=too-many-instance-attributes +class ServiceDiagnosticSettingsResource(Resource): """Description of a service diagnostic setting. 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: Azure resource Id. :vartype id: str @@ -448,7 +446,7 @@ class ServiceDiagnosticSettingsResource(Resource): # pylint: disable=too-many-i :vartype logs: list[~azure.mgmt.monitor.v2016_09_01.models.LogSettings] :ivar workspace_id: The workspace ID (resource ID of a Log Analytics workspace) for a Log Analytics workspace to which you would like to send Diagnostic Logs. Example: - /subscriptions/4b9e8510-67ab-4e9a-95a9-e2f1e570ea9c/resourceGroups/insights-integration/providers/Microsoft.OperationalInsights/workspaces/viruela2. + /subscriptions/4b9e8510-67ab-4e9a-95a9-e2f1e570ea9c/resourceGroups/insights-integration/providers/Microsoft.OperationalInsights/workspaces/viruela2. # pylint: disable=line-too-long :vartype workspace_id: str """ @@ -507,7 +505,7 @@ def __init__( :paramtype logs: list[~azure.mgmt.monitor.v2016_09_01.models.LogSettings] :keyword workspace_id: The workspace ID (resource ID of a Log Analytics workspace) for a Log Analytics workspace to which you would like to send Diagnostic Logs. Example: - /subscriptions/4b9e8510-67ab-4e9a-95a9-e2f1e570ea9c/resourceGroups/insights-integration/providers/Microsoft.OperationalInsights/workspaces/viruela2. + /subscriptions/4b9e8510-67ab-4e9a-95a9-e2f1e570ea9c/resourceGroups/insights-integration/providers/Microsoft.OperationalInsights/workspaces/viruela2. # pylint: disable=line-too-long :paramtype workspace_id: str """ super().__init__(location=location, tags=tags, **kwargs) @@ -540,7 +538,7 @@ class ServiceDiagnosticSettingsResourcePatch(_serialization.Model): :vartype logs: list[~azure.mgmt.monitor.v2016_09_01.models.LogSettings] :ivar workspace_id: The workspace ID (resource ID of a Log Analytics workspace) for a Log Analytics workspace to which you would like to send Diagnostic Logs. Example: - /subscriptions/4b9e8510-67ab-4e9a-95a9-e2f1e570ea9c/resourceGroups/insights-integration/providers/Microsoft.OperationalInsights/workspaces/viruela2. + /subscriptions/4b9e8510-67ab-4e9a-95a9-e2f1e570ea9c/resourceGroups/insights-integration/providers/Microsoft.OperationalInsights/workspaces/viruela2. # pylint: disable=line-too-long :vartype workspace_id: str """ @@ -585,7 +583,7 @@ def __init__( :paramtype logs: list[~azure.mgmt.monitor.v2016_09_01.models.LogSettings] :keyword workspace_id: The workspace ID (resource ID of a Log Analytics workspace) for a Log Analytics workspace to which you would like to send Diagnostic Logs. Example: - /subscriptions/4b9e8510-67ab-4e9a-95a9-e2f1e570ea9c/resourceGroups/insights-integration/providers/Microsoft.OperationalInsights/workspaces/viruela2. + /subscriptions/4b9e8510-67ab-4e9a-95a9-e2f1e570ea9c/resourceGroups/insights-integration/providers/Microsoft.OperationalInsights/workspaces/viruela2. # pylint: disable=line-too-long :paramtype workspace_id: str """ super().__init__(**kwargs) diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_09_01/operations/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_09_01/operations/__init__.py index ba50816b0687..bd6427d8b11d 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_09_01/operations/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_09_01/operations/__init__.py @@ -5,17 +5,23 @@ # 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 ._metrics_operations import MetricsOperations -from ._service_diagnostic_settings_operations import ServiceDiagnosticSettingsOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._metrics_operations import MetricsOperations # type: ignore +from ._service_diagnostic_settings_operations import ServiceDiagnosticSettingsOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ "MetricsOperations", "ServiceDiagnosticSettingsOperations", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_09_01/operations/_metrics_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_09_01/operations/_metrics_operations.py index dbc223710694..0703557c9642 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_09_01/operations/_metrics_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_09_01/operations/_metrics_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,7 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, Callable, Dict, Iterable, Optional, TypeVar import urllib.parse @@ -19,16 +19,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, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -49,7 +51,7 @@ def build_list_request(resource_uri: str, *, filter: Optional[str] = None, **kwa "resourceUri": _SERIALIZER.url("resource_uri", resource_uri, "str", skip_quote=True), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters if filter is not None: @@ -80,6 +82,7 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list(self, resource_uri: str, filter: Optional[str] = None, **kwargs: Any) -> Iterable["_models.Metric"]: @@ -90,10 +93,10 @@ def list(self, resource_uri: str, filter: Optional[str] = None, **kwargs: Any) - :param filter: Reduces the set of data collected.:code:`
`The filter is optional. If present it must contain a list of metric names to retrieve of the form: *(name.value eq 'metricName' [or name.value eq 'metricName' or ...])*. Optionally, the filter can contain conditions for the - following attributes *aggregationType*\ , *startTime*\ , *endTime*\ , and *timeGrain* of the - form *attributeName operator value*. Where operator is one of *ne*\ , *eq*\ , *gt*\ , + following attributes *aggregationType*\\ , *startTime*\\ , *endTime*\\ , and *timeGrain* of the + form *attributeName operator value*. Where operator is one of *ne*\\ , *eq*\\ , *gt*\\ , *lt*.:code:`
`Several conditions can be combined with parentheses and logical operators, - e.g: *and*\ , *or*.:code:`
`Some example filter expressions are::code:`
`- + e.g: *and*\\ , *or*.:code:`
`Some example filter expressions are::code:`
`- $filter=(name.value eq 'RunsSucceeded') and aggregationType eq 'Total' and startTime eq 2016-02-20 and endTime eq 2016-02-21 and timeGrain eq duration'PT1M',:code:`
`- $filter=(name.value eq 'RunsSucceeded') and (aggregationType eq 'Total' or aggregationType eq @@ -101,12 +104,11 @@ def list(self, resource_uri: str, filter: Optional[str] = None, **kwargs: Any) - duration'PT1H',:code:`
`- $filter=(name.value eq 'ActionsCompleted' or name.value eq 'RunsSucceeded') and (aggregationType eq 'Total' or aggregationType eq 'Average') and startTime eq 2016-02-20 and endTime eq 2016-02-21 and timeGrain eq - duration'PT1M'.:code:`
`:code:`
`\ **NOTE**\ : When a metrics query comes in with + duration'PT1M'.:code:`
`:code:`
`\\ **NOTE**\\ : When a metrics query comes in with multiple metrics, but with no aggregation types defined, the service will pick the Primary aggregation type of the first metrics to be used as the default aggregation type for all the metrics. Default value is None. :type filter: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Metric or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.monitor.v2016_09_01.models.Metric] :raises ~azure.core.exceptions.HttpResponseError: @@ -114,10 +116,10 @@ def list(self, resource_uri: str, filter: Optional[str] = None, **kwargs: Any) - _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2016-09-01")) cls: ClsType[_models.MetricCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -128,16 +130,14 @@ def list(self, resource_uri: str, filter: Optional[str] = None, **kwargs: Any) - def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( resource_uri=resource_uri, filter=filter, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -148,14 +148,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("MetricCollection", pipeline_response) @@ -165,11 +164,11 @@ def extract_data(pipeline_response): return None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -181,5 +180,3 @@ def get_next(next_link=None): return pipeline_response return ItemPaged(get_next, extract_data) - - list.metadata = {"url": "/{resourceUri}/providers/microsoft.insights/metrics"} diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_09_01/operations/_service_diagnostic_settings_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_09_01/operations/_service_diagnostic_settings_operations.py index 4f09c027be1c..bdf25e02b55e 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_09_01/operations/_service_diagnostic_settings_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2016_09_01/operations/_service_diagnostic_settings_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload from azure.core.exceptions import ( @@ -17,16 +18,18 @@ map_error, ) 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 +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -47,7 +50,7 @@ def build_get_request(resource_uri: str, **kwargs: Any) -> HttpRequest: "resourceUri": _SERIALIZER.url("resource_uri", resource_uri, "str", skip_quote=True), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -72,7 +75,7 @@ def build_create_or_update_request(resource_uri: str, **kwargs: Any) -> HttpRequ "resourceUri": _SERIALIZER.url("resource_uri", resource_uri, "str", skip_quote=True), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -99,7 +102,7 @@ def build_update_request(resource_uri: str, **kwargs: Any) -> HttpRequest: "resourceUri": _SERIALIZER.url("resource_uri", resource_uri, "str", skip_quote=True), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -130,20 +133,20 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def get(self, resource_uri: str, **kwargs: Any) -> _models.ServiceDiagnosticSettingsResource: - """Gets the active diagnostic settings for the specified resource. **WARNING**\ : This method will - be deprecated in future releases. + """Gets the active diagnostic settings for the specified resource. **WARNING**\\ : This method + will be deprecated in future releases. :param resource_uri: The identifier of the resource. Required. :type resource_uri: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ServiceDiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2016_09_01.models.ServiceDiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -154,22 +157,20 @@ def get(self, resource_uri: str, **kwargs: Any) -> _models.ServiceDiagnosticSett _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2016-09-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2016-09-01")) cls: ClsType[_models.ServiceDiagnosticSettingsResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_uri=resource_uri, api_version=api_version, - template_url=self.get.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -179,14 +180,12 @@ def get(self, resource_uri: str, **kwargs: Any) -> _models.ServiceDiagnosticSett error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ServiceDiagnosticSettingsResource", pipeline_response) + deserialized = self._deserialize("ServiceDiagnosticSettingsResource", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get.metadata = {"url": "/{resourceUri}/providers/microsoft.insights/diagnosticSettings/service"} + return deserialized # type: ignore @overload def create_or_update( @@ -197,8 +196,8 @@ def create_or_update( content_type: str = "application/json", **kwargs: Any ) -> _models.ServiceDiagnosticSettingsResource: - """Create or update new diagnostic settings for the specified resource. **WARNING**\ : This method - will be deprecated in future releases. + """Create or update new diagnostic settings for the specified resource. **WARNING**\\ : This + method will be deprecated in future releases. :param resource_uri: The identifier of the resource. Required. :type resource_uri: str @@ -207,7 +206,6 @@ def create_or_update( :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: ServiceDiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2016_09_01.models.ServiceDiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: @@ -215,19 +213,18 @@ def create_or_update( @overload def create_or_update( - self, resource_uri: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + self, resource_uri: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any ) -> _models.ServiceDiagnosticSettingsResource: - """Create or update new diagnostic settings for the specified resource. **WARNING**\ : This method - will be deprecated in future releases. + """Create or update new diagnostic settings for the specified resource. **WARNING**\\ : This + method will be deprecated in future releases. :param resource_uri: The identifier of the resource. Required. :type resource_uri: str :param parameters: Parameters supplied to the operation. Required. - :type parameters: IO + :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: ServiceDiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2016_09_01.models.ServiceDiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: @@ -235,26 +232,22 @@ def create_or_update( @distributed_trace def create_or_update( - self, resource_uri: str, parameters: Union[_models.ServiceDiagnosticSettingsResource, IO], **kwargs: Any + self, resource_uri: str, parameters: Union[_models.ServiceDiagnosticSettingsResource, IO[bytes]], **kwargs: Any ) -> _models.ServiceDiagnosticSettingsResource: - """Create or update new diagnostic settings for the specified resource. **WARNING**\ : This method - will be deprecated in future releases. + """Create or update new diagnostic settings for the specified resource. **WARNING**\\ : This + method will be deprecated in future releases. :param resource_uri: The identifier of the resource. Required. :type resource_uri: str :param parameters: Parameters supplied to the operation. Is either a - ServiceDiagnosticSettingsResource type or a IO type. Required. + ServiceDiagnosticSettingsResource type or a IO[bytes] type. Required. :type parameters: ~azure.mgmt.monitor.v2016_09_01.models.ServiceDiagnosticSettingsResource 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 + IO[bytes] :return: ServiceDiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2016_09_01.models.ServiceDiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -265,34 +258,32 @@ def create_or_update( _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", "2016-09-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2016-09-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ServiceDiagnosticSettingsResource] = 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, "ServiceDiagnosticSettingsResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_uri=resource_uri, 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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -301,14 +292,12 @@ def create_or_update( map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize("ServiceDiagnosticSettingsResource", pipeline_response) + deserialized = self._deserialize("ServiceDiagnosticSettingsResource", 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": "/{resourceUri}/providers/microsoft.insights/diagnosticSettings/service"} + return deserialized # type: ignore @overload def update( @@ -320,7 +309,7 @@ def update( **kwargs: Any ) -> _models.ServiceDiagnosticSettingsResource: """Updates an existing ServiceDiagnosticSettingsResource. To update other fields use the - CreateOrUpdate method. **WARNING**\ : This method will be deprecated in future releases. + CreateOrUpdate method. **WARNING**\\ : This method will be deprecated in future releases. :param resource_uri: The identifier of the resource. Required. :type resource_uri: str @@ -330,7 +319,6 @@ def update( :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: ServiceDiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2016_09_01.models.ServiceDiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: @@ -340,22 +328,21 @@ def update( def update( self, resource_uri: str, - service_diagnostic_settings_resource: IO, + service_diagnostic_settings_resource: IO[bytes], *, content_type: str = "application/json", **kwargs: Any ) -> _models.ServiceDiagnosticSettingsResource: """Updates an existing ServiceDiagnosticSettingsResource. To update other fields use the - CreateOrUpdate method. **WARNING**\ : This method will be deprecated in future releases. + CreateOrUpdate method. **WARNING**\\ : This method will be deprecated in future releases. :param resource_uri: The identifier of the resource. Required. :type resource_uri: str :param service_diagnostic_settings_resource: Parameters supplied to the operation. Required. - :type service_diagnostic_settings_resource: IO + :type service_diagnostic_settings_resource: 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: ServiceDiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2016_09_01.models.ServiceDiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: @@ -365,27 +352,23 @@ def update( def update( self, resource_uri: str, - service_diagnostic_settings_resource: Union[_models.ServiceDiagnosticSettingsResourcePatch, IO], + service_diagnostic_settings_resource: Union[_models.ServiceDiagnosticSettingsResourcePatch, IO[bytes]], **kwargs: Any ) -> _models.ServiceDiagnosticSettingsResource: """Updates an existing ServiceDiagnosticSettingsResource. To update other fields use the - CreateOrUpdate method. **WARNING**\ : This method will be deprecated in future releases. + CreateOrUpdate method. **WARNING**\\ : This method will be deprecated in future releases. :param resource_uri: The identifier of the resource. Required. :type resource_uri: str :param service_diagnostic_settings_resource: Parameters supplied to the operation. Is either a - ServiceDiagnosticSettingsResourcePatch type or a IO type. Required. + ServiceDiagnosticSettingsResourcePatch type or a IO[bytes] type. Required. :type service_diagnostic_settings_resource: - ~azure.mgmt.monitor.v2016_09_01.models.ServiceDiagnosticSettingsResourcePatch 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 + ~azure.mgmt.monitor.v2016_09_01.models.ServiceDiagnosticSettingsResourcePatch or IO[bytes] :return: ServiceDiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2016_09_01.models.ServiceDiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -396,34 +379,32 @@ def update( _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", "2016-09-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2016-09-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ServiceDiagnosticSettingsResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(service_diagnostic_settings_resource, (IO, bytes)): + if isinstance(service_diagnostic_settings_resource, (IOBase, bytes)): _content = service_diagnostic_settings_resource else: _json = self._serialize.body(service_diagnostic_settings_resource, "ServiceDiagnosticSettingsResourcePatch") - request = build_update_request( + _request = build_update_request( resource_uri=resource_uri, 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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -433,11 +414,9 @@ def update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ServiceDiagnosticSettingsResource", pipeline_response) + deserialized = self._deserialize("ServiceDiagnosticSettingsResource", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - update.metadata = {"url": "/{resourceUri}/providers/microsoft.insights/diagnosticSettings/service"} + return deserialized # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_03_01_preview/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_03_01_preview/__init__.py index 2c7733bfd566..42cc62301757 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_03_01_preview/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_03_01_preview/__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 ._monitor_management_client import MonitorManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._monitor_management_client import MonitorManagementClient # type: ignore from ._version import VERSION __version__ = VERSION try: from ._patch import __all__ as _patch_all - from ._patch import * # 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__ = [ "MonitorManagementClient", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_03_01_preview/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_03_01_preview/_configuration.py index fdcd1f8c7456..80892bdeb9ad 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_03_01_preview/_configuration.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_03_01_preview/_configuration.py @@ -8,18 +8,16 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy from ._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MonitorManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class MonitorManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for MonitorManagementClient. Note that all parameters used to create this instance are saved as instance @@ -35,7 +33,6 @@ class MonitorManagementClientConfiguration(Configuration): # pylint: disable=to """ def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: - super(MonitorManagementClientConfiguration, self).__init__(**kwargs) api_version: str = kwargs.pop("api_version", "2017-03-01-preview") if credential is None: @@ -48,6 +45,7 @@ def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-monitor/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -56,9 +54,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.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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_03_01_preview/_metadata.json b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_03_01_preview/_metadata.json index 9efc7cb572fe..19f1a41fe504 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_03_01_preview/_metadata.json +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_03_01_preview/_metadata.json @@ -8,10 +8,10 @@ "host_value": "\"https://management.azure.com\"", "parameterized_host_template": null, "azure_arm": true, - "has_lro_operations": false, + "has_public_lro_operations": false, "client_side_validation": false, - "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"sdkcore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMAutoResourceProviderRegistrationPolicy\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}, \"stdlib\": {\"typing_extensions\": [\"Self\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"sdkcore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"AsyncARMAutoResourceProviderRegistrationPolicy\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}, \"stdlib\": {\"typing_extensions\": [\"Self\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "global_parameters": { "sync": { @@ -101,8 +101,8 @@ "credential_scopes": ["https://management.azure.com/.default"], "credential_call_sync": "ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", "credential_call_async": "AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", - "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "sync_imports": "{\"regular\": {\"sdkcore\": {\"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"regular\": {\"sdkcore\": {\"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "operation_groups": { "activity_log_alerts": "ActivityLogAlertsOperations" diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_03_01_preview/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_03_01_preview/_monitor_management_client.py index 8e181236d253..4ea1aef6a12d 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_03_01_preview/_monitor_management_client.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_03_01_preview/_monitor_management_client.py @@ -8,9 +8,12 @@ from copy import deepcopy from typing import Any, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient +from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy from . import models as _models from .._serialization import Deserializer, Serializer @@ -18,11 +21,10 @@ from .operations import ActivityLogAlertsOperations if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MonitorManagementClient: # pylint: disable=client-accepts-api-version-keyword +class MonitorManagementClient: """Monitor Management Client. :ivar activity_log_alerts: ActivityLogAlertsOperations operations @@ -49,17 +51,35 @@ def __init__( self._config = MonitorManagementClientConfiguration( credential=credential, subscription_id=subscription_id, **kwargs ) - self._client: ARMPipelineClient = ARMPipelineClient(base_url=base_url, config=self._config, **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), + 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=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.activity_log_alerts = ActivityLogAlertsOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2017-03-01-preview" ) - 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 @@ -79,12 +99,12 @@ 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) -> None: self._client.close() - def __enter__(self) -> "MonitorManagementClient": + def __enter__(self) -> Self: self._client.__enter__() return self diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_03_01_preview/_vendor.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_03_01_preview/_vendor.py deleted file mode 100644 index bd0df84f5319..000000000000 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_03_01_preview/_vendor.py +++ /dev/null @@ -1,30 +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 typing import List, cast - -from azure.core.pipeline.transport import HttpRequest - - -def _convert_request(request, files=None): - data = request.content if not files else None - request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) - if files: - request.set_formdata_body(files) - return request - - -def _format_url_section(template, **kwargs): - components = template.split("/") - while components: - try: - return template.format(**kwargs) - except KeyError as key: - # Need the cast, as for some reasons "split" is typed as list[str | Any] - formatted_components = cast(List[str], template.split("/")) - components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] - template = "/".join(components) diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_03_01_preview/_version.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_03_01_preview/_version.py index 394ee7c0c03c..e5754a47ce68 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_03_01_preview/_version.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_03_01_preview/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "6.0.2" +VERSION = "1.0.0b1" diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_03_01_preview/aio/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_03_01_preview/aio/__init__.py index 2c151bb41c19..3df30ff42149 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_03_01_preview/aio/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_03_01_preview/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 ._monitor_management_client import MonitorManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._monitor_management_client import MonitorManagementClient # type: ignore try: from ._patch import __all__ as _patch_all - from ._patch import * # 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__ = [ "MonitorManagementClient", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_03_01_preview/aio/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_03_01_preview/aio/_configuration.py index 40ec0a582da1..de38482a8068 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_03_01_preview/aio/_configuration.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_03_01_preview/aio/_configuration.py @@ -8,18 +8,16 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy from .._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MonitorManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class MonitorManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for MonitorManagementClient. Note that all parameters used to create this instance are saved as instance @@ -35,7 +33,6 @@ class MonitorManagementClientConfiguration(Configuration): # pylint: disable=to """ def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: - super(MonitorManagementClientConfiguration, self).__init__(**kwargs) api_version: str = kwargs.pop("api_version", "2017-03-01-preview") if credential is None: @@ -48,6 +45,7 @@ def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **k self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-monitor/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -56,9 +54,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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_03_01_preview/aio/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_03_01_preview/aio/_monitor_management_client.py index 47608ace8a5c..1fc0ba57c473 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_03_01_preview/aio/_monitor_management_client.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_03_01_preview/aio/_monitor_management_client.py @@ -8,9 +8,12 @@ from copy import deepcopy from typing import Any, Awaitable, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient +from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy from .. import models as _models from ..._serialization import Deserializer, Serializer @@ -18,11 +21,10 @@ from .operations import ActivityLogAlertsOperations if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MonitorManagementClient: # pylint: disable=client-accepts-api-version-keyword +class MonitorManagementClient: """Monitor Management Client. :ivar activity_log_alerts: ActivityLogAlertsOperations operations @@ -49,17 +51,37 @@ def __init__( self._config = MonitorManagementClientConfiguration( credential=credential, subscription_id=subscription_id, **kwargs ) - self._client: AsyncARMPipelineClient = AsyncARMPipelineClient(base_url=base_url, config=self._config, **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=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.activity_log_alerts = ActivityLogAlertsOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2017-03-01-preview" ) - 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 @@ -79,12 +101,12 @@ 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) -> "MonitorManagementClient": + async def __aenter__(self) -> Self: await self._client.__aenter__() return self diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_03_01_preview/aio/operations/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_03_01_preview/aio/operations/__init__.py index b024a2af0682..41e2b371bc7a 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_03_01_preview/aio/operations/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_03_01_preview/aio/operations/__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 ._activity_log_alerts_operations import ActivityLogAlertsOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._activity_log_alerts_operations import ActivityLogAlertsOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ "ActivityLogAlertsOperations", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_03_01_preview/aio/operations/_activity_log_alerts_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_03_01_preview/aio/operations/_activity_log_alerts_operations.py index 61c912abf42b..a016632507b1 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_03_01_preview/aio/operations/_activity_log_alerts_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_03_01_preview/aio/operations/_activity_log_alerts_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload import urllib.parse @@ -19,15 +20,13 @@ 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 ...operations._activity_log_alerts_operations import ( build_create_or_update_request, build_delete_request, @@ -37,6 +36,10 @@ build_update_request, ) +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -59,6 +62,7 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @overload async def create_or_update( @@ -83,7 +87,6 @@ async def create_or_update( :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: ActivityLogAlertResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2017_03_01_preview.models.ActivityLogAlertResource :raises ~azure.core.exceptions.HttpResponseError: @@ -94,7 +97,7 @@ async def create_or_update( self, resource_group_name: str, activity_log_alert_name: str, - activity_log_alert: IO, + activity_log_alert: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -107,11 +110,10 @@ async def create_or_update( :param activity_log_alert_name: The name of the activity log alert. Required. :type activity_log_alert_name: str :param activity_log_alert: The activity log alert to create or use for the update. Required. - :type activity_log_alert: IO + :type activity_log_alert: 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: ActivityLogAlertResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2017_03_01_preview.models.ActivityLogAlertResource :raises ~azure.core.exceptions.HttpResponseError: @@ -122,7 +124,7 @@ async def create_or_update( self, resource_group_name: str, activity_log_alert_name: str, - activity_log_alert: Union[_models.ActivityLogAlertResource, IO], + activity_log_alert: Union[_models.ActivityLogAlertResource, IO[bytes]], **kwargs: Any ) -> _models.ActivityLogAlertResource: """Create a new activity log alert or update an existing one. @@ -133,18 +135,14 @@ async def create_or_update( :param activity_log_alert_name: The name of the activity log alert. Required. :type activity_log_alert_name: str :param activity_log_alert: The activity log alert to create or use for the update. Is either a - ActivityLogAlertResource type or a IO type. Required. + ActivityLogAlertResource type or a IO[bytes] type. Required. :type activity_log_alert: - ~azure.mgmt.monitor.v2017_03_01_preview.models.ActivityLogAlertResource 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 + ~azure.mgmt.monitor.v2017_03_01_preview.models.ActivityLogAlertResource or IO[bytes] :return: ActivityLogAlertResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2017_03_01_preview.models.ActivityLogAlertResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -155,19 +153,21 @@ async def create_or_update( _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", "2017-03-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2017-03-01-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ActivityLogAlertResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(activity_log_alert, (IO, bytes)): + if isinstance(activity_log_alert, (IOBase, bytes)): _content = activity_log_alert else: _json = self._serialize.body(activity_log_alert, "ActivityLogAlertResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, activity_log_alert_name=activity_log_alert_name, subscription_id=self._config.subscription_id, @@ -175,16 +175,14 @@ async def create_or_update( 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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -194,21 +192,13 @@ async def create_or_update( 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("ActivityLogAlertResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("ActivityLogAlertResource", pipeline_response) + deserialized = self._deserialize("ActivityLogAlertResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/activityLogAlerts/{activityLogAlertName}" - } - @distributed_trace_async async def get( self, resource_group_name: str, activity_log_alert_name: str, **kwargs: Any @@ -220,12 +210,11 @@ async def get( :type resource_group_name: str :param activity_log_alert_name: The name of the activity log alert. Required. :type activity_log_alert_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ActivityLogAlertResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2017_03_01_preview.models.ActivityLogAlertResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -236,24 +225,24 @@ async def get( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-03-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2017-03-01-preview") + ) cls: ClsType[_models.ActivityLogAlertResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, activity_log_alert_name=activity_log_alert_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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -263,21 +252,15 @@ async def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ActivityLogAlertResource", pipeline_response) + deserialized = self._deserialize("ActivityLogAlertResource", 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.insights/activityLogAlerts/{activityLogAlertName}" - } + return deserialized # type: ignore @distributed_trace_async - async def delete( # pylint: disable=inconsistent-return-statements - self, resource_group_name: str, activity_log_alert_name: str, **kwargs: Any - ) -> None: + async def delete(self, resource_group_name: str, activity_log_alert_name: str, **kwargs: Any) -> None: """Delete an activity log alert. :param resource_group_name: The name of the resource group. The name is case insensitive. @@ -285,12 +268,11 @@ async def delete( # pylint: disable=inconsistent-return-statements :type resource_group_name: str :param activity_log_alert_name: The name of the activity log alert. Required. :type activity_log_alert_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, @@ -301,24 +283,24 @@ async def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-03-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2017-03-01-preview") + ) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, activity_log_alert_name=activity_log_alert_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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -329,11 +311,7 @@ async def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/activityLogAlerts/{activityLogAlertName}" - } + return cls(pipeline_response, None, {}) # type: ignore @overload async def update( @@ -359,7 +337,6 @@ async def update( :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: ActivityLogAlertResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2017_03_01_preview.models.ActivityLogAlertResource :raises ~azure.core.exceptions.HttpResponseError: @@ -370,7 +347,7 @@ async def update( self, resource_group_name: str, activity_log_alert_name: str, - activity_log_alert_patch: IO, + activity_log_alert_patch: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -384,11 +361,10 @@ async def update( :param activity_log_alert_name: The name of the activity log alert. Required. :type activity_log_alert_name: str :param activity_log_alert_patch: Parameters supplied to the operation. Required. - :type activity_log_alert_patch: IO + :type activity_log_alert_patch: 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: ActivityLogAlertResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2017_03_01_preview.models.ActivityLogAlertResource :raises ~azure.core.exceptions.HttpResponseError: @@ -399,7 +375,7 @@ async def update( self, resource_group_name: str, activity_log_alert_name: str, - activity_log_alert_patch: Union[_models.ActivityLogAlertResourcePatch, IO], + activity_log_alert_patch: Union[_models.ActivityLogAlertResourcePatch, IO[bytes]], **kwargs: Any ) -> _models.ActivityLogAlertResource: """Updates an existing ActivityLogAlertResource's tags. To update other fields use the @@ -411,18 +387,14 @@ async def update( :param activity_log_alert_name: The name of the activity log alert. Required. :type activity_log_alert_name: str :param activity_log_alert_patch: Parameters supplied to the operation. Is either a - ActivityLogAlertResourcePatch type or a IO type. Required. + ActivityLogAlertResourcePatch type or a IO[bytes] type. Required. :type activity_log_alert_patch: - ~azure.mgmt.monitor.v2017_03_01_preview.models.ActivityLogAlertResourcePatch 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 + ~azure.mgmt.monitor.v2017_03_01_preview.models.ActivityLogAlertResourcePatch or IO[bytes] :return: ActivityLogAlertResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2017_03_01_preview.models.ActivityLogAlertResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -433,19 +405,21 @@ async def update( _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", "2017-03-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2017-03-01-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ActivityLogAlertResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(activity_log_alert_patch, (IO, bytes)): + if isinstance(activity_log_alert_patch, (IOBase, bytes)): _content = activity_log_alert_patch else: _json = self._serialize.body(activity_log_alert_patch, "ActivityLogAlertResourcePatch") - request = build_update_request( + _request = build_update_request( resource_group_name=resource_group_name, activity_log_alert_name=activity_log_alert_name, subscription_id=self._config.subscription_id, @@ -453,16 +427,14 @@ async def update( 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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -472,22 +444,18 @@ async def update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ActivityLogAlertResource", pipeline_response) + deserialized = self._deserialize("ActivityLogAlertResource", 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.insights/activityLogAlerts/{activityLogAlertName}" - } + return deserialized # type: ignore @distributed_trace def list_by_subscription_id(self, **kwargs: Any) -> AsyncIterable["_models.ActivityLogAlertResource"]: + # pylint: disable=line-too-long """Get a list of all activity log alerts in a subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ActivityLogAlertResource or the result of cls(response) :rtype: @@ -497,10 +465,12 @@ def list_by_subscription_id(self, **kwargs: Any) -> AsyncIterable["_models.Activ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-03-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2017-03-01-preview") + ) cls: ClsType[_models.ActivityLogAlertList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -511,15 +481,13 @@ def list_by_subscription_id(self, **kwargs: Any) -> AsyncIterable["_models.Activ def prepare_request(next_link=None): if not next_link: - request = build_list_by_subscription_id_request( + _request = build_list_by_subscription_id_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_subscription_id.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -530,14 +498,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("ActivityLogAlertList", pipeline_response) @@ -547,11 +514,11 @@ async def extract_data(pipeline_response): return None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -564,20 +531,16 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_by_subscription_id.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/microsoft.insights/activityLogAlerts" - } - @distributed_trace def list_by_resource_group( self, resource_group_name: str, **kwargs: Any ) -> AsyncIterable["_models.ActivityLogAlertResource"]: + # pylint: disable=line-too-long """Get a list of all activity log alerts in a resource group. :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ActivityLogAlertResource or the result of cls(response) :rtype: @@ -587,10 +550,12 @@ def list_by_resource_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-03-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2017-03-01-preview") + ) cls: ClsType[_models.ActivityLogAlertList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -601,16 +566,14 @@ 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_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -621,14 +584,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("ActivityLogAlertList", pipeline_response) @@ -638,11 +600,11 @@ async def extract_data(pipeline_response): return None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -654,7 +616,3 @@ async def get_next(next_link=None): return pipeline_response return AsyncItemPaged(get_next, extract_data) - - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/activityLogAlerts" - } diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_03_01_preview/models/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_03_01_preview/models/__init__.py index 0ca76e5f619d..6bb0d504170a 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_03_01_preview/models/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_03_01_preview/models/__init__.py @@ -5,18 +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 ._models_py3 import ActivityLogAlertActionGroup -from ._models_py3 import ActivityLogAlertActionList -from ._models_py3 import ActivityLogAlertAllOfCondition -from ._models_py3 import ActivityLogAlertLeafCondition -from ._models_py3 import ActivityLogAlertList -from ._models_py3 import ActivityLogAlertResource -from ._models_py3 import ActivityLogAlertResourcePatch -from ._models_py3 import ErrorResponse -from ._models_py3 import Resource +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models_py3 import ( # type: ignore + ActivityLogAlertActionGroup, + ActivityLogAlertActionList, + ActivityLogAlertAllOfCondition, + ActivityLogAlertLeafCondition, + ActivityLogAlertList, + ActivityLogAlertResource, + ActivityLogAlertResourcePatch, + ErrorResponse, + Resource, +) from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ @@ -30,5 +39,5 @@ "ErrorResponse", "Resource", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_03_01_preview/models/_models_py3.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_03_01_preview/models/_models_py3.py index b0c4fb509c4a..40bc90d72b43 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_03_01_preview/models/_models_py3.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_03_01_preview/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. @@ -12,14 +11,13 @@ from ... import _serialization if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from .. import models as _models class ActivityLogAlertActionGroup(_serialization.Model): """A pointer to an Azure Action Group. - 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 action_group_id: The resourceId of the action group. This cannot be null or empty. Required. @@ -81,7 +79,7 @@ def __init__( class ActivityLogAlertAllOfCondition(_serialization.Model): """An Activity Log alert condition that is met when all its member conditions are met. - 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 all_of: The list of activity log alert conditions. Required. :vartype all_of: @@ -109,7 +107,7 @@ def __init__(self, *, all_of: List["_models.ActivityLogAlertLeafCondition"], **k class ActivityLogAlertLeafCondition(_serialization.Model): """An Activity Log alert condition that is met by comparing an activity log field and value. - 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 field: The name of the field that this condition will examine. The possible values for this field are (case-insensitive): 'resourceId', 'category', 'caller', 'level', @@ -172,7 +170,7 @@ class Resource(_serialization.Model): 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: Azure resource Id. :vartype id: str @@ -221,7 +219,7 @@ class ActivityLogAlertResource(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: Azure resource Id. :vartype id: str @@ -314,7 +312,7 @@ class ActivityLogAlertResourcePatch(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: Azure resource Id. :vartype id: str diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_03_01_preview/operations/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_03_01_preview/operations/__init__.py index b024a2af0682..41e2b371bc7a 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_03_01_preview/operations/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_03_01_preview/operations/__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 ._activity_log_alerts_operations import ActivityLogAlertsOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._activity_log_alerts_operations import ActivityLogAlertsOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ "ActivityLogAlertsOperations", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_03_01_preview/operations/_activity_log_alerts_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_03_01_preview/operations/_activity_log_alerts_operations.py index 850077311db8..2c27434e4dfb 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_03_01_preview/operations/_activity_log_alerts_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_03_01_preview/operations/_activity_log_alerts_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload import urllib.parse @@ -19,16 +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, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -59,7 +62,7 @@ def build_create_or_update_request( "activityLogAlertName": _SERIALIZER.url("activity_log_alert_name", activity_log_alert_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -94,7 +97,7 @@ def build_get_request( "activityLogAlertName": _SERIALIZER.url("activity_log_alert_name", activity_log_alert_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -127,7 +130,7 @@ def build_delete_request( "activityLogAlertName": _SERIALIZER.url("activity_log_alert_name", activity_log_alert_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -161,7 +164,7 @@ def build_update_request( "activityLogAlertName": _SERIALIZER.url("activity_log_alert_name", activity_log_alert_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -187,7 +190,7 @@ def build_list_by_subscription_id_request(subscription_id: str, **kwargs: Any) - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -217,7 +220,7 @@ def build_list_by_resource_group_request(resource_group_name: str, subscription_ ), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -246,6 +249,7 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @overload def create_or_update( @@ -270,7 +274,6 @@ def create_or_update( :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: ActivityLogAlertResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2017_03_01_preview.models.ActivityLogAlertResource :raises ~azure.core.exceptions.HttpResponseError: @@ -281,7 +284,7 @@ def create_or_update( self, resource_group_name: str, activity_log_alert_name: str, - activity_log_alert: IO, + activity_log_alert: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -294,11 +297,10 @@ def create_or_update( :param activity_log_alert_name: The name of the activity log alert. Required. :type activity_log_alert_name: str :param activity_log_alert: The activity log alert to create or use for the update. Required. - :type activity_log_alert: IO + :type activity_log_alert: 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: ActivityLogAlertResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2017_03_01_preview.models.ActivityLogAlertResource :raises ~azure.core.exceptions.HttpResponseError: @@ -309,7 +311,7 @@ def create_or_update( self, resource_group_name: str, activity_log_alert_name: str, - activity_log_alert: Union[_models.ActivityLogAlertResource, IO], + activity_log_alert: Union[_models.ActivityLogAlertResource, IO[bytes]], **kwargs: Any ) -> _models.ActivityLogAlertResource: """Create a new activity log alert or update an existing one. @@ -320,18 +322,14 @@ def create_or_update( :param activity_log_alert_name: The name of the activity log alert. Required. :type activity_log_alert_name: str :param activity_log_alert: The activity log alert to create or use for the update. Is either a - ActivityLogAlertResource type or a IO type. Required. + ActivityLogAlertResource type or a IO[bytes] type. Required. :type activity_log_alert: - ~azure.mgmt.monitor.v2017_03_01_preview.models.ActivityLogAlertResource 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 + ~azure.mgmt.monitor.v2017_03_01_preview.models.ActivityLogAlertResource or IO[bytes] :return: ActivityLogAlertResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2017_03_01_preview.models.ActivityLogAlertResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -342,19 +340,21 @@ def create_or_update( _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", "2017-03-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2017-03-01-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ActivityLogAlertResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(activity_log_alert, (IO, bytes)): + if isinstance(activity_log_alert, (IOBase, bytes)): _content = activity_log_alert else: _json = self._serialize.body(activity_log_alert, "ActivityLogAlertResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, activity_log_alert_name=activity_log_alert_name, subscription_id=self._config.subscription_id, @@ -362,16 +362,14 @@ def create_or_update( 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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -381,21 +379,13 @@ def create_or_update( 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("ActivityLogAlertResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("ActivityLogAlertResource", pipeline_response) + deserialized = self._deserialize("ActivityLogAlertResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/activityLogAlerts/{activityLogAlertName}" - } - @distributed_trace def get( self, resource_group_name: str, activity_log_alert_name: str, **kwargs: Any @@ -407,12 +397,11 @@ def get( :type resource_group_name: str :param activity_log_alert_name: The name of the activity log alert. Required. :type activity_log_alert_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ActivityLogAlertResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2017_03_01_preview.models.ActivityLogAlertResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -423,24 +412,24 @@ def get( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-03-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2017-03-01-preview") + ) cls: ClsType[_models.ActivityLogAlertResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, activity_log_alert_name=activity_log_alert_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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -450,16 +439,12 @@ def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ActivityLogAlertResource", pipeline_response) + deserialized = self._deserialize("ActivityLogAlertResource", 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.insights/activityLogAlerts/{activityLogAlertName}" - } + return deserialized # type: ignore @distributed_trace def delete( # pylint: disable=inconsistent-return-statements @@ -472,12 +457,11 @@ def delete( # pylint: disable=inconsistent-return-statements :type resource_group_name: str :param activity_log_alert_name: The name of the activity log alert. Required. :type activity_log_alert_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, @@ -488,24 +472,24 @@ def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-03-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2017-03-01-preview") + ) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, activity_log_alert_name=activity_log_alert_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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -516,11 +500,7 @@ def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/activityLogAlerts/{activityLogAlertName}" - } + return cls(pipeline_response, None, {}) # type: ignore @overload def update( @@ -546,7 +526,6 @@ def update( :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: ActivityLogAlertResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2017_03_01_preview.models.ActivityLogAlertResource :raises ~azure.core.exceptions.HttpResponseError: @@ -557,7 +536,7 @@ def update( self, resource_group_name: str, activity_log_alert_name: str, - activity_log_alert_patch: IO, + activity_log_alert_patch: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -571,11 +550,10 @@ def update( :param activity_log_alert_name: The name of the activity log alert. Required. :type activity_log_alert_name: str :param activity_log_alert_patch: Parameters supplied to the operation. Required. - :type activity_log_alert_patch: IO + :type activity_log_alert_patch: 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: ActivityLogAlertResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2017_03_01_preview.models.ActivityLogAlertResource :raises ~azure.core.exceptions.HttpResponseError: @@ -586,7 +564,7 @@ def update( self, resource_group_name: str, activity_log_alert_name: str, - activity_log_alert_patch: Union[_models.ActivityLogAlertResourcePatch, IO], + activity_log_alert_patch: Union[_models.ActivityLogAlertResourcePatch, IO[bytes]], **kwargs: Any ) -> _models.ActivityLogAlertResource: """Updates an existing ActivityLogAlertResource's tags. To update other fields use the @@ -598,18 +576,14 @@ def update( :param activity_log_alert_name: The name of the activity log alert. Required. :type activity_log_alert_name: str :param activity_log_alert_patch: Parameters supplied to the operation. Is either a - ActivityLogAlertResourcePatch type or a IO type. Required. + ActivityLogAlertResourcePatch type or a IO[bytes] type. Required. :type activity_log_alert_patch: - ~azure.mgmt.monitor.v2017_03_01_preview.models.ActivityLogAlertResourcePatch 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 + ~azure.mgmt.monitor.v2017_03_01_preview.models.ActivityLogAlertResourcePatch or IO[bytes] :return: ActivityLogAlertResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2017_03_01_preview.models.ActivityLogAlertResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -620,19 +594,21 @@ def update( _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", "2017-03-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2017-03-01-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ActivityLogAlertResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(activity_log_alert_patch, (IO, bytes)): + if isinstance(activity_log_alert_patch, (IOBase, bytes)): _content = activity_log_alert_patch else: _json = self._serialize.body(activity_log_alert_patch, "ActivityLogAlertResourcePatch") - request = build_update_request( + _request = build_update_request( resource_group_name=resource_group_name, activity_log_alert_name=activity_log_alert_name, subscription_id=self._config.subscription_id, @@ -640,16 +616,14 @@ def update( 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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -659,22 +633,17 @@ def update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ActivityLogAlertResource", pipeline_response) + deserialized = self._deserialize("ActivityLogAlertResource", 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.insights/activityLogAlerts/{activityLogAlertName}" - } + return deserialized # type: ignore @distributed_trace def list_by_subscription_id(self, **kwargs: Any) -> Iterable["_models.ActivityLogAlertResource"]: """Get a list of all activity log alerts in a subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ActivityLogAlertResource or the result of cls(response) :rtype: @@ -684,10 +653,12 @@ def list_by_subscription_id(self, **kwargs: Any) -> Iterable["_models.ActivityLo _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-03-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2017-03-01-preview") + ) cls: ClsType[_models.ActivityLogAlertList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -698,15 +669,13 @@ def list_by_subscription_id(self, **kwargs: Any) -> Iterable["_models.ActivityLo def prepare_request(next_link=None): if not next_link: - request = build_list_by_subscription_id_request( + _request = build_list_by_subscription_id_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_subscription_id.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -717,14 +686,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("ActivityLogAlertList", pipeline_response) @@ -734,11 +702,11 @@ def extract_data(pipeline_response): return None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -751,10 +719,6 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_by_subscription_id.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/microsoft.insights/activityLogAlerts" - } - @distributed_trace def list_by_resource_group( self, resource_group_name: str, **kwargs: Any @@ -764,7 +728,6 @@ def list_by_resource_group( :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ActivityLogAlertResource or the result of cls(response) :rtype: @@ -774,10 +737,12 @@ def list_by_resource_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-03-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2017-03-01-preview") + ) cls: ClsType[_models.ActivityLogAlertList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -788,16 +753,14 @@ 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_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -808,14 +771,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("ActivityLogAlertList", pipeline_response) @@ -825,11 +787,11 @@ def extract_data(pipeline_response): return None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -841,7 +803,3 @@ def get_next(next_link=None): return pipeline_response return ItemPaged(get_next, extract_data) - - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/activityLogAlerts" - } diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_04_01/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_04_01/__init__.py index 2c7733bfd566..42cc62301757 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_04_01/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_04_01/__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 ._monitor_management_client import MonitorManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._monitor_management_client import MonitorManagementClient # type: ignore from ._version import VERSION __version__ = VERSION try: from ._patch import __all__ as _patch_all - from ._patch import * # 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__ = [ "MonitorManagementClient", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_04_01/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_04_01/_configuration.py index 9cbb2f0deda3..b2571c0ecb90 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_04_01/_configuration.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_04_01/_configuration.py @@ -8,18 +8,16 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy from ._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MonitorManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class MonitorManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for MonitorManagementClient. Note that all parameters used to create this instance are saved as instance @@ -35,7 +33,6 @@ class MonitorManagementClientConfiguration(Configuration): # pylint: disable=to """ def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: - super(MonitorManagementClientConfiguration, self).__init__(**kwargs) api_version: str = kwargs.pop("api_version", "2017-04-01") if credential is None: @@ -48,6 +45,7 @@ def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-monitor/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -56,9 +54,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.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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_04_01/_metadata.json b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_04_01/_metadata.json index 6eaf6b014379..90e567f33c78 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_04_01/_metadata.json +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_04_01/_metadata.json @@ -8,10 +8,10 @@ "host_value": "\"https://management.azure.com\"", "parameterized_host_template": null, "azure_arm": true, - "has_lro_operations": false, + "has_public_lro_operations": false, "client_side_validation": false, - "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"sdkcore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMAutoResourceProviderRegistrationPolicy\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}, \"stdlib\": {\"typing_extensions\": [\"Self\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"sdkcore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"AsyncARMAutoResourceProviderRegistrationPolicy\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}, \"stdlib\": {\"typing_extensions\": [\"Self\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "global_parameters": { "sync": { @@ -101,8 +101,8 @@ "credential_scopes": ["https://management.azure.com/.default"], "credential_call_sync": "ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", "credential_call_async": "AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", - "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "sync_imports": "{\"regular\": {\"sdkcore\": {\"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"regular\": {\"sdkcore\": {\"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "operation_groups": { "action_groups": "ActionGroupsOperations", diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_04_01/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_04_01/_monitor_management_client.py index 6ce7c69392ab..813398e0f82b 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_04_01/_monitor_management_client.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_04_01/_monitor_management_client.py @@ -8,9 +8,12 @@ from copy import deepcopy from typing import Any, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient +from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy from . import models as _models from .._serialization import Deserializer, Serializer @@ -18,11 +21,10 @@ from .operations import ActionGroupsOperations, ActivityLogAlertsOperations if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MonitorManagementClient: # pylint: disable=client-accepts-api-version-keyword +class MonitorManagementClient: """Monitor Management Client. :ivar action_groups: ActionGroupsOperations operations @@ -51,18 +53,38 @@ def __init__( self._config = MonitorManagementClientConfiguration( credential=credential, subscription_id=subscription_id, **kwargs ) - self._client: ARMPipelineClient = ARMPipelineClient(base_url=base_url, config=self._config, **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), + 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=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.action_groups = ActionGroupsOperations(self._client, self._config, self._serialize, self._deserialize) + self.action_groups = ActionGroupsOperations( + self._client, self._config, self._serialize, self._deserialize, "2017-04-01" + ) self.activity_log_alerts = ActivityLogAlertsOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2017-04-01" ) - 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 @@ -82,12 +104,12 @@ 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) -> None: self._client.close() - def __enter__(self) -> "MonitorManagementClient": + def __enter__(self) -> Self: self._client.__enter__() return self diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_04_01/_vendor.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_04_01/_vendor.py deleted file mode 100644 index bd0df84f5319..000000000000 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_04_01/_vendor.py +++ /dev/null @@ -1,30 +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 typing import List, cast - -from azure.core.pipeline.transport import HttpRequest - - -def _convert_request(request, files=None): - data = request.content if not files else None - request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) - if files: - request.set_formdata_body(files) - return request - - -def _format_url_section(template, **kwargs): - components = template.split("/") - while components: - try: - return template.format(**kwargs) - except KeyError as key: - # Need the cast, as for some reasons "split" is typed as list[str | Any] - formatted_components = cast(List[str], template.split("/")) - components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] - template = "/".join(components) diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_04_01/_version.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_04_01/_version.py index 394ee7c0c03c..e5754a47ce68 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_04_01/_version.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_04_01/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "6.0.2" +VERSION = "1.0.0b1" diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_04_01/aio/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_04_01/aio/__init__.py index 2c151bb41c19..3df30ff42149 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_04_01/aio/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_04_01/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 ._monitor_management_client import MonitorManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._monitor_management_client import MonitorManagementClient # type: ignore try: from ._patch import __all__ as _patch_all - from ._patch import * # 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__ = [ "MonitorManagementClient", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_04_01/aio/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_04_01/aio/_configuration.py index 8a6aabc450e2..0f842dda4d8c 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_04_01/aio/_configuration.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_04_01/aio/_configuration.py @@ -8,18 +8,16 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy from .._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MonitorManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class MonitorManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for MonitorManagementClient. Note that all parameters used to create this instance are saved as instance @@ -35,7 +33,6 @@ class MonitorManagementClientConfiguration(Configuration): # pylint: disable=to """ def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: - super(MonitorManagementClientConfiguration, self).__init__(**kwargs) api_version: str = kwargs.pop("api_version", "2017-04-01") if credential is None: @@ -48,6 +45,7 @@ def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **k self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-monitor/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -56,9 +54,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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_04_01/aio/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_04_01/aio/_monitor_management_client.py index e0679b80cee6..b3faf0745608 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_04_01/aio/_monitor_management_client.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_04_01/aio/_monitor_management_client.py @@ -8,9 +8,12 @@ from copy import deepcopy from typing import Any, Awaitable, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient +from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy from .. import models as _models from ..._serialization import Deserializer, Serializer @@ -18,11 +21,10 @@ from .operations import ActionGroupsOperations, ActivityLogAlertsOperations if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MonitorManagementClient: # pylint: disable=client-accepts-api-version-keyword +class MonitorManagementClient: """Monitor Management Client. :ivar action_groups: ActionGroupsOperations operations @@ -51,18 +53,40 @@ def __init__( self._config = MonitorManagementClientConfiguration( credential=credential, subscription_id=subscription_id, **kwargs ) - self._client: AsyncARMPipelineClient = AsyncARMPipelineClient(base_url=base_url, config=self._config, **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=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.action_groups = ActionGroupsOperations(self._client, self._config, self._serialize, self._deserialize) + self.action_groups = ActionGroupsOperations( + self._client, self._config, self._serialize, self._deserialize, "2017-04-01" + ) self.activity_log_alerts = ActivityLogAlertsOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2017-04-01" ) - 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 @@ -82,12 +106,12 @@ 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) -> "MonitorManagementClient": + async def __aenter__(self) -> Self: await self._client.__aenter__() return self diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_04_01/aio/operations/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_04_01/aio/operations/__init__.py index 204d3d1aa9c7..7bba15ade70c 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_04_01/aio/operations/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_04_01/aio/operations/__init__.py @@ -5,17 +5,23 @@ # 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 ._action_groups_operations import ActionGroupsOperations -from ._activity_log_alerts_operations import ActivityLogAlertsOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._action_groups_operations import ActionGroupsOperations # type: ignore +from ._activity_log_alerts_operations import ActivityLogAlertsOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ "ActionGroupsOperations", "ActivityLogAlertsOperations", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_04_01/aio/operations/_action_groups_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_04_01/aio/operations/_action_groups_operations.py index b7e49ee0bde7..8abdfd445c61 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_04_01/aio/operations/_action_groups_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_04_01/aio/operations/_action_groups_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload import urllib.parse @@ -19,15 +20,13 @@ 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 ...operations._action_groups_operations import ( build_create_or_update_request, build_delete_request, @@ -38,6 +37,10 @@ build_update_request, ) +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -60,6 +63,7 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @overload async def create_or_update( @@ -83,7 +87,6 @@ async def create_or_update( :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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2017_04_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -94,7 +97,7 @@ async def create_or_update( self, resource_group_name: str, action_group_name: str, - action_group: IO, + action_group: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -107,11 +110,10 @@ async def create_or_update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group: The action group to create or use for the update. Required. - :type action_group: IO + :type action_group: 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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2017_04_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -122,7 +124,7 @@ async def create_or_update( self, resource_group_name: str, action_group_name: str, - action_group: Union[_models.ActionGroupResource, IO], + action_group: Union[_models.ActionGroupResource, IO[bytes]], **kwargs: Any ) -> _models.ActionGroupResource: """Create a new action group or update an existing one. @@ -133,17 +135,13 @@ async def create_or_update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group: The action group to create or use for the update. Is either a - ActionGroupResource type or a IO type. Required. - :type action_group: ~azure.mgmt.monitor.v2017_04_01.models.ActionGroupResource 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 + ActionGroupResource type or a IO[bytes] type. Required. + :type action_group: ~azure.mgmt.monitor.v2017_04_01.models.ActionGroupResource or IO[bytes] :return: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2017_04_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -154,19 +152,19 @@ async def create_or_update( _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", "2017-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2017-04-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ActionGroupResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(action_group, (IO, bytes)): + if isinstance(action_group, (IOBase, bytes)): _content = action_group else: _json = self._serialize.body(action_group, "ActionGroupResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, action_group_name=action_group_name, subscription_id=self._config.subscription_id, @@ -174,16 +172,14 @@ async def create_or_update( 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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -193,21 +189,13 @@ async def create_or_update( 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("ActionGroupResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("ActionGroupResource", pipeline_response) + deserialized = self._deserialize("ActionGroupResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/actionGroups/{actionGroupName}" - } - @distributed_trace_async async def get(self, resource_group_name: str, action_group_name: str, **kwargs: Any) -> _models.ActionGroupResource: """Get an action group. @@ -217,12 +205,11 @@ async def get(self, resource_group_name: str, action_group_name: str, **kwargs: :type resource_group_name: str :param action_group_name: The name of the action group. Required. :type action_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2017_04_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -233,24 +220,22 @@ async def get(self, resource_group_name: str, action_group_name: str, **kwargs: _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2017-04-01")) cls: ClsType[_models.ActionGroupResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, action_group_name=action_group_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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -260,21 +245,15 @@ async def get(self, resource_group_name: str, action_group_name: str, **kwargs: error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ActionGroupResource", pipeline_response) + deserialized = self._deserialize("ActionGroupResource", 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.insights/actionGroups/{actionGroupName}" - } + return deserialized # type: ignore @distributed_trace_async - async def delete( # pylint: disable=inconsistent-return-statements - self, resource_group_name: str, action_group_name: str, **kwargs: Any - ) -> None: + async def delete(self, resource_group_name: str, action_group_name: str, **kwargs: Any) -> None: """Delete an action group. :param resource_group_name: The name of the resource group. The name is case insensitive. @@ -282,12 +261,11 @@ async def delete( # pylint: disable=inconsistent-return-statements :type resource_group_name: str :param action_group_name: The name of the action group. Required. :type action_group_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, @@ -298,24 +276,22 @@ async def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2017-04-01")) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, action_group_name=action_group_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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -326,11 +302,7 @@ async def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/actionGroups/{actionGroupName}" - } + return cls(pipeline_response, None, {}) # type: ignore @overload async def update( @@ -354,7 +326,6 @@ async def update( :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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2017_04_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -365,7 +336,7 @@ async def update( self, resource_group_name: str, action_group_name: str, - action_group_patch: IO, + action_group_patch: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -378,11 +349,10 @@ async def update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group_patch: Parameters supplied to the operation. Required. - :type action_group_patch: IO + :type action_group_patch: 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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2017_04_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -393,7 +363,7 @@ async def update( self, resource_group_name: str, action_group_name: str, - action_group_patch: Union[_models.ActionGroupPatchBody, IO], + action_group_patch: Union[_models.ActionGroupPatchBody, IO[bytes]], **kwargs: Any ) -> _models.ActionGroupResource: """Updates an existing action group's tags. To update other fields use the CreateOrUpdate method. @@ -404,17 +374,14 @@ async def update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group_patch: Parameters supplied to the operation. Is either a - ActionGroupPatchBody type or a IO type. Required. - :type action_group_patch: ~azure.mgmt.monitor.v2017_04_01.models.ActionGroupPatchBody 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 + ActionGroupPatchBody type or a IO[bytes] type. Required. + :type action_group_patch: ~azure.mgmt.monitor.v2017_04_01.models.ActionGroupPatchBody or + IO[bytes] :return: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2017_04_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -425,19 +392,19 @@ async def update( _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", "2017-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2017-04-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ActionGroupResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(action_group_patch, (IO, bytes)): + if isinstance(action_group_patch, (IOBase, bytes)): _content = action_group_patch else: _json = self._serialize.body(action_group_patch, "ActionGroupPatchBody") - request = build_update_request( + _request = build_update_request( resource_group_name=resource_group_name, action_group_name=action_group_name, subscription_id=self._config.subscription_id, @@ -445,16 +412,14 @@ async def update( 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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -464,22 +429,17 @@ async def update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ActionGroupResource", pipeline_response) + deserialized = self._deserialize("ActionGroupResource", 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.insights/actionGroups/{actionGroupName}" - } + return deserialized # type: ignore @distributed_trace def list_by_subscription_id(self, **kwargs: Any) -> AsyncIterable["_models.ActionGroupResource"]: """Get a list of all action groups in a subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ActionGroupResource or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.monitor.v2017_04_01.models.ActionGroupResource] @@ -488,10 +448,10 @@ def list_by_subscription_id(self, **kwargs: Any) -> AsyncIterable["_models.Actio _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2017-04-01")) cls: ClsType[_models.ActionGroupList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -502,15 +462,13 @@ def list_by_subscription_id(self, **kwargs: Any) -> AsyncIterable["_models.Actio def prepare_request(next_link=None): if not next_link: - request = build_list_by_subscription_id_request( + _request = build_list_by_subscription_id_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_subscription_id.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -521,14 +479,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("ActionGroupList", pipeline_response) @@ -538,11 +495,11 @@ async def extract_data(pipeline_response): return None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -555,10 +512,6 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_by_subscription_id.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/microsoft.insights/actionGroups" - } - @distributed_trace def list_by_resource_group( self, resource_group_name: str, **kwargs: Any @@ -568,7 +521,6 @@ def list_by_resource_group( :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ActionGroupResource or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.monitor.v2017_04_01.models.ActionGroupResource] @@ -577,10 +529,10 @@ def list_by_resource_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2017-04-01")) cls: ClsType[_models.ActionGroupList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -591,16 +543,14 @@ 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_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -611,14 +561,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("ActionGroupList", pipeline_response) @@ -628,11 +577,11 @@ async def extract_data(pipeline_response): return None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -645,12 +594,8 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/actionGroups" - } - @overload - async def enable_receiver( # pylint: disable=inconsistent-return-statements + async def enable_receiver( self, resource_group_name: str, action_group_name: str, @@ -672,18 +617,17 @@ async def enable_receiver( # pylint: disable=inconsistent-return-statements :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: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def enable_receiver( # pylint: disable=inconsistent-return-statements + async def enable_receiver( self, resource_group_name: str, action_group_name: str, - enable_request: IO, + enable_request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -697,22 +641,21 @@ async def enable_receiver( # pylint: disable=inconsistent-return-statements :param action_group_name: The name of the action group. Required. :type action_group_name: str :param enable_request: The receiver to re-enable. Required. - :type enable_request: IO + :type enable_request: 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: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async - async def enable_receiver( # pylint: disable=inconsistent-return-statements + async def enable_receiver( self, resource_group_name: str, action_group_name: str, - enable_request: Union[_models.EnableRequest, IO], + enable_request: Union[_models.EnableRequest, IO[bytes]], **kwargs: Any ) -> None: """Enable a receiver in an action group. This changes the receiver's status from Disabled to @@ -723,18 +666,14 @@ async def enable_receiver( # pylint: disable=inconsistent-return-statements :type resource_group_name: str :param action_group_name: The name of the action group. Required. :type action_group_name: str - :param enable_request: The receiver to re-enable. Is either a EnableRequest type or a IO type. - Required. - :type enable_request: ~azure.mgmt.monitor.v2017_04_01.models.EnableRequest 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 + :param enable_request: The receiver to re-enable. Is either a EnableRequest type or a IO[bytes] + type. Required. + :type enable_request: ~azure.mgmt.monitor.v2017_04_01.models.EnableRequest or IO[bytes] :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, @@ -745,19 +684,19 @@ async def enable_receiver( # pylint: disable=inconsistent-return-statements _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", "2017-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2017-04-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[None] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(enable_request, (IO, bytes)): + if isinstance(enable_request, (IOBase, bytes)): _content = enable_request else: _json = self._serialize.body(enable_request, "EnableRequest") - request = build_enable_receiver_request( + _request = build_enable_receiver_request( resource_group_name=resource_group_name, action_group_name=action_group_name, subscription_id=self._config.subscription_id, @@ -765,16 +704,14 @@ async def enable_receiver( # pylint: disable=inconsistent-return-statements content_type=content_type, json=_json, content=_content, - template_url=self.enable_receiver.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -785,8 +722,4 @@ async def enable_receiver( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - enable_receiver.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/actionGroups/{actionGroupName}/subscribe" - } + return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_04_01/aio/operations/_activity_log_alerts_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_04_01/aio/operations/_activity_log_alerts_operations.py index 6817f7dda629..fad57cb5f7a4 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_04_01/aio/operations/_activity_log_alerts_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_04_01/aio/operations/_activity_log_alerts_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload import urllib.parse @@ -19,15 +20,13 @@ 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 ...operations._activity_log_alerts_operations import ( build_create_or_update_request, build_delete_request, @@ -37,6 +36,10 @@ build_update_request, ) +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -59,6 +62,7 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @overload async def create_or_update( @@ -82,7 +86,6 @@ async def create_or_update( :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: ActivityLogAlertResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2017_04_01.models.ActivityLogAlertResource :raises ~azure.core.exceptions.HttpResponseError: @@ -93,7 +96,7 @@ async def create_or_update( self, resource_group_name: str, activity_log_alert_name: str, - activity_log_alert: IO, + activity_log_alert: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -106,11 +109,10 @@ async def create_or_update( :param activity_log_alert_name: The name of the activity log alert. Required. :type activity_log_alert_name: str :param activity_log_alert: The activity log alert to create or use for the update. Required. - :type activity_log_alert: IO + :type activity_log_alert: 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: ActivityLogAlertResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2017_04_01.models.ActivityLogAlertResource :raises ~azure.core.exceptions.HttpResponseError: @@ -121,7 +123,7 @@ async def create_or_update( self, resource_group_name: str, activity_log_alert_name: str, - activity_log_alert: Union[_models.ActivityLogAlertResource, IO], + activity_log_alert: Union[_models.ActivityLogAlertResource, IO[bytes]], **kwargs: Any ) -> _models.ActivityLogAlertResource: """Create a new activity log alert or update an existing one. @@ -132,17 +134,14 @@ async def create_or_update( :param activity_log_alert_name: The name of the activity log alert. Required. :type activity_log_alert_name: str :param activity_log_alert: The activity log alert to create or use for the update. Is either a - ActivityLogAlertResource type or a IO type. Required. - :type activity_log_alert: ~azure.mgmt.monitor.v2017_04_01.models.ActivityLogAlertResource 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 + ActivityLogAlertResource type or a IO[bytes] type. Required. + :type activity_log_alert: ~azure.mgmt.monitor.v2017_04_01.models.ActivityLogAlertResource or + IO[bytes] :return: ActivityLogAlertResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2017_04_01.models.ActivityLogAlertResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -153,19 +152,19 @@ async def create_or_update( _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", "2017-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2017-04-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ActivityLogAlertResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(activity_log_alert, (IO, bytes)): + if isinstance(activity_log_alert, (IOBase, bytes)): _content = activity_log_alert else: _json = self._serialize.body(activity_log_alert, "ActivityLogAlertResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, activity_log_alert_name=activity_log_alert_name, subscription_id=self._config.subscription_id, @@ -173,16 +172,14 @@ async def create_or_update( 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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -192,21 +189,13 @@ async def create_or_update( 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("ActivityLogAlertResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("ActivityLogAlertResource", pipeline_response) + deserialized = self._deserialize("ActivityLogAlertResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/activityLogAlerts/{activityLogAlertName}" - } - @distributed_trace_async async def get( self, resource_group_name: str, activity_log_alert_name: str, **kwargs: Any @@ -218,12 +207,11 @@ async def get( :type resource_group_name: str :param activity_log_alert_name: The name of the activity log alert. Required. :type activity_log_alert_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ActivityLogAlertResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2017_04_01.models.ActivityLogAlertResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -234,24 +222,22 @@ async def get( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2017-04-01")) cls: ClsType[_models.ActivityLogAlertResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, activity_log_alert_name=activity_log_alert_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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -261,21 +247,15 @@ async def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ActivityLogAlertResource", pipeline_response) + deserialized = self._deserialize("ActivityLogAlertResource", 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.insights/activityLogAlerts/{activityLogAlertName}" - } + return deserialized # type: ignore @distributed_trace_async - async def delete( # pylint: disable=inconsistent-return-statements - self, resource_group_name: str, activity_log_alert_name: str, **kwargs: Any - ) -> None: + async def delete(self, resource_group_name: str, activity_log_alert_name: str, **kwargs: Any) -> None: """Delete an activity log alert. :param resource_group_name: The name of the resource group. The name is case insensitive. @@ -283,12 +263,11 @@ async def delete( # pylint: disable=inconsistent-return-statements :type resource_group_name: str :param activity_log_alert_name: The name of the activity log alert. Required. :type activity_log_alert_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, @@ -299,24 +278,22 @@ async def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2017-04-01")) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, activity_log_alert_name=activity_log_alert_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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -327,11 +304,7 @@ async def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/activityLogAlerts/{activityLogAlertName}" - } + return cls(pipeline_response, None, {}) # type: ignore @overload async def update( @@ -357,7 +330,6 @@ async def update( :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: ActivityLogAlertResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2017_04_01.models.ActivityLogAlertResource :raises ~azure.core.exceptions.HttpResponseError: @@ -368,7 +340,7 @@ async def update( self, resource_group_name: str, activity_log_alert_name: str, - activity_log_alert_patch: IO, + activity_log_alert_patch: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -382,11 +354,10 @@ async def update( :param activity_log_alert_name: The name of the activity log alert. Required. :type activity_log_alert_name: str :param activity_log_alert_patch: Parameters supplied to the operation. Required. - :type activity_log_alert_patch: IO + :type activity_log_alert_patch: 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: ActivityLogAlertResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2017_04_01.models.ActivityLogAlertResource :raises ~azure.core.exceptions.HttpResponseError: @@ -397,7 +368,7 @@ async def update( self, resource_group_name: str, activity_log_alert_name: str, - activity_log_alert_patch: Union[_models.ActivityLogAlertPatchBody, IO], + activity_log_alert_patch: Union[_models.ActivityLogAlertPatchBody, IO[bytes]], **kwargs: Any ) -> _models.ActivityLogAlertResource: """Updates an existing ActivityLogAlertResource's tags. To update other fields use the @@ -409,18 +380,14 @@ async def update( :param activity_log_alert_name: The name of the activity log alert. Required. :type activity_log_alert_name: str :param activity_log_alert_patch: Parameters supplied to the operation. Is either a - ActivityLogAlertPatchBody type or a IO type. Required. + ActivityLogAlertPatchBody type or a IO[bytes] type. Required. :type activity_log_alert_patch: - ~azure.mgmt.monitor.v2017_04_01.models.ActivityLogAlertPatchBody 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 + ~azure.mgmt.monitor.v2017_04_01.models.ActivityLogAlertPatchBody or IO[bytes] :return: ActivityLogAlertResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2017_04_01.models.ActivityLogAlertResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -431,19 +398,19 @@ async def update( _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", "2017-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2017-04-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ActivityLogAlertResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(activity_log_alert_patch, (IO, bytes)): + if isinstance(activity_log_alert_patch, (IOBase, bytes)): _content = activity_log_alert_patch else: _json = self._serialize.body(activity_log_alert_patch, "ActivityLogAlertPatchBody") - request = build_update_request( + _request = build_update_request( resource_group_name=resource_group_name, activity_log_alert_name=activity_log_alert_name, subscription_id=self._config.subscription_id, @@ -451,16 +418,14 @@ async def update( 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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -470,22 +435,17 @@ async def update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ActivityLogAlertResource", pipeline_response) + deserialized = self._deserialize("ActivityLogAlertResource", 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.insights/activityLogAlerts/{activityLogAlertName}" - } + return deserialized # type: ignore @distributed_trace def list_by_subscription_id(self, **kwargs: Any) -> AsyncIterable["_models.ActivityLogAlertResource"]: """Get a list of all activity log alerts in a subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ActivityLogAlertResource or the result of cls(response) :rtype: @@ -495,10 +455,10 @@ def list_by_subscription_id(self, **kwargs: Any) -> AsyncIterable["_models.Activ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2017-04-01")) cls: ClsType[_models.ActivityLogAlertList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -509,15 +469,13 @@ def list_by_subscription_id(self, **kwargs: Any) -> AsyncIterable["_models.Activ def prepare_request(next_link=None): if not next_link: - request = build_list_by_subscription_id_request( + _request = build_list_by_subscription_id_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_subscription_id.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -528,14 +486,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("ActivityLogAlertList", pipeline_response) @@ -545,11 +502,11 @@ async def extract_data(pipeline_response): return None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -562,10 +519,6 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_by_subscription_id.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/microsoft.insights/activityLogAlerts" - } - @distributed_trace def list_by_resource_group( self, resource_group_name: str, **kwargs: Any @@ -575,7 +528,6 @@ def list_by_resource_group( :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ActivityLogAlertResource or the result of cls(response) :rtype: @@ -585,10 +537,10 @@ def list_by_resource_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2017-04-01")) cls: ClsType[_models.ActivityLogAlertList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -599,16 +551,14 @@ 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_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -619,14 +569,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("ActivityLogAlertList", pipeline_response) @@ -636,11 +585,11 @@ async def extract_data(pipeline_response): return None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -652,7 +601,3 @@ async def get_next(next_link=None): return pipeline_response return AsyncItemPaged(get_next, extract_data) - - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/activityLogAlerts" - } diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_04_01/models/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_04_01/models/__init__.py index 353a71918f69..1ba2b856e294 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_04_01/models/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_04_01/models/__init__.py @@ -5,30 +5,41 @@ # 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 ActionGroupList -from ._models_py3 import ActionGroupPatchBody -from ._models_py3 import ActionGroupResource -from ._models_py3 import ActivityLogAlertActionGroup -from ._models_py3 import ActivityLogAlertActionList -from ._models_py3 import ActivityLogAlertAllOfCondition -from ._models_py3 import ActivityLogAlertLeafCondition -from ._models_py3 import ActivityLogAlertList -from ._models_py3 import ActivityLogAlertPatchBody -from ._models_py3 import ActivityLogAlertResource -from ._models_py3 import AutomationRunbookReceiver -from ._models_py3 import AzureAppPushReceiver -from ._models_py3 import EmailReceiver -from ._models_py3 import EnableRequest -from ._models_py3 import ErrorResponse -from ._models_py3 import ItsmReceiver -from ._models_py3 import Resource -from ._models_py3 import SmsReceiver -from ._models_py3 import WebhookReceiver +from typing import TYPE_CHECKING -from ._monitor_management_client_enums import ReceiverStatus +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models_py3 import ( # type: ignore + ActionGroupList, + ActionGroupPatchBody, + ActionGroupResource, + ActivityLogAlertActionGroup, + ActivityLogAlertActionList, + ActivityLogAlertAllOfCondition, + ActivityLogAlertLeafCondition, + ActivityLogAlertList, + ActivityLogAlertPatchBody, + ActivityLogAlertResource, + AutomationRunbookReceiver, + AzureAppPushReceiver, + EmailReceiver, + EnableRequest, + ErrorResponse, + ItsmReceiver, + Resource, + SmsReceiver, + WebhookReceiver, +) + +from ._monitor_management_client_enums import ( # type: ignore + ReceiverStatus, +) from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ @@ -53,5 +64,5 @@ "WebhookReceiver", "ReceiverStatus", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_04_01/models/_models_py3.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_04_01/models/_models_py3.py index 8a9f989dad6b..5dc0d45c0460 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_04_01/models/_models_py3.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_04_01/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. @@ -12,7 +11,6 @@ from ... import _serialization if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from .. import models as _models @@ -81,7 +79,7 @@ class Resource(_serialization.Model): 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: Azure resource Id. :vartype id: str @@ -125,12 +123,12 @@ def __init__(self, *, location: str, tags: Optional[Dict[str, str]] = None, **kw self.tags = tags -class ActionGroupResource(Resource): # pylint: disable=too-many-instance-attributes +class ActionGroupResource(Resource): """An action group 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: Azure resource Id. :vartype id: str @@ -249,7 +247,7 @@ def __init__( class ActivityLogAlertActionGroup(_serialization.Model): """A pointer to an Azure Action Group. - 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 action_group_id: The resourceId of the action group. This cannot be null or empty. Required. @@ -311,7 +309,7 @@ def __init__( class ActivityLogAlertAllOfCondition(_serialization.Model): """An Activity Log alert condition that is met when all its member conditions are met. - 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 all_of: The list of activity log alert conditions. Required. :vartype all_of: list[~azure.mgmt.monitor.v2017_04_01.models.ActivityLogAlertLeafCondition] @@ -337,7 +335,7 @@ def __init__(self, *, all_of: List["_models.ActivityLogAlertLeafCondition"], **k class ActivityLogAlertLeafCondition(_serialization.Model): """An Activity Log alert condition that is met by comparing an activity log field and value. - 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 field: The name of the field that this condition will examine. The possible values for this field are (case-insensitive): 'resourceId', 'category', 'caller', 'level', @@ -440,7 +438,7 @@ class ActivityLogAlertResource(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: Azure resource Id. :vartype id: str @@ -529,7 +527,7 @@ def __init__( class AutomationRunbookReceiver(_serialization.Model): """The Azure Automation Runbook notification receiver. - 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 automation_account_id: The Azure automation account Id which holds this runbook and authenticate to Azure resource. Required. @@ -600,7 +598,7 @@ def __init__( class AzureAppPushReceiver(_serialization.Model): """The Azure mobile App push notification receiver. - 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 name of the Azure mobile app push receiver. Names must be unique across all receivers within an action group. Required. @@ -637,7 +635,7 @@ class EmailReceiver(_serialization.Model): 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 name: The name of the email receiver. Names must be unique across all receivers within an action group. Required. @@ -678,7 +676,7 @@ def __init__(self, *, name: str, email_address: str, **kwargs: Any) -> None: class EnableRequest(_serialization.Model): """Describes a receiver that should be resubscribed. - 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 receiver_name: The name of the receiver to resubscribe. Required. :vartype receiver_name: str @@ -730,7 +728,7 @@ def __init__(self, *, code: Optional[str] = None, message: Optional[str] = None, class ItsmReceiver(_serialization.Model): """An Itsm receiver. - 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 name of the Itsm receiver. Names must be unique across all receivers within an action group. Required. @@ -744,7 +742,7 @@ class ItsmReceiver(_serialization.Model): CreateMultipleWorkItems option will be part of this blob as well. Required. :vartype ticket_configuration: str :ivar region: Region in which workspace resides. Supported - values:'centralindia','japaneast','southeastasia','australiasoutheast','uksouth','westcentralus','canadacentral','eastus','westeurope'. + values:'centralindia','japaneast','southeastasia','australiasoutheast','uksouth','westcentralus','canadacentral','eastus','westeurope'. # pylint: disable=line-too-long Required. :vartype region: str """ @@ -781,7 +779,7 @@ def __init__( CreateMultipleWorkItems option will be part of this blob as well. Required. :paramtype ticket_configuration: str :keyword region: Region in which workspace resides. Supported - values:'centralindia','japaneast','southeastasia','australiasoutheast','uksouth','westcentralus','canadacentral','eastus','westeurope'. + values:'centralindia','japaneast','southeastasia','australiasoutheast','uksouth','westcentralus','canadacentral','eastus','westeurope'. # pylint: disable=line-too-long Required. :paramtype region: str """ @@ -798,7 +796,7 @@ class SmsReceiver(_serialization.Model): 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 name: The name of the SMS receiver. Names must be unique across all receivers within an action group. Required. @@ -846,7 +844,7 @@ def __init__(self, *, name: str, country_code: str, phone_number: str, **kwargs: class WebhookReceiver(_serialization.Model): """A webhook receiver. - 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 name of the webhook receiver. Names must be unique across all receivers within an action group. Required. diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_04_01/operations/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_04_01/operations/__init__.py index 204d3d1aa9c7..7bba15ade70c 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_04_01/operations/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_04_01/operations/__init__.py @@ -5,17 +5,23 @@ # 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 ._action_groups_operations import ActionGroupsOperations -from ._activity_log_alerts_operations import ActivityLogAlertsOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._action_groups_operations import ActionGroupsOperations # type: ignore +from ._activity_log_alerts_operations import ActivityLogAlertsOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ "ActionGroupsOperations", "ActivityLogAlertsOperations", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_04_01/operations/_action_groups_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_04_01/operations/_action_groups_operations.py index ec9b3d745d80..38a78ea9edee 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_04_01/operations/_action_groups_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_04_01/operations/_action_groups_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload import urllib.parse @@ -19,16 +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, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -59,7 +62,7 @@ def build_create_or_update_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -94,7 +97,7 @@ def build_get_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -127,7 +130,7 @@ def build_delete_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -161,7 +164,7 @@ def build_update_request( "actionGroupName": _SERIALIZER.url("action_group_name", action_group_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -187,7 +190,7 @@ def build_list_by_subscription_id_request(subscription_id: str, **kwargs: Any) - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -217,7 +220,7 @@ def build_list_by_resource_group_request(resource_group_name: str, subscription_ "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -251,7 +254,7 @@ def build_enable_receiver_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -282,6 +285,7 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @overload def create_or_update( @@ -305,7 +309,6 @@ def create_or_update( :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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2017_04_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -316,7 +319,7 @@ def create_or_update( self, resource_group_name: str, action_group_name: str, - action_group: IO, + action_group: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -329,11 +332,10 @@ def create_or_update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group: The action group to create or use for the update. Required. - :type action_group: IO + :type action_group: 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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2017_04_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -344,7 +346,7 @@ def create_or_update( self, resource_group_name: str, action_group_name: str, - action_group: Union[_models.ActionGroupResource, IO], + action_group: Union[_models.ActionGroupResource, IO[bytes]], **kwargs: Any ) -> _models.ActionGroupResource: """Create a new action group or update an existing one. @@ -355,17 +357,13 @@ def create_or_update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group: The action group to create or use for the update. Is either a - ActionGroupResource type or a IO type. Required. - :type action_group: ~azure.mgmt.monitor.v2017_04_01.models.ActionGroupResource 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 + ActionGroupResource type or a IO[bytes] type. Required. + :type action_group: ~azure.mgmt.monitor.v2017_04_01.models.ActionGroupResource or IO[bytes] :return: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2017_04_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -376,19 +374,19 @@ def create_or_update( _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", "2017-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2017-04-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ActionGroupResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(action_group, (IO, bytes)): + if isinstance(action_group, (IOBase, bytes)): _content = action_group else: _json = self._serialize.body(action_group, "ActionGroupResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, action_group_name=action_group_name, subscription_id=self._config.subscription_id, @@ -396,16 +394,14 @@ def create_or_update( 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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -415,21 +411,13 @@ def create_or_update( 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("ActionGroupResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("ActionGroupResource", pipeline_response) + deserialized = self._deserialize("ActionGroupResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/actionGroups/{actionGroupName}" - } - @distributed_trace def get(self, resource_group_name: str, action_group_name: str, **kwargs: Any) -> _models.ActionGroupResource: """Get an action group. @@ -439,12 +427,11 @@ def get(self, resource_group_name: str, action_group_name: str, **kwargs: Any) - :type resource_group_name: str :param action_group_name: The name of the action group. Required. :type action_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2017_04_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -455,24 +442,22 @@ def get(self, resource_group_name: str, action_group_name: str, **kwargs: Any) - _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2017-04-01")) cls: ClsType[_models.ActionGroupResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, action_group_name=action_group_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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -482,16 +467,12 @@ def get(self, resource_group_name: str, action_group_name: str, **kwargs: Any) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ActionGroupResource", pipeline_response) + deserialized = self._deserialize("ActionGroupResource", 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.insights/actionGroups/{actionGroupName}" - } + return deserialized # type: ignore @distributed_trace def delete( # pylint: disable=inconsistent-return-statements @@ -504,12 +485,11 @@ def delete( # pylint: disable=inconsistent-return-statements :type resource_group_name: str :param action_group_name: The name of the action group. Required. :type action_group_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, @@ -520,24 +500,22 @@ def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2017-04-01")) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, action_group_name=action_group_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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -548,11 +526,7 @@ def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/actionGroups/{actionGroupName}" - } + return cls(pipeline_response, None, {}) # type: ignore @overload def update( @@ -576,7 +550,6 @@ def update( :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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2017_04_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -587,7 +560,7 @@ def update( self, resource_group_name: str, action_group_name: str, - action_group_patch: IO, + action_group_patch: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -600,11 +573,10 @@ def update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group_patch: Parameters supplied to the operation. Required. - :type action_group_patch: IO + :type action_group_patch: 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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2017_04_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -615,7 +587,7 @@ def update( self, resource_group_name: str, action_group_name: str, - action_group_patch: Union[_models.ActionGroupPatchBody, IO], + action_group_patch: Union[_models.ActionGroupPatchBody, IO[bytes]], **kwargs: Any ) -> _models.ActionGroupResource: """Updates an existing action group's tags. To update other fields use the CreateOrUpdate method. @@ -626,17 +598,14 @@ def update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group_patch: Parameters supplied to the operation. Is either a - ActionGroupPatchBody type or a IO type. Required. - :type action_group_patch: ~azure.mgmt.monitor.v2017_04_01.models.ActionGroupPatchBody 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 + ActionGroupPatchBody type or a IO[bytes] type. Required. + :type action_group_patch: ~azure.mgmt.monitor.v2017_04_01.models.ActionGroupPatchBody or + IO[bytes] :return: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2017_04_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -647,19 +616,19 @@ def update( _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", "2017-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2017-04-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ActionGroupResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(action_group_patch, (IO, bytes)): + if isinstance(action_group_patch, (IOBase, bytes)): _content = action_group_patch else: _json = self._serialize.body(action_group_patch, "ActionGroupPatchBody") - request = build_update_request( + _request = build_update_request( resource_group_name=resource_group_name, action_group_name=action_group_name, subscription_id=self._config.subscription_id, @@ -667,16 +636,14 @@ def update( 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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -686,22 +653,17 @@ def update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ActionGroupResource", pipeline_response) + deserialized = self._deserialize("ActionGroupResource", 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.insights/actionGroups/{actionGroupName}" - } + return deserialized # type: ignore @distributed_trace def list_by_subscription_id(self, **kwargs: Any) -> Iterable["_models.ActionGroupResource"]: """Get a list of all action groups in a subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ActionGroupResource or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.monitor.v2017_04_01.models.ActionGroupResource] @@ -710,10 +672,10 @@ def list_by_subscription_id(self, **kwargs: Any) -> Iterable["_models.ActionGrou _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2017-04-01")) cls: ClsType[_models.ActionGroupList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -724,15 +686,13 @@ def list_by_subscription_id(self, **kwargs: Any) -> Iterable["_models.ActionGrou def prepare_request(next_link=None): if not next_link: - request = build_list_by_subscription_id_request( + _request = build_list_by_subscription_id_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_subscription_id.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -743,14 +703,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("ActionGroupList", pipeline_response) @@ -760,11 +719,11 @@ def extract_data(pipeline_response): return None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -777,10 +736,6 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_by_subscription_id.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/microsoft.insights/actionGroups" - } - @distributed_trace def list_by_resource_group( self, resource_group_name: str, **kwargs: Any @@ -790,7 +745,6 @@ def list_by_resource_group( :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ActionGroupResource or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.monitor.v2017_04_01.models.ActionGroupResource] @@ -799,10 +753,10 @@ def list_by_resource_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2017-04-01")) cls: ClsType[_models.ActionGroupList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -813,16 +767,14 @@ 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_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -833,14 +785,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("ActionGroupList", pipeline_response) @@ -850,11 +801,11 @@ def extract_data(pipeline_response): return None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -867,12 +818,8 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/actionGroups" - } - @overload - def enable_receiver( # pylint: disable=inconsistent-return-statements + def enable_receiver( self, resource_group_name: str, action_group_name: str, @@ -894,18 +841,17 @@ def enable_receiver( # pylint: disable=inconsistent-return-statements :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: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def enable_receiver( # pylint: disable=inconsistent-return-statements + def enable_receiver( self, resource_group_name: str, action_group_name: str, - enable_request: IO, + enable_request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -919,11 +865,10 @@ def enable_receiver( # pylint: disable=inconsistent-return-statements :param action_group_name: The name of the action group. Required. :type action_group_name: str :param enable_request: The receiver to re-enable. Required. - :type enable_request: IO + :type enable_request: 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: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -934,7 +879,7 @@ def enable_receiver( # pylint: disable=inconsistent-return-statements self, resource_group_name: str, action_group_name: str, - enable_request: Union[_models.EnableRequest, IO], + enable_request: Union[_models.EnableRequest, IO[bytes]], **kwargs: Any ) -> None: """Enable a receiver in an action group. This changes the receiver's status from Disabled to @@ -945,18 +890,14 @@ def enable_receiver( # pylint: disable=inconsistent-return-statements :type resource_group_name: str :param action_group_name: The name of the action group. Required. :type action_group_name: str - :param enable_request: The receiver to re-enable. Is either a EnableRequest type or a IO type. - Required. - :type enable_request: ~azure.mgmt.monitor.v2017_04_01.models.EnableRequest 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 + :param enable_request: The receiver to re-enable. Is either a EnableRequest type or a IO[bytes] + type. Required. + :type enable_request: ~azure.mgmt.monitor.v2017_04_01.models.EnableRequest or IO[bytes] :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, @@ -967,19 +908,19 @@ def enable_receiver( # pylint: disable=inconsistent-return-statements _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", "2017-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2017-04-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[None] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(enable_request, (IO, bytes)): + if isinstance(enable_request, (IOBase, bytes)): _content = enable_request else: _json = self._serialize.body(enable_request, "EnableRequest") - request = build_enable_receiver_request( + _request = build_enable_receiver_request( resource_group_name=resource_group_name, action_group_name=action_group_name, subscription_id=self._config.subscription_id, @@ -987,16 +928,14 @@ def enable_receiver( # pylint: disable=inconsistent-return-statements content_type=content_type, json=_json, content=_content, - template_url=self.enable_receiver.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1007,8 +946,4 @@ def enable_receiver( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - enable_receiver.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/actionGroups/{actionGroupName}/subscribe" - } + return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_04_01/operations/_activity_log_alerts_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_04_01/operations/_activity_log_alerts_operations.py index 5ec2a2b958b4..fb814cdf37f3 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_04_01/operations/_activity_log_alerts_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_04_01/operations/_activity_log_alerts_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload import urllib.parse @@ -19,16 +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, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -59,7 +62,7 @@ def build_create_or_update_request( "activityLogAlertName": _SERIALIZER.url("activity_log_alert_name", activity_log_alert_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -94,7 +97,7 @@ def build_get_request( "activityLogAlertName": _SERIALIZER.url("activity_log_alert_name", activity_log_alert_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -127,7 +130,7 @@ def build_delete_request( "activityLogAlertName": _SERIALIZER.url("activity_log_alert_name", activity_log_alert_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -161,7 +164,7 @@ def build_update_request( "activityLogAlertName": _SERIALIZER.url("activity_log_alert_name", activity_log_alert_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -187,7 +190,7 @@ def build_list_by_subscription_id_request(subscription_id: str, **kwargs: Any) - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -217,7 +220,7 @@ def build_list_by_resource_group_request(resource_group_name: str, subscription_ ), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -246,6 +249,7 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @overload def create_or_update( @@ -269,7 +273,6 @@ def create_or_update( :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: ActivityLogAlertResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2017_04_01.models.ActivityLogAlertResource :raises ~azure.core.exceptions.HttpResponseError: @@ -280,7 +283,7 @@ def create_or_update( self, resource_group_name: str, activity_log_alert_name: str, - activity_log_alert: IO, + activity_log_alert: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -293,11 +296,10 @@ def create_or_update( :param activity_log_alert_name: The name of the activity log alert. Required. :type activity_log_alert_name: str :param activity_log_alert: The activity log alert to create or use for the update. Required. - :type activity_log_alert: IO + :type activity_log_alert: 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: ActivityLogAlertResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2017_04_01.models.ActivityLogAlertResource :raises ~azure.core.exceptions.HttpResponseError: @@ -308,7 +310,7 @@ def create_or_update( self, resource_group_name: str, activity_log_alert_name: str, - activity_log_alert: Union[_models.ActivityLogAlertResource, IO], + activity_log_alert: Union[_models.ActivityLogAlertResource, IO[bytes]], **kwargs: Any ) -> _models.ActivityLogAlertResource: """Create a new activity log alert or update an existing one. @@ -319,17 +321,14 @@ def create_or_update( :param activity_log_alert_name: The name of the activity log alert. Required. :type activity_log_alert_name: str :param activity_log_alert: The activity log alert to create or use for the update. Is either a - ActivityLogAlertResource type or a IO type. Required. - :type activity_log_alert: ~azure.mgmt.monitor.v2017_04_01.models.ActivityLogAlertResource 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 + ActivityLogAlertResource type or a IO[bytes] type. Required. + :type activity_log_alert: ~azure.mgmt.monitor.v2017_04_01.models.ActivityLogAlertResource or + IO[bytes] :return: ActivityLogAlertResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2017_04_01.models.ActivityLogAlertResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -340,19 +339,19 @@ def create_or_update( _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", "2017-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2017-04-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ActivityLogAlertResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(activity_log_alert, (IO, bytes)): + if isinstance(activity_log_alert, (IOBase, bytes)): _content = activity_log_alert else: _json = self._serialize.body(activity_log_alert, "ActivityLogAlertResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, activity_log_alert_name=activity_log_alert_name, subscription_id=self._config.subscription_id, @@ -360,16 +359,14 @@ def create_or_update( 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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -379,21 +376,13 @@ def create_or_update( 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("ActivityLogAlertResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("ActivityLogAlertResource", pipeline_response) + deserialized = self._deserialize("ActivityLogAlertResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/activityLogAlerts/{activityLogAlertName}" - } - @distributed_trace def get( self, resource_group_name: str, activity_log_alert_name: str, **kwargs: Any @@ -405,12 +394,11 @@ def get( :type resource_group_name: str :param activity_log_alert_name: The name of the activity log alert. Required. :type activity_log_alert_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ActivityLogAlertResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2017_04_01.models.ActivityLogAlertResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -421,24 +409,22 @@ def get( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2017-04-01")) cls: ClsType[_models.ActivityLogAlertResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, activity_log_alert_name=activity_log_alert_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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -448,16 +434,12 @@ def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ActivityLogAlertResource", pipeline_response) + deserialized = self._deserialize("ActivityLogAlertResource", 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.insights/activityLogAlerts/{activityLogAlertName}" - } + return deserialized # type: ignore @distributed_trace def delete( # pylint: disable=inconsistent-return-statements @@ -470,12 +452,11 @@ def delete( # pylint: disable=inconsistent-return-statements :type resource_group_name: str :param activity_log_alert_name: The name of the activity log alert. Required. :type activity_log_alert_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, @@ -486,24 +467,22 @@ def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2017-04-01")) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, activity_log_alert_name=activity_log_alert_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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -514,11 +493,7 @@ def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/activityLogAlerts/{activityLogAlertName}" - } + return cls(pipeline_response, None, {}) # type: ignore @overload def update( @@ -544,7 +519,6 @@ def update( :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: ActivityLogAlertResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2017_04_01.models.ActivityLogAlertResource :raises ~azure.core.exceptions.HttpResponseError: @@ -555,7 +529,7 @@ def update( self, resource_group_name: str, activity_log_alert_name: str, - activity_log_alert_patch: IO, + activity_log_alert_patch: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -569,11 +543,10 @@ def update( :param activity_log_alert_name: The name of the activity log alert. Required. :type activity_log_alert_name: str :param activity_log_alert_patch: Parameters supplied to the operation. Required. - :type activity_log_alert_patch: IO + :type activity_log_alert_patch: 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: ActivityLogAlertResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2017_04_01.models.ActivityLogAlertResource :raises ~azure.core.exceptions.HttpResponseError: @@ -584,7 +557,7 @@ def update( self, resource_group_name: str, activity_log_alert_name: str, - activity_log_alert_patch: Union[_models.ActivityLogAlertPatchBody, IO], + activity_log_alert_patch: Union[_models.ActivityLogAlertPatchBody, IO[bytes]], **kwargs: Any ) -> _models.ActivityLogAlertResource: """Updates an existing ActivityLogAlertResource's tags. To update other fields use the @@ -596,18 +569,14 @@ def update( :param activity_log_alert_name: The name of the activity log alert. Required. :type activity_log_alert_name: str :param activity_log_alert_patch: Parameters supplied to the operation. Is either a - ActivityLogAlertPatchBody type or a IO type. Required. + ActivityLogAlertPatchBody type or a IO[bytes] type. Required. :type activity_log_alert_patch: - ~azure.mgmt.monitor.v2017_04_01.models.ActivityLogAlertPatchBody 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 + ~azure.mgmt.monitor.v2017_04_01.models.ActivityLogAlertPatchBody or IO[bytes] :return: ActivityLogAlertResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2017_04_01.models.ActivityLogAlertResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -618,19 +587,19 @@ def update( _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", "2017-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2017-04-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ActivityLogAlertResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(activity_log_alert_patch, (IO, bytes)): + if isinstance(activity_log_alert_patch, (IOBase, bytes)): _content = activity_log_alert_patch else: _json = self._serialize.body(activity_log_alert_patch, "ActivityLogAlertPatchBody") - request = build_update_request( + _request = build_update_request( resource_group_name=resource_group_name, activity_log_alert_name=activity_log_alert_name, subscription_id=self._config.subscription_id, @@ -638,16 +607,14 @@ def update( 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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -657,22 +624,17 @@ def update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ActivityLogAlertResource", pipeline_response) + deserialized = self._deserialize("ActivityLogAlertResource", 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.insights/activityLogAlerts/{activityLogAlertName}" - } + return deserialized # type: ignore @distributed_trace def list_by_subscription_id(self, **kwargs: Any) -> Iterable["_models.ActivityLogAlertResource"]: """Get a list of all activity log alerts in a subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ActivityLogAlertResource or the result of cls(response) :rtype: @@ -682,10 +644,10 @@ def list_by_subscription_id(self, **kwargs: Any) -> Iterable["_models.ActivityLo _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2017-04-01")) cls: ClsType[_models.ActivityLogAlertList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -696,15 +658,13 @@ def list_by_subscription_id(self, **kwargs: Any) -> Iterable["_models.ActivityLo def prepare_request(next_link=None): if not next_link: - request = build_list_by_subscription_id_request( + _request = build_list_by_subscription_id_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_subscription_id.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -715,14 +675,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("ActivityLogAlertList", pipeline_response) @@ -732,11 +691,11 @@ def extract_data(pipeline_response): return None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -749,10 +708,6 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_by_subscription_id.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/microsoft.insights/activityLogAlerts" - } - @distributed_trace def list_by_resource_group( self, resource_group_name: str, **kwargs: Any @@ -762,7 +717,6 @@ def list_by_resource_group( :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ActivityLogAlertResource or the result of cls(response) :rtype: @@ -772,10 +726,10 @@ def list_by_resource_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2017-04-01")) cls: ClsType[_models.ActivityLogAlertList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -786,16 +740,14 @@ 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_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -806,14 +758,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("ActivityLogAlertList", pipeline_response) @@ -823,11 +774,11 @@ def extract_data(pipeline_response): return None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -839,7 +790,3 @@ def get_next(next_link=None): return pipeline_response return ItemPaged(get_next, extract_data) - - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/activityLogAlerts" - } diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/__init__.py index 2c7733bfd566..42cc62301757 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/__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 ._monitor_management_client import MonitorManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._monitor_management_client import MonitorManagementClient # type: ignore from ._version import VERSION __version__ = VERSION try: from ._patch import __all__ as _patch_all - from ._patch import * # 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__ = [ "MonitorManagementClient", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/_configuration.py index 4997675f6534..37f761023308 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/_configuration.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/_configuration.py @@ -8,18 +8,16 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy from ._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MonitorManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class MonitorManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for MonitorManagementClient. Note that all parameters used to create this instance are saved as instance @@ -35,7 +33,6 @@ class MonitorManagementClientConfiguration(Configuration): # pylint: disable=to """ def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: - super(MonitorManagementClientConfiguration, self).__init__(**kwargs) api_version: str = kwargs.pop("api_version", "2017-05-01-preview") if credential is None: @@ -48,6 +45,7 @@ def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-monitor/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -56,9 +54,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.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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/_metadata.json b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/_metadata.json index 98a13f9d0362..35d4963831a1 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/_metadata.json +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/_metadata.json @@ -8,10 +8,10 @@ "host_value": "\"https://management.azure.com\"", "parameterized_host_template": null, "azure_arm": true, - "has_lro_operations": false, + "has_public_lro_operations": false, "client_side_validation": false, - "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"sdkcore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMAutoResourceProviderRegistrationPolicy\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}, \"stdlib\": {\"typing_extensions\": [\"Self\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"sdkcore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"AsyncARMAutoResourceProviderRegistrationPolicy\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}, \"stdlib\": {\"typing_extensions\": [\"Self\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "global_parameters": { "sync": { @@ -101,8 +101,8 @@ "credential_scopes": ["https://management.azure.com/.default"], "credential_call_sync": "ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", "credential_call_async": "AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", - "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "sync_imports": "{\"regular\": {\"sdkcore\": {\"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"regular\": {\"sdkcore\": {\"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "operation_groups": { "diagnostic_settings_category": "DiagnosticSettingsCategoryOperations", diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/_monitor_management_client.py index 716984e952e1..09583cce2da1 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/_monitor_management_client.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/_monitor_management_client.py @@ -8,9 +8,12 @@ from copy import deepcopy from typing import Any, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient +from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy from . import models as _models from .._serialization import Deserializer, Serializer @@ -24,11 +27,10 @@ ) if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MonitorManagementClient: # pylint: disable=client-accepts-api-version-keyword +class MonitorManagementClient: """Monitor Management Client. :ivar diagnostic_settings_category: DiagnosticSettingsCategoryOperations operations @@ -66,27 +68,47 @@ def __init__( self._config = MonitorManagementClientConfiguration( credential=credential, subscription_id=subscription_id, **kwargs ) - self._client: ARMPipelineClient = ARMPipelineClient(base_url=base_url, config=self._config, **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), + 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=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.diagnostic_settings_category = DiagnosticSettingsCategoryOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2017-05-01-preview" ) self.diagnostic_settings = DiagnosticSettingsOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2017-05-01-preview" ) self.metric_definitions = MetricDefinitionsOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2017-05-01-preview" + ) + self.metrics = MetricsOperations( + self._client, self._config, self._serialize, self._deserialize, "2017-05-01-preview" ) - self.metrics = MetricsOperations(self._client, self._config, self._serialize, self._deserialize) self.subscription_diagnostic_settings = SubscriptionDiagnosticSettingsOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2017-05-01-preview" ) - 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,12 +128,12 @@ 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) -> None: self._client.close() - def __enter__(self) -> "MonitorManagementClient": + def __enter__(self) -> Self: self._client.__enter__() return self diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/_vendor.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/_vendor.py deleted file mode 100644 index bd0df84f5319..000000000000 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/_vendor.py +++ /dev/null @@ -1,30 +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 typing import List, cast - -from azure.core.pipeline.transport import HttpRequest - - -def _convert_request(request, files=None): - data = request.content if not files else None - request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) - if files: - request.set_formdata_body(files) - return request - - -def _format_url_section(template, **kwargs): - components = template.split("/") - while components: - try: - return template.format(**kwargs) - except KeyError as key: - # Need the cast, as for some reasons "split" is typed as list[str | Any] - formatted_components = cast(List[str], template.split("/")) - components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] - template = "/".join(components) diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/_version.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/_version.py index 394ee7c0c03c..e5754a47ce68 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/_version.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "6.0.2" +VERSION = "1.0.0b1" diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/aio/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/aio/__init__.py index 2c151bb41c19..3df30ff42149 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/aio/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/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 ._monitor_management_client import MonitorManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._monitor_management_client import MonitorManagementClient # type: ignore try: from ._patch import __all__ as _patch_all - from ._patch import * # 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__ = [ "MonitorManagementClient", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/aio/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/aio/_configuration.py index 850cb89324d2..724d3f13a9d3 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/aio/_configuration.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/aio/_configuration.py @@ -8,18 +8,16 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy from .._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MonitorManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class MonitorManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for MonitorManagementClient. Note that all parameters used to create this instance are saved as instance @@ -35,7 +33,6 @@ class MonitorManagementClientConfiguration(Configuration): # pylint: disable=to """ def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: - super(MonitorManagementClientConfiguration, self).__init__(**kwargs) api_version: str = kwargs.pop("api_version", "2017-05-01-preview") if credential is None: @@ -48,6 +45,7 @@ def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **k self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-monitor/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -56,9 +54,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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/aio/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/aio/_monitor_management_client.py index 086db347d6d9..5c501f1442f3 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/aio/_monitor_management_client.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/aio/_monitor_management_client.py @@ -8,9 +8,12 @@ from copy import deepcopy from typing import Any, Awaitable, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient +from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy from .. import models as _models from ..._serialization import Deserializer, Serializer @@ -24,11 +27,10 @@ ) if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MonitorManagementClient: # pylint: disable=client-accepts-api-version-keyword +class MonitorManagementClient: """Monitor Management Client. :ivar diagnostic_settings_category: DiagnosticSettingsCategoryOperations operations @@ -66,27 +68,49 @@ def __init__( self._config = MonitorManagementClientConfiguration( credential=credential, subscription_id=subscription_id, **kwargs ) - self._client: AsyncARMPipelineClient = AsyncARMPipelineClient(base_url=base_url, config=self._config, **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=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.diagnostic_settings_category = DiagnosticSettingsCategoryOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2017-05-01-preview" ) self.diagnostic_settings = DiagnosticSettingsOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2017-05-01-preview" ) self.metric_definitions = MetricDefinitionsOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2017-05-01-preview" + ) + self.metrics = MetricsOperations( + self._client, self._config, self._serialize, self._deserialize, "2017-05-01-preview" ) - self.metrics = MetricsOperations(self._client, self._config, self._serialize, self._deserialize) self.subscription_diagnostic_settings = SubscriptionDiagnosticSettingsOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2017-05-01-preview" ) - 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,12 +130,12 @@ 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) -> "MonitorManagementClient": + async def __aenter__(self) -> Self: await self._client.__aenter__() return self diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/aio/operations/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/aio/operations/__init__.py index ce13a3cecdd5..3f8a5beffd5d 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/aio/operations/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/aio/operations/__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 ._diagnostic_settings_category_operations import DiagnosticSettingsCategoryOperations -from ._diagnostic_settings_operations import DiagnosticSettingsOperations -from ._metric_definitions_operations import MetricDefinitionsOperations -from ._metrics_operations import MetricsOperations -from ._subscription_diagnostic_settings_operations import SubscriptionDiagnosticSettingsOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._diagnostic_settings_category_operations import DiagnosticSettingsCategoryOperations # type: ignore +from ._diagnostic_settings_operations import DiagnosticSettingsOperations # type: ignore +from ._metric_definitions_operations import MetricDefinitionsOperations # type: ignore +from ._metrics_operations import MetricsOperations # type: ignore +from ._subscription_diagnostic_settings_operations import SubscriptionDiagnosticSettingsOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ @@ -23,5 +29,5 @@ "MetricsOperations", "SubscriptionDiagnosticSettingsOperations", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/aio/operations/_diagnostic_settings_category_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/aio/operations/_diagnostic_settings_category_operations.py index 0d83e355a73a..37bd40b51c7e 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/aio/operations/_diagnostic_settings_category_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/aio/operations/_diagnostic_settings_category_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,7 @@ # 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 ( @@ -17,16 +17,18 @@ 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_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._diagnostic_settings_category_operations import build_get_request, build_list_request +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -49,6 +51,7 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace_async async def get(self, resource_uri: str, name: str, **kwargs: Any) -> _models.DiagnosticSettingsCategoryResource: @@ -58,12 +61,11 @@ async def get(self, resource_uri: str, name: str, **kwargs: Any) -> _models.Diag :type resource_uri: str :param name: The name of the diagnostic setting. Required. :type name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: DiagnosticSettingsCategoryResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2017_05_01_preview.models.DiagnosticSettingsCategoryResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -74,23 +76,23 @@ async def get(self, resource_uri: str, name: str, **kwargs: Any) -> _models.Diag _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2017-05-01-preview") + ) cls: ClsType[_models.DiagnosticSettingsCategoryResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_uri=resource_uri, name=name, api_version=api_version, - template_url=self.get.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -100,14 +102,12 @@ async def get(self, resource_uri: str, name: str, **kwargs: Any) -> _models.Diag error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("DiagnosticSettingsCategoryResource", pipeline_response) + deserialized = self._deserialize("DiagnosticSettingsCategoryResource", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get.metadata = {"url": "/{resourceUri}/providers/Microsoft.Insights/diagnosticSettingsCategories/{name}"} + return deserialized # type: ignore @distributed_trace_async async def list(self, resource_uri: str, **kwargs: Any) -> _models.DiagnosticSettingsCategoryResourceCollection: @@ -115,13 +115,12 @@ async def list(self, resource_uri: str, **kwargs: Any) -> _models.DiagnosticSett :param resource_uri: The identifier of the resource. Required. :type resource_uri: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: DiagnosticSettingsCategoryResourceCollection or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2017_05_01_preview.models.DiagnosticSettingsCategoryResourceCollection :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -132,22 +131,22 @@ async def list(self, resource_uri: str, **kwargs: Any) -> _models.DiagnosticSett _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2017-05-01-preview") + ) cls: ClsType[_models.DiagnosticSettingsCategoryResourceCollection] = kwargs.pop("cls", None) - request = build_list_request( + _request = build_list_request( resource_uri=resource_uri, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -157,11 +156,11 @@ async def list(self, resource_uri: str, **kwargs: Any) -> _models.DiagnosticSett error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("DiagnosticSettingsCategoryResourceCollection", pipeline_response) + deserialized = self._deserialize( + "DiagnosticSettingsCategoryResourceCollection", pipeline_response.http_response + ) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - list.metadata = {"url": "/{resourceUri}/providers/Microsoft.Insights/diagnosticSettingsCategories"} + return deserialized # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/aio/operations/_diagnostic_settings_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/aio/operations/_diagnostic_settings_operations.py index dc66df3a6c66..dee3585b4386 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/aio/operations/_diagnostic_settings_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/aio/operations/_diagnostic_settings_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload from azure.core.exceptions import ( @@ -17,14 +18,12 @@ 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_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._diagnostic_settings_operations import ( build_create_or_update_request, build_delete_request, @@ -32,6 +31,10 @@ build_list_request, ) +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -54,6 +57,7 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace_async async def get(self, resource_uri: str, name: str, **kwargs: Any) -> _models.DiagnosticSettingsResource: @@ -63,12 +67,11 @@ async def get(self, resource_uri: str, name: str, **kwargs: Any) -> _models.Diag :type resource_uri: str :param name: The name of the diagnostic setting. Required. :type name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: DiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2017_05_01_preview.models.DiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -79,23 +82,23 @@ async def get(self, resource_uri: str, name: str, **kwargs: Any) -> _models.Diag _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2017-05-01-preview") + ) cls: ClsType[_models.DiagnosticSettingsResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_uri=resource_uri, name=name, api_version=api_version, - template_url=self.get.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -105,14 +108,12 @@ async def get(self, resource_uri: str, name: str, **kwargs: Any) -> _models.Diag error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("DiagnosticSettingsResource", pipeline_response) + deserialized = self._deserialize("DiagnosticSettingsResource", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get.metadata = {"url": "/{resourceUri}/providers/Microsoft.Insights/diagnosticSettings/{name}"} + return deserialized # type: ignore @overload async def create_or_update( @@ -135,7 +136,6 @@ async def create_or_update( :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: DiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2017_05_01_preview.models.DiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: @@ -143,7 +143,13 @@ async def create_or_update( @overload async def create_or_update( - self, resource_uri: str, name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + self, + resource_uri: str, + name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any ) -> _models.DiagnosticSettingsResource: """Creates or updates diagnostic settings for the specified resource. @@ -152,11 +158,10 @@ async def create_or_update( :param name: The name of the diagnostic setting. Required. :type name: str :param parameters: Parameters supplied to the operation. Required. - :type parameters: IO + :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: DiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2017_05_01_preview.models.DiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: @@ -164,7 +169,11 @@ async def create_or_update( @distributed_trace_async async def create_or_update( - self, resource_uri: str, name: str, parameters: Union[_models.DiagnosticSettingsResource, IO], **kwargs: Any + self, + resource_uri: str, + name: str, + parameters: Union[_models.DiagnosticSettingsResource, IO[bytes]], + **kwargs: Any ) -> _models.DiagnosticSettingsResource: """Creates or updates diagnostic settings for the specified resource. @@ -173,18 +182,14 @@ async def create_or_update( :param name: The name of the diagnostic setting. Required. :type name: str :param parameters: Parameters supplied to the operation. Is either a DiagnosticSettingsResource - type or a IO type. Required. + type or a IO[bytes] type. Required. :type parameters: ~azure.mgmt.monitor.v2017_05_01_preview.models.DiagnosticSettingsResource 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 + IO[bytes] :return: DiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2017_05_01_preview.models.DiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -195,35 +200,35 @@ async def create_or_update( _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", "2017-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2017-05-01-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.DiagnosticSettingsResource] = 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, "DiagnosticSettingsResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_uri=resource_uri, name=name, 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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -233,31 +238,26 @@ async def create_or_update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("DiagnosticSettingsResource", pipeline_response) + deserialized = self._deserialize("DiagnosticSettingsResource", 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": "/{resourceUri}/providers/Microsoft.Insights/diagnosticSettings/{name}"} + return deserialized # type: ignore @distributed_trace_async - async def delete( # pylint: disable=inconsistent-return-statements - self, resource_uri: str, name: str, **kwargs: Any - ) -> None: + async def delete(self, resource_uri: str, name: str, **kwargs: Any) -> None: """Deletes existing diagnostic settings for the specified resource. :param resource_uri: The identifier of the resource. Required. :type resource_uri: str :param name: The name of the diagnostic setting. Required. :type 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, @@ -268,23 +268,23 @@ async def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2017-05-01-preview") + ) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_uri=resource_uri, name=name, api_version=api_version, - template_url=self.delete.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -295,9 +295,7 @@ async def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = {"url": "/{resourceUri}/providers/Microsoft.Insights/diagnosticSettings/{name}"} + return cls(pipeline_response, None, {}) # type: ignore @distributed_trace_async async def list(self, resource_uri: str, **kwargs: Any) -> _models.DiagnosticSettingsResourceCollection: @@ -305,12 +303,11 @@ async def list(self, resource_uri: str, **kwargs: Any) -> _models.DiagnosticSett :param resource_uri: The identifier of the resource. Required. :type resource_uri: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: DiagnosticSettingsResourceCollection or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2017_05_01_preview.models.DiagnosticSettingsResourceCollection :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -321,22 +318,22 @@ async def list(self, resource_uri: str, **kwargs: Any) -> _models.DiagnosticSett _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2017-05-01-preview") + ) cls: ClsType[_models.DiagnosticSettingsResourceCollection] = kwargs.pop("cls", None) - request = build_list_request( + _request = build_list_request( resource_uri=resource_uri, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -346,11 +343,9 @@ async def list(self, resource_uri: str, **kwargs: Any) -> _models.DiagnosticSett error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("DiagnosticSettingsResourceCollection", pipeline_response) + deserialized = self._deserialize("DiagnosticSettingsResourceCollection", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - list.metadata = {"url": "/{resourceUri}/providers/Microsoft.Insights/diagnosticSettings"} + return deserialized # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/aio/operations/_metric_definitions_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/aio/operations/_metric_definitions_operations.py index 4fc92805e16b..c2bc9c3a439e 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/aio/operations/_metric_definitions_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/aio/operations/_metric_definitions_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,7 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar import urllib.parse @@ -19,16 +19,18 @@ 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 ...operations._metric_definitions_operations import build_list_request +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -51,6 +53,7 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list(self, resource_uri: str, **kwargs: Any) -> AsyncIterable["_models.MetricDefinition"]: @@ -58,7 +61,6 @@ def list(self, resource_uri: str, **kwargs: Any) -> AsyncIterable["_models.Metri :param resource_uri: The identifier of the resource. Required. :type resource_uri: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either MetricDefinition or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.monitor.v2017_05_01_preview.models.MetricDefinition] @@ -67,10 +69,12 @@ def list(self, resource_uri: str, **kwargs: Any) -> AsyncIterable["_models.Metri _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2017-05-01-preview") + ) cls: ClsType[_models.MetricDefinitionCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -81,15 +85,13 @@ def list(self, resource_uri: str, **kwargs: Any) -> AsyncIterable["_models.Metri def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( resource_uri=resource_uri, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -100,14 +102,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("MetricDefinitionCollection", pipeline_response) @@ -117,11 +118,11 @@ async def extract_data(pipeline_response): return None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -133,5 +134,3 @@ async def get_next(next_link=None): return pipeline_response return AsyncItemPaged(get_next, extract_data) - - list.metadata = {"url": "/{resourceUri}/providers/microsoft.insights/metricDefinitions"} diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/aio/operations/_metrics_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/aio/operations/_metrics_operations.py index 9f58ae2b706a..226ff60bab44 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/aio/operations/_metrics_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/aio/operations/_metrics_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +6,7 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- import datetime +import sys from typing import Any, Callable, Dict, Optional, TypeVar, Union from azure.core.exceptions import ( @@ -18,16 +18,18 @@ 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_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._metrics_operations import build_list_request +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -50,6 +52,7 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace_async async def list( @@ -89,24 +92,23 @@ async def list( :type orderby: str :param filter: The **$filter** is used to reduce the set of metric data returned.:code:`
`Example::code:`
`Metric contains metadata A, B and C.:code:`
`- - Return all time series of C where A = a1 and B = b1 or b2:code:`
`\ **$filter=A eq ‘a1’ and - B eq ‘b1’ or B eq ‘b2’ and C eq ‘*’**\ :code:`
`- Invalid variant::code:`
`\ **$filter=A - eq ‘a1’ and B eq ‘b1’ and C eq ‘*’ or B = ‘b2’**\ :code:`
`This is invalid because the - logical or operator cannot separate two different metadata names.:code:`
`- Return all time - series where A = a1, B = b1 and C = c1::code:`
`\ **$filter=A eq ‘a1’ and B eq ‘b1’ and C eq - ‘c1’**\ :code:`
`- Return all time series where A = a1:code:`
`\ **$filter=A eq ‘a1’ and - B eq ‘\ *’ and C eq ‘*\ ’**. Default value is None. + Return all time series of C where A = a1 and B = b1 or b2:code:`
`\\ **$filter=A eq ‘a1’ and + B eq ‘b1’ or B eq ‘b2’ and C eq ‘*’**\\ :code:`
`- Invalid variant::code:`
`\\ + **$filter=A eq ‘a1’ and B eq ‘b1’ and C eq ‘*’ or B = ‘b2’**\\ :code:`
`This is invalid + because the logical or operator cannot separate two different metadata names.:code:`
`- + Return all time series where A = a1, B = b1 and C = c1::code:`
`\\ **$filter=A eq ‘a1’ and B + eq ‘b1’ and C eq ‘c1’**\\ :code:`
`- Return all time series where A = a1:code:`
`\\ + **$filter=A eq ‘a1’ and B eq ‘\\ *’ and C eq ‘*\\ ’**. Default value is None. :type filter: str :param result_type: Reduces the set of data collected. The syntax allowed depends on the operation. See the operation's description for details. Known values are: "Data" and "Metadata". Default value is None. :type result_type: str or ~azure.mgmt.monitor.v2017_05_01_preview.models.ResultType - :keyword callable cls: A custom type or function that will be passed the direct response :return: Response or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2017_05_01_preview.models.Response :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -117,10 +119,12 @@ async def list( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2017-05-01-preview") + ) cls: ClsType[_models.Response] = kwargs.pop("cls", None) - request = build_list_request( + _request = build_list_request( resource_uri=resource_uri, timespan=timespan, interval=interval, @@ -131,16 +135,14 @@ async def list( filter=filter, result_type=result_type, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -150,11 +152,9 @@ async def list( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("Response", pipeline_response) + deserialized = self._deserialize("Response", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - list.metadata = {"url": "/{resourceUri}/providers/microsoft.insights/metrics"} + return deserialized # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/aio/operations/_subscription_diagnostic_settings_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/aio/operations/_subscription_diagnostic_settings_operations.py index 943d33f893aa..0381203dc40b 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/aio/operations/_subscription_diagnostic_settings_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/aio/operations/_subscription_diagnostic_settings_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload from azure.core.exceptions import ( @@ -17,14 +18,12 @@ 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_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._subscription_diagnostic_settings_operations import ( build_create_or_update_request, build_delete_request, @@ -32,6 +31,10 @@ build_list_request, ) +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -54,6 +57,7 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace_async async def get(self, name: str, **kwargs: Any) -> _models.SubscriptionDiagnosticSettingsResource: @@ -61,12 +65,11 @@ async def get(self, name: str, **kwargs: Any) -> _models.SubscriptionDiagnosticS :param name: The name of the diagnostic setting. Required. :type name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: SubscriptionDiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2017_05_01_preview.models.SubscriptionDiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -77,23 +80,23 @@ async def get(self, name: str, **kwargs: Any) -> _models.SubscriptionDiagnosticS _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2017-05-01-preview") + ) cls: ClsType[_models.SubscriptionDiagnosticSettingsResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( name=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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -103,14 +106,12 @@ async def get(self, name: str, **kwargs: Any) -> _models.SubscriptionDiagnosticS error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("SubscriptionDiagnosticSettingsResource", pipeline_response) + deserialized = self._deserialize("SubscriptionDiagnosticSettingsResource", 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}/providers/microsoft.insights/diagnosticSettings/{name}"} + return deserialized # type: ignore @overload async def create_or_update( @@ -131,7 +132,6 @@ async def create_or_update( :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: SubscriptionDiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2017_05_01_preview.models.SubscriptionDiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: @@ -139,18 +139,17 @@ async def create_or_update( @overload async def create_or_update( - self, name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + self, name: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any ) -> _models.SubscriptionDiagnosticSettingsResource: """Creates or updates subscription diagnostic settings for the specified resource. :param name: The name of the diagnostic setting. Required. :type name: str :param parameters: Parameters supplied to the operation. Required. - :type parameters: IO + :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: SubscriptionDiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2017_05_01_preview.models.SubscriptionDiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: @@ -158,25 +157,22 @@ async def create_or_update( @distributed_trace_async async def create_or_update( - self, name: str, parameters: Union[_models.SubscriptionDiagnosticSettingsResource, IO], **kwargs: Any + self, name: str, parameters: Union[_models.SubscriptionDiagnosticSettingsResource, IO[bytes]], **kwargs: Any ) -> _models.SubscriptionDiagnosticSettingsResource: """Creates or updates subscription diagnostic settings for the specified resource. :param name: The name of the diagnostic setting. Required. :type name: str :param parameters: Parameters supplied to the operation. Is either a - SubscriptionDiagnosticSettingsResource type or a IO type. Required. + SubscriptionDiagnosticSettingsResource type or a IO[bytes] type. Required. :type parameters: - ~azure.mgmt.monitor.v2017_05_01_preview.models.SubscriptionDiagnosticSettingsResource 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 + ~azure.mgmt.monitor.v2017_05_01_preview.models.SubscriptionDiagnosticSettingsResource or + IO[bytes] :return: SubscriptionDiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2017_05_01_preview.models.SubscriptionDiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -187,35 +183,35 @@ async def create_or_update( _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", "2017-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2017-05-01-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.SubscriptionDiagnosticSettingsResource] = 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, "SubscriptionDiagnosticSettingsResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( name=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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -225,29 +221,24 @@ async def create_or_update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("SubscriptionDiagnosticSettingsResource", pipeline_response) + deserialized = self._deserialize("SubscriptionDiagnosticSettingsResource", 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}/providers/microsoft.insights/diagnosticSettings/{name}" - } + return deserialized # type: ignore @distributed_trace_async - async def delete(self, name: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements + async def delete(self, name: str, **kwargs: Any) -> None: """Deletes existing subscription diagnostic settings for the specified resource. :param name: The name of the diagnostic setting. Required. :type 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, @@ -258,23 +249,23 @@ async def delete(self, name: str, **kwargs: Any) -> None: # pylint: disable=inc _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2017-05-01-preview") + ) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( name=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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -285,21 +276,18 @@ async def delete(self, name: str, **kwargs: Any) -> None: # pylint: disable=inc raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = {"url": "/subscriptions/{subscriptionId}/providers/microsoft.insights/diagnosticSettings/{name}"} + return cls(pipeline_response, None, {}) # type: ignore @distributed_trace_async async def list(self, **kwargs: Any) -> _models.SubscriptionDiagnosticSettingsResourceCollection: """Gets the active subscription diagnostic settings list for the specified subscriptionId. - :keyword callable cls: A custom type or function that will be passed the direct response :return: SubscriptionDiagnosticSettingsResourceCollection or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2017_05_01_preview.models.SubscriptionDiagnosticSettingsResourceCollection :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -310,22 +298,22 @@ async def list(self, **kwargs: Any) -> _models.SubscriptionDiagnosticSettingsRes _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2017-05-01-preview") + ) cls: ClsType[_models.SubscriptionDiagnosticSettingsResourceCollection] = kwargs.pop("cls", None) - request = build_list_request( + _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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -335,11 +323,11 @@ async def list(self, **kwargs: Any) -> _models.SubscriptionDiagnosticSettingsRes error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("SubscriptionDiagnosticSettingsResourceCollection", pipeline_response) + deserialized = self._deserialize( + "SubscriptionDiagnosticSettingsResourceCollection", pipeline_response.http_response + ) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/microsoft.insights/diagnosticSettings"} + return deserialized # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/models/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/models/__init__.py index b0c0eda56278..bf4b3f65dd57 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/models/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/models/__init__.py @@ -5,36 +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 DiagnosticSettingsCategoryResource -from ._models_py3 import DiagnosticSettingsCategoryResourceCollection -from ._models_py3 import DiagnosticSettingsResource -from ._models_py3 import DiagnosticSettingsResourceCollection -from ._models_py3 import ErrorResponse -from ._models_py3 import LocalizableString -from ._models_py3 import LogSettings -from ._models_py3 import MetadataValue -from ._models_py3 import Metric -from ._models_py3 import MetricAvailability -from ._models_py3 import MetricDefinition -from ._models_py3 import MetricDefinitionCollection -from ._models_py3 import MetricSettings -from ._models_py3 import MetricValue -from ._models_py3 import ProxyOnlyResource -from ._models_py3 import Response -from ._models_py3 import RetentionPolicy -from ._models_py3 import SubscriptionDiagnosticSettingsResource -from ._models_py3 import SubscriptionDiagnosticSettingsResourceCollection -from ._models_py3 import SubscriptionLogSettings -from ._models_py3 import SubscriptionProxyOnlyResource -from ._models_py3 import TimeSeriesElement +from typing import TYPE_CHECKING -from ._monitor_management_client_enums import AggregationType -from ._monitor_management_client_enums import CategoryType -from ._monitor_management_client_enums import ResultType -from ._monitor_management_client_enums import Unit +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models_py3 import ( # type: ignore + DiagnosticSettingsCategoryResource, + DiagnosticSettingsCategoryResourceCollection, + DiagnosticSettingsResource, + DiagnosticSettingsResourceCollection, + ErrorResponse, + LocalizableString, + LogSettings, + MetadataValue, + Metric, + MetricAvailability, + MetricDefinition, + MetricDefinitionCollection, + MetricSettings, + MetricValue, + ProxyOnlyResource, + Response, + RetentionPolicy, + SubscriptionDiagnosticSettingsResource, + SubscriptionDiagnosticSettingsResourceCollection, + SubscriptionLogSettings, + SubscriptionProxyOnlyResource, + TimeSeriesElement, +) + +from ._monitor_management_client_enums import ( # type: ignore + AggregationType, + CategoryType, + ResultType, + Unit, +) from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ @@ -65,5 +76,5 @@ "ResultType", "Unit", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/models/_models_py3.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/models/_models_py3.py index 0564434e908a..7b644b691d13 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/models/_models_py3.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/models/_models_py3.py @@ -1,5 +1,5 @@ -# coding=utf-8 # 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. @@ -13,7 +13,6 @@ from ... import _serialization if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from .. import models as _models @@ -89,7 +88,7 @@ def __init__(self, *, category_type: Optional[Union[str, "_models.CategoryType"] self.category_type = category_type -class DiagnosticSettingsCategoryResourceCollection(_serialization.Model): +class DiagnosticSettingsCategoryResourceCollection(_serialization.Model): # pylint: disable=name-too-long """Represents a collection of diagnostic setting category resources. :ivar value: The collection of diagnostic settings category resources. @@ -113,7 +112,7 @@ def __init__( self.value = value -class DiagnosticSettingsResource(ProxyOnlyResource): # pylint: disable=too-many-instance-attributes +class DiagnosticSettingsResource(ProxyOnlyResource): """The diagnostic setting resource. Variables are only populated by the server, and will be ignored when sending a request. @@ -141,7 +140,7 @@ class DiagnosticSettingsResource(ProxyOnlyResource): # pylint: disable=too-many :vartype logs: list[~azure.mgmt.monitor.v2017_05_01_preview.models.LogSettings] :ivar workspace_id: The full ARM resource ID of the Log Analytics workspace to which you would like to send Diagnostic Logs. Example: - /subscriptions/4b9e8510-67ab-4e9a-95a9-e2f1e570ea9c/resourceGroups/insights-integration/providers/Microsoft.OperationalInsights/workspaces/viruela2. + /subscriptions/4b9e8510-67ab-4e9a-95a9-e2f1e570ea9c/resourceGroups/insights-integration/providers/Microsoft.OperationalInsights/workspaces/viruela2. # pylint: disable=line-too-long :vartype workspace_id: str :ivar log_analytics_destination_type: A string indicating whether the export to Log Analytics should use the default destination type, i.e. AzureDiagnostics, or use a destination type @@ -201,7 +200,7 @@ def __init__( :paramtype logs: list[~azure.mgmt.monitor.v2017_05_01_preview.models.LogSettings] :keyword workspace_id: The full ARM resource ID of the Log Analytics workspace to which you would like to send Diagnostic Logs. Example: - /subscriptions/4b9e8510-67ab-4e9a-95a9-e2f1e570ea9c/resourceGroups/insights-integration/providers/Microsoft.OperationalInsights/workspaces/viruela2. + /subscriptions/4b9e8510-67ab-4e9a-95a9-e2f1e570ea9c/resourceGroups/insights-integration/providers/Microsoft.OperationalInsights/workspaces/viruela2. # pylint: disable=line-too-long :paramtype workspace_id: str :keyword log_analytics_destination_type: A string indicating whether the export to Log Analytics should use the default destination type, i.e. AzureDiagnostics, or use a destination @@ -270,7 +269,7 @@ def __init__(self, *, code: Optional[str] = None, message: Optional[str] = None, class LocalizableString(_serialization.Model): """The localizable string class. - 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 value: the invariant value. Required. :vartype value: str @@ -302,7 +301,7 @@ def __init__(self, *, value: str, localized_value: Optional[str] = None, **kwarg class LogSettings(_serialization.Model): """Part of MultiTenantDiagnosticSettings. Specifies the settings for a particular log. - 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 category: Name of a Diagnostic Log category for a resource type this setting is applied to. To obtain the list of Diagnostic Log categories for a resource, first perform a GET @@ -379,7 +378,7 @@ def __init__( class Metric(_serialization.Model): """The result data of a query. - 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: the metric Id. Required. :vartype id: str @@ -610,7 +609,7 @@ def __init__( class MetricDefinitionCollection(_serialization.Model): """Represents collection of metric definitions. - 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 value: the values for the metric definitions. Required. :vartype value: list[~azure.mgmt.monitor.v2017_05_01_preview.models.MetricDefinition] @@ -636,7 +635,7 @@ def __init__(self, *, value: List["_models.MetricDefinition"], **kwargs: Any) -> class MetricSettings(_serialization.Model): """Part of MultiTenantDiagnosticSettings. Specifies the settings for a particular metric. - 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 time_grain: the timegrain of the metric in ISO8601 format. :vartype time_grain: ~datetime.timedelta @@ -692,7 +691,7 @@ def __init__( class MetricValue(_serialization.Model): """Represents a metric value. - 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 time_stamp: the timestamp for the metric value in ISO 8601 format. Required. :vartype time_stamp: ~datetime.datetime @@ -760,7 +759,7 @@ def __init__( class Response(_serialization.Model): """The response to a metrics query. - 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 cost: The integer value representing the relative cost of the query. :vartype cost: int @@ -822,7 +821,7 @@ def __init__( class RetentionPolicy(_serialization.Model): """Specifies the retention policy for the log. - 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 enabled: a value indicating whether the retention policy is enabled. Required. :vartype enabled: bool @@ -922,7 +921,7 @@ class SubscriptionDiagnosticSettingsResource(SubscriptionProxyOnlyResource): :vartype logs: list[~azure.mgmt.monitor.v2017_05_01_preview.models.SubscriptionLogSettings] :ivar workspace_id: The full ARM resource ID of the Log Analytics workspace to which you would like to send Diagnostic Logs. Example: - /subscriptions/4b9e8510-67ab-4e9a-95a9-e2f1e570ea9c/resourceGroups/insights-integration/providers/Microsoft.OperationalInsights/workspaces/viruela2. + /subscriptions/4b9e8510-67ab-4e9a-95a9-e2f1e570ea9c/resourceGroups/insights-integration/providers/Microsoft.OperationalInsights/workspaces/viruela2. # pylint: disable=line-too-long :vartype workspace_id: str """ @@ -975,7 +974,7 @@ def __init__( :paramtype logs: list[~azure.mgmt.monitor.v2017_05_01_preview.models.SubscriptionLogSettings] :keyword workspace_id: The full ARM resource ID of the Log Analytics workspace to which you would like to send Diagnostic Logs. Example: - /subscriptions/4b9e8510-67ab-4e9a-95a9-e2f1e570ea9c/resourceGroups/insights-integration/providers/Microsoft.OperationalInsights/workspaces/viruela2. + /subscriptions/4b9e8510-67ab-4e9a-95a9-e2f1e570ea9c/resourceGroups/insights-integration/providers/Microsoft.OperationalInsights/workspaces/viruela2. # pylint: disable=line-too-long :paramtype workspace_id: str """ super().__init__(location=location, **kwargs) @@ -987,7 +986,7 @@ def __init__( self.workspace_id = workspace_id -class SubscriptionDiagnosticSettingsResourceCollection(_serialization.Model): +class SubscriptionDiagnosticSettingsResourceCollection(_serialization.Model): # pylint: disable=name-too-long """Represents a collection of subscription diagnostic settings resources. :ivar value: The collection of subscription diagnostic settings resources. @@ -1014,7 +1013,7 @@ def __init__( class SubscriptionLogSettings(_serialization.Model): """Part of Subscription diagnostic setting. Specifies the settings for a particular log. - 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 category: Name of a Subscription Diagnostic Log category for a resource type this setting is applied to. diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/operations/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/operations/__init__.py index ce13a3cecdd5..3f8a5beffd5d 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/operations/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/operations/__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 ._diagnostic_settings_category_operations import DiagnosticSettingsCategoryOperations -from ._diagnostic_settings_operations import DiagnosticSettingsOperations -from ._metric_definitions_operations import MetricDefinitionsOperations -from ._metrics_operations import MetricsOperations -from ._subscription_diagnostic_settings_operations import SubscriptionDiagnosticSettingsOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._diagnostic_settings_category_operations import DiagnosticSettingsCategoryOperations # type: ignore +from ._diagnostic_settings_operations import DiagnosticSettingsOperations # type: ignore +from ._metric_definitions_operations import MetricDefinitionsOperations # type: ignore +from ._metrics_operations import MetricsOperations # type: ignore +from ._subscription_diagnostic_settings_operations import SubscriptionDiagnosticSettingsOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ @@ -23,5 +29,5 @@ "MetricsOperations", "SubscriptionDiagnosticSettingsOperations", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/operations/_diagnostic_settings_category_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/operations/_diagnostic_settings_category_operations.py index 8ce4544b481d..a9edc83d0217 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/operations/_diagnostic_settings_category_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/operations/_diagnostic_settings_category_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,7 @@ # 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 ( @@ -17,16 +17,18 @@ map_error, ) 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 +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -48,7 +50,7 @@ def build_get_request(resource_uri: str, name: str, **kwargs: Any) -> HttpReques "name": _SERIALIZER.url("name", name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -72,7 +74,7 @@ def build_list_request(resource_uri: str, **kwargs: Any) -> HttpRequest: "resourceUri": _SERIALIZER.url("resource_uri", resource_uri, "str", skip_quote=True), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -101,6 +103,7 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def get(self, resource_uri: str, name: str, **kwargs: Any) -> _models.DiagnosticSettingsCategoryResource: @@ -110,12 +113,11 @@ def get(self, resource_uri: str, name: str, **kwargs: Any) -> _models.Diagnostic :type resource_uri: str :param name: The name of the diagnostic setting. Required. :type name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: DiagnosticSettingsCategoryResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2017_05_01_preview.models.DiagnosticSettingsCategoryResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -126,23 +128,23 @@ def get(self, resource_uri: str, name: str, **kwargs: Any) -> _models.Diagnostic _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2017-05-01-preview") + ) cls: ClsType[_models.DiagnosticSettingsCategoryResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_uri=resource_uri, name=name, api_version=api_version, - template_url=self.get.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -152,14 +154,12 @@ def get(self, resource_uri: str, name: str, **kwargs: Any) -> _models.Diagnostic error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("DiagnosticSettingsCategoryResource", pipeline_response) + deserialized = self._deserialize("DiagnosticSettingsCategoryResource", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get.metadata = {"url": "/{resourceUri}/providers/Microsoft.Insights/diagnosticSettingsCategories/{name}"} + return deserialized # type: ignore @distributed_trace def list(self, resource_uri: str, **kwargs: Any) -> _models.DiagnosticSettingsCategoryResourceCollection: @@ -167,13 +167,12 @@ def list(self, resource_uri: str, **kwargs: Any) -> _models.DiagnosticSettingsCa :param resource_uri: The identifier of the resource. Required. :type resource_uri: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: DiagnosticSettingsCategoryResourceCollection or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2017_05_01_preview.models.DiagnosticSettingsCategoryResourceCollection :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -184,22 +183,22 @@ def list(self, resource_uri: str, **kwargs: Any) -> _models.DiagnosticSettingsCa _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2017-05-01-preview") + ) cls: ClsType[_models.DiagnosticSettingsCategoryResourceCollection] = kwargs.pop("cls", None) - request = build_list_request( + _request = build_list_request( resource_uri=resource_uri, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -209,11 +208,11 @@ def list(self, resource_uri: str, **kwargs: Any) -> _models.DiagnosticSettingsCa error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("DiagnosticSettingsCategoryResourceCollection", pipeline_response) + deserialized = self._deserialize( + "DiagnosticSettingsCategoryResourceCollection", pipeline_response.http_response + ) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - list.metadata = {"url": "/{resourceUri}/providers/Microsoft.Insights/diagnosticSettingsCategories"} + return deserialized # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/operations/_diagnostic_settings_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/operations/_diagnostic_settings_operations.py index 8b0088864477..ca83a6fe1c1a 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/operations/_diagnostic_settings_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/operations/_diagnostic_settings_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload from azure.core.exceptions import ( @@ -17,16 +18,18 @@ map_error, ) 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 +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -48,7 +51,7 @@ def build_get_request(resource_uri: str, name: str, **kwargs: Any) -> HttpReques "name": _SERIALIZER.url("name", name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -74,7 +77,7 @@ def build_create_or_update_request(resource_uri: str, name: str, **kwargs: Any) "name": _SERIALIZER.url("name", name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -101,7 +104,7 @@ def build_delete_request(resource_uri: str, name: str, **kwargs: Any) -> HttpReq "name": _SERIALIZER.url("name", name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -125,7 +128,7 @@ def build_list_request(resource_uri: str, **kwargs: Any) -> HttpRequest: "resourceUri": _SERIALIZER.url("resource_uri", resource_uri, "str", skip_quote=True), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -154,6 +157,7 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def get(self, resource_uri: str, name: str, **kwargs: Any) -> _models.DiagnosticSettingsResource: @@ -163,12 +167,11 @@ def get(self, resource_uri: str, name: str, **kwargs: Any) -> _models.Diagnostic :type resource_uri: str :param name: The name of the diagnostic setting. Required. :type name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: DiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2017_05_01_preview.models.DiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -179,23 +182,23 @@ def get(self, resource_uri: str, name: str, **kwargs: Any) -> _models.Diagnostic _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2017-05-01-preview") + ) cls: ClsType[_models.DiagnosticSettingsResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_uri=resource_uri, name=name, api_version=api_version, - template_url=self.get.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -205,14 +208,12 @@ def get(self, resource_uri: str, name: str, **kwargs: Any) -> _models.Diagnostic error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("DiagnosticSettingsResource", pipeline_response) + deserialized = self._deserialize("DiagnosticSettingsResource", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get.metadata = {"url": "/{resourceUri}/providers/Microsoft.Insights/diagnosticSettings/{name}"} + return deserialized # type: ignore @overload def create_or_update( @@ -235,7 +236,6 @@ def create_or_update( :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: DiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2017_05_01_preview.models.DiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: @@ -243,7 +243,13 @@ def create_or_update( @overload def create_or_update( - self, resource_uri: str, name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + self, + resource_uri: str, + name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any ) -> _models.DiagnosticSettingsResource: """Creates or updates diagnostic settings for the specified resource. @@ -252,11 +258,10 @@ def create_or_update( :param name: The name of the diagnostic setting. Required. :type name: str :param parameters: Parameters supplied to the operation. Required. - :type parameters: IO + :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: DiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2017_05_01_preview.models.DiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: @@ -264,7 +269,11 @@ def create_or_update( @distributed_trace def create_or_update( - self, resource_uri: str, name: str, parameters: Union[_models.DiagnosticSettingsResource, IO], **kwargs: Any + self, + resource_uri: str, + name: str, + parameters: Union[_models.DiagnosticSettingsResource, IO[bytes]], + **kwargs: Any ) -> _models.DiagnosticSettingsResource: """Creates or updates diagnostic settings for the specified resource. @@ -273,18 +282,14 @@ def create_or_update( :param name: The name of the diagnostic setting. Required. :type name: str :param parameters: Parameters supplied to the operation. Is either a DiagnosticSettingsResource - type or a IO type. Required. + type or a IO[bytes] type. Required. :type parameters: ~azure.mgmt.monitor.v2017_05_01_preview.models.DiagnosticSettingsResource 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 + IO[bytes] :return: DiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2017_05_01_preview.models.DiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -295,35 +300,35 @@ def create_or_update( _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", "2017-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2017-05-01-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.DiagnosticSettingsResource] = 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, "DiagnosticSettingsResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_uri=resource_uri, name=name, 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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -333,14 +338,12 @@ def create_or_update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("DiagnosticSettingsResource", pipeline_response) + deserialized = self._deserialize("DiagnosticSettingsResource", 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": "/{resourceUri}/providers/Microsoft.Insights/diagnosticSettings/{name}"} + return deserialized # type: ignore @distributed_trace def delete( # pylint: disable=inconsistent-return-statements @@ -352,12 +355,11 @@ def delete( # pylint: disable=inconsistent-return-statements :type resource_uri: str :param name: The name of the diagnostic setting. Required. :type 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, @@ -368,23 +370,23 @@ def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2017-05-01-preview") + ) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_uri=resource_uri, name=name, api_version=api_version, - template_url=self.delete.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -395,9 +397,7 @@ def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = {"url": "/{resourceUri}/providers/Microsoft.Insights/diagnosticSettings/{name}"} + return cls(pipeline_response, None, {}) # type: ignore @distributed_trace def list(self, resource_uri: str, **kwargs: Any) -> _models.DiagnosticSettingsResourceCollection: @@ -405,12 +405,11 @@ def list(self, resource_uri: str, **kwargs: Any) -> _models.DiagnosticSettingsRe :param resource_uri: The identifier of the resource. Required. :type resource_uri: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: DiagnosticSettingsResourceCollection or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2017_05_01_preview.models.DiagnosticSettingsResourceCollection :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -421,22 +420,22 @@ def list(self, resource_uri: str, **kwargs: Any) -> _models.DiagnosticSettingsRe _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2017-05-01-preview") + ) cls: ClsType[_models.DiagnosticSettingsResourceCollection] = kwargs.pop("cls", None) - request = build_list_request( + _request = build_list_request( resource_uri=resource_uri, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -446,11 +445,9 @@ def list(self, resource_uri: str, **kwargs: Any) -> _models.DiagnosticSettingsRe error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("DiagnosticSettingsResourceCollection", pipeline_response) + deserialized = self._deserialize("DiagnosticSettingsResourceCollection", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - list.metadata = {"url": "/{resourceUri}/providers/Microsoft.Insights/diagnosticSettings"} + return deserialized # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/operations/_metric_definitions_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/operations/_metric_definitions_operations.py index 335a3a180e77..07d6efa408e6 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/operations/_metric_definitions_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/operations/_metric_definitions_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,7 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, Callable, Dict, Iterable, Optional, TypeVar import urllib.parse @@ -19,16 +19,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, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -49,7 +51,7 @@ def build_list_request(resource_uri: str, **kwargs: Any) -> HttpRequest: "resourceUri": _SERIALIZER.url("resource_uri", resource_uri, "str", skip_quote=True), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -78,6 +80,7 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list(self, resource_uri: str, **kwargs: Any) -> Iterable["_models.MetricDefinition"]: @@ -85,7 +88,6 @@ def list(self, resource_uri: str, **kwargs: Any) -> Iterable["_models.MetricDefi :param resource_uri: The identifier of the resource. Required. :type resource_uri: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either MetricDefinition or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.monitor.v2017_05_01_preview.models.MetricDefinition] @@ -94,10 +96,12 @@ def list(self, resource_uri: str, **kwargs: Any) -> Iterable["_models.MetricDefi _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2017-05-01-preview") + ) cls: ClsType[_models.MetricDefinitionCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -108,15 +112,13 @@ def list(self, resource_uri: str, **kwargs: Any) -> Iterable["_models.MetricDefi def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( resource_uri=resource_uri, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -127,14 +129,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("MetricDefinitionCollection", pipeline_response) @@ -144,11 +145,11 @@ def extract_data(pipeline_response): return None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -160,5 +161,3 @@ def get_next(next_link=None): return pipeline_response return ItemPaged(get_next, extract_data) - - list.metadata = {"url": "/{resourceUri}/providers/microsoft.insights/metricDefinitions"} diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/operations/_metrics_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/operations/_metrics_operations.py index de3f7287bb16..fcc8de944694 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/operations/_metrics_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/operations/_metrics_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +6,7 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- import datetime +import sys from typing import Any, Callable, Dict, Optional, TypeVar, Union from azure.core.exceptions import ( @@ -18,16 +18,18 @@ map_error, ) 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 +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -60,7 +62,7 @@ def build_list_request( "resourceUri": _SERIALIZER.url("resource_uri", resource_uri, "str", skip_quote=True), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters if timespan is not None: @@ -105,6 +107,7 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list( @@ -144,24 +147,23 @@ def list( :type orderby: str :param filter: The **$filter** is used to reduce the set of metric data returned.:code:`
`Example::code:`
`Metric contains metadata A, B and C.:code:`
`- - Return all time series of C where A = a1 and B = b1 or b2:code:`
`\ **$filter=A eq ‘a1’ and - B eq ‘b1’ or B eq ‘b2’ and C eq ‘*’**\ :code:`
`- Invalid variant::code:`
`\ **$filter=A - eq ‘a1’ and B eq ‘b1’ and C eq ‘*’ or B = ‘b2’**\ :code:`
`This is invalid because the - logical or operator cannot separate two different metadata names.:code:`
`- Return all time - series where A = a1, B = b1 and C = c1::code:`
`\ **$filter=A eq ‘a1’ and B eq ‘b1’ and C eq - ‘c1’**\ :code:`
`- Return all time series where A = a1:code:`
`\ **$filter=A eq ‘a1’ and - B eq ‘\ *’ and C eq ‘*\ ’**. Default value is None. + Return all time series of C where A = a1 and B = b1 or b2:code:`
`\\ **$filter=A eq ‘a1’ and + B eq ‘b1’ or B eq ‘b2’ and C eq ‘*’**\\ :code:`
`- Invalid variant::code:`
`\\ + **$filter=A eq ‘a1’ and B eq ‘b1’ and C eq ‘*’ or B = ‘b2’**\\ :code:`
`This is invalid + because the logical or operator cannot separate two different metadata names.:code:`
`- + Return all time series where A = a1, B = b1 and C = c1::code:`
`\\ **$filter=A eq ‘a1’ and B + eq ‘b1’ and C eq ‘c1’**\\ :code:`
`- Return all time series where A = a1:code:`
`\\ + **$filter=A eq ‘a1’ and B eq ‘\\ *’ and C eq ‘*\\ ’**. Default value is None. :type filter: str :param result_type: Reduces the set of data collected. The syntax allowed depends on the operation. See the operation's description for details. Known values are: "Data" and "Metadata". Default value is None. :type result_type: str or ~azure.mgmt.monitor.v2017_05_01_preview.models.ResultType - :keyword callable cls: A custom type or function that will be passed the direct response :return: Response or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2017_05_01_preview.models.Response :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -172,10 +174,12 @@ def list( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2017-05-01-preview") + ) cls: ClsType[_models.Response] = kwargs.pop("cls", None) - request = build_list_request( + _request = build_list_request( resource_uri=resource_uri, timespan=timespan, interval=interval, @@ -186,16 +190,14 @@ def list( filter=filter, result_type=result_type, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -205,11 +207,9 @@ def list( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("Response", pipeline_response) + deserialized = self._deserialize("Response", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - list.metadata = {"url": "/{resourceUri}/providers/microsoft.insights/metrics"} + return deserialized # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/operations/_subscription_diagnostic_settings_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/operations/_subscription_diagnostic_settings_operations.py index c63a9c5463a6..b5a213ad9964 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/operations/_subscription_diagnostic_settings_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/operations/_subscription_diagnostic_settings_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload from azure.core.exceptions import ( @@ -17,16 +18,18 @@ map_error, ) 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 +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -50,7 +53,7 @@ def build_get_request(name: str, subscription_id: str, **kwargs: Any) -> HttpReq "name": _SERIALIZER.url("name", name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -78,7 +81,7 @@ def build_create_or_update_request(name: str, subscription_id: str, **kwargs: An "name": _SERIALIZER.url("name", name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -107,7 +110,7 @@ def build_delete_request(name: str, subscription_id: str, **kwargs: Any) -> Http "name": _SERIALIZER.url("name", name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -131,7 +134,7 @@ def build_list_request(subscription_id: str, **kwargs: Any) -> HttpRequest: "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -160,6 +163,7 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def get(self, name: str, **kwargs: Any) -> _models.SubscriptionDiagnosticSettingsResource: @@ -167,12 +171,11 @@ def get(self, name: str, **kwargs: Any) -> _models.SubscriptionDiagnosticSetting :param name: The name of the diagnostic setting. Required. :type name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: SubscriptionDiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2017_05_01_preview.models.SubscriptionDiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -183,23 +186,23 @@ def get(self, name: str, **kwargs: Any) -> _models.SubscriptionDiagnosticSetting _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2017-05-01-preview") + ) cls: ClsType[_models.SubscriptionDiagnosticSettingsResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( name=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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -209,14 +212,12 @@ def get(self, name: str, **kwargs: Any) -> _models.SubscriptionDiagnosticSetting error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("SubscriptionDiagnosticSettingsResource", pipeline_response) + deserialized = self._deserialize("SubscriptionDiagnosticSettingsResource", 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}/providers/microsoft.insights/diagnosticSettings/{name}"} + return deserialized # type: ignore @overload def create_or_update( @@ -237,7 +238,6 @@ def create_or_update( :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: SubscriptionDiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2017_05_01_preview.models.SubscriptionDiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: @@ -245,18 +245,17 @@ def create_or_update( @overload def create_or_update( - self, name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + self, name: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any ) -> _models.SubscriptionDiagnosticSettingsResource: """Creates or updates subscription diagnostic settings for the specified resource. :param name: The name of the diagnostic setting. Required. :type name: str :param parameters: Parameters supplied to the operation. Required. - :type parameters: IO + :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: SubscriptionDiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2017_05_01_preview.models.SubscriptionDiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: @@ -264,25 +263,22 @@ def create_or_update( @distributed_trace def create_or_update( - self, name: str, parameters: Union[_models.SubscriptionDiagnosticSettingsResource, IO], **kwargs: Any + self, name: str, parameters: Union[_models.SubscriptionDiagnosticSettingsResource, IO[bytes]], **kwargs: Any ) -> _models.SubscriptionDiagnosticSettingsResource: """Creates or updates subscription diagnostic settings for the specified resource. :param name: The name of the diagnostic setting. Required. :type name: str :param parameters: Parameters supplied to the operation. Is either a - SubscriptionDiagnosticSettingsResource type or a IO type. Required. + SubscriptionDiagnosticSettingsResource type or a IO[bytes] type. Required. :type parameters: - ~azure.mgmt.monitor.v2017_05_01_preview.models.SubscriptionDiagnosticSettingsResource 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 + ~azure.mgmt.monitor.v2017_05_01_preview.models.SubscriptionDiagnosticSettingsResource or + IO[bytes] :return: SubscriptionDiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2017_05_01_preview.models.SubscriptionDiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -293,35 +289,35 @@ def create_or_update( _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", "2017-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2017-05-01-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.SubscriptionDiagnosticSettingsResource] = 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, "SubscriptionDiagnosticSettingsResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( name=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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -331,16 +327,12 @@ def create_or_update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("SubscriptionDiagnosticSettingsResource", pipeline_response) + deserialized = self._deserialize("SubscriptionDiagnosticSettingsResource", 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}/providers/microsoft.insights/diagnosticSettings/{name}" - } + return deserialized # type: ignore @distributed_trace def delete(self, name: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements @@ -348,12 +340,11 @@ def delete(self, name: str, **kwargs: Any) -> None: # pylint: disable=inconsist :param name: The name of the diagnostic setting. Required. :type 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, @@ -364,23 +355,23 @@ def delete(self, name: str, **kwargs: Any) -> None: # pylint: disable=inconsist _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2017-05-01-preview") + ) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( name=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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -391,21 +382,18 @@ def delete(self, name: str, **kwargs: Any) -> None: # pylint: disable=inconsist raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = {"url": "/subscriptions/{subscriptionId}/providers/microsoft.insights/diagnosticSettings/{name}"} + return cls(pipeline_response, None, {}) # type: ignore @distributed_trace def list(self, **kwargs: Any) -> _models.SubscriptionDiagnosticSettingsResourceCollection: """Gets the active subscription diagnostic settings list for the specified subscriptionId. - :keyword callable cls: A custom type or function that will be passed the direct response :return: SubscriptionDiagnosticSettingsResourceCollection or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2017_05_01_preview.models.SubscriptionDiagnosticSettingsResourceCollection :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -416,22 +404,22 @@ def list(self, **kwargs: Any) -> _models.SubscriptionDiagnosticSettingsResourceC _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2017-05-01-preview") + ) cls: ClsType[_models.SubscriptionDiagnosticSettingsResourceCollection] = kwargs.pop("cls", None) - request = build_list_request( + _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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -441,11 +429,11 @@ def list(self, **kwargs: Any) -> _models.SubscriptionDiagnosticSettingsResourceC error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("SubscriptionDiagnosticSettingsResourceCollection", pipeline_response) + deserialized = self._deserialize( + "SubscriptionDiagnosticSettingsResourceCollection", pipeline_response.http_response + ) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/microsoft.insights/diagnosticSettings"} + return deserialized # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_12_01_preview/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_12_01_preview/__init__.py index 2c7733bfd566..42cc62301757 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_12_01_preview/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_12_01_preview/__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 ._monitor_management_client import MonitorManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._monitor_management_client import MonitorManagementClient # type: ignore from ._version import VERSION __version__ = VERSION try: from ._patch import __all__ as _patch_all - from ._patch import * # 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__ = [ "MonitorManagementClient", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_12_01_preview/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_12_01_preview/_configuration.py index 005178cd1407..f8b988de5ab2 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_12_01_preview/_configuration.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_12_01_preview/_configuration.py @@ -8,18 +8,16 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy from ._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MonitorManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class MonitorManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for MonitorManagementClient. Note that all parameters used to create this instance are saved as instance @@ -33,7 +31,6 @@ class MonitorManagementClientConfiguration(Configuration): # pylint: disable=to """ def __init__(self, credential: "TokenCredential", **kwargs: Any) -> None: - super(MonitorManagementClientConfiguration, self).__init__(**kwargs) api_version: str = kwargs.pop("api_version", "2017-12-01-preview") if credential is None: @@ -43,6 +40,7 @@ def __init__(self, credential: "TokenCredential", **kwargs: Any) -> None: self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-monitor/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -51,9 +49,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.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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_12_01_preview/_metadata.json b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_12_01_preview/_metadata.json index 19de87bd9d48..7b27f8e77ef2 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_12_01_preview/_metadata.json +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_12_01_preview/_metadata.json @@ -8,10 +8,10 @@ "host_value": "\"https://management.azure.com\"", "parameterized_host_template": null, "azure_arm": true, - "has_lro_operations": false, + "has_public_lro_operations": false, "client_side_validation": false, - "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"sdkcore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMAutoResourceProviderRegistrationPolicy\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}, \"stdlib\": {\"typing_extensions\": [\"Self\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"sdkcore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"AsyncARMAutoResourceProviderRegistrationPolicy\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}, \"stdlib\": {\"typing_extensions\": [\"Self\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "global_parameters": { "sync": { @@ -88,8 +88,8 @@ "credential_scopes": ["https://management.azure.com/.default"], "credential_call_sync": "ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", "credential_call_async": "AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", - "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "sync_imports": "{\"regular\": {\"sdkcore\": {\"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"regular\": {\"sdkcore\": {\"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "operation_groups": { "metric_namespaces": "MetricNamespacesOperations" diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_12_01_preview/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_12_01_preview/_monitor_management_client.py index 5bd19e332aaa..dfa4de104f57 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_12_01_preview/_monitor_management_client.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_12_01_preview/_monitor_management_client.py @@ -8,9 +8,12 @@ from copy import deepcopy from typing import Any, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient +from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy from . import models as _models from .._serialization import Deserializer, Serializer @@ -18,11 +21,10 @@ from .operations import MetricNamespacesOperations if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MonitorManagementClient: # pylint: disable=client-accepts-api-version-keyword +class MonitorManagementClient: """Monitor Management Client. :ivar metric_namespaces: MetricNamespacesOperations operations @@ -41,17 +43,35 @@ def __init__( self, credential: "TokenCredential", base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: self._config = MonitorManagementClientConfiguration(credential=credential, **kwargs) - self._client: ARMPipelineClient = ARMPipelineClient(base_url=base_url, config=self._config, **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), + 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=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.metric_namespaces = MetricNamespacesOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2017-12-01-preview" ) - 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 @@ -71,12 +91,12 @@ 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) -> None: self._client.close() - def __enter__(self) -> "MonitorManagementClient": + def __enter__(self) -> Self: self._client.__enter__() return self diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_12_01_preview/_vendor.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_12_01_preview/_vendor.py deleted file mode 100644 index bd0df84f5319..000000000000 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_12_01_preview/_vendor.py +++ /dev/null @@ -1,30 +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 typing import List, cast - -from azure.core.pipeline.transport import HttpRequest - - -def _convert_request(request, files=None): - data = request.content if not files else None - request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) - if files: - request.set_formdata_body(files) - return request - - -def _format_url_section(template, **kwargs): - components = template.split("/") - while components: - try: - return template.format(**kwargs) - except KeyError as key: - # Need the cast, as for some reasons "split" is typed as list[str | Any] - formatted_components = cast(List[str], template.split("/")) - components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] - template = "/".join(components) diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_12_01_preview/_version.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_12_01_preview/_version.py index 394ee7c0c03c..e5754a47ce68 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_12_01_preview/_version.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_12_01_preview/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "6.0.2" +VERSION = "1.0.0b1" diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_12_01_preview/aio/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_12_01_preview/aio/__init__.py index 2c151bb41c19..3df30ff42149 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_12_01_preview/aio/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_12_01_preview/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 ._monitor_management_client import MonitorManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._monitor_management_client import MonitorManagementClient # type: ignore try: from ._patch import __all__ as _patch_all - from ._patch import * # 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__ = [ "MonitorManagementClient", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_12_01_preview/aio/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_12_01_preview/aio/_configuration.py index e54d5ce7c1ef..9cd88ade3195 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_12_01_preview/aio/_configuration.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_12_01_preview/aio/_configuration.py @@ -8,18 +8,16 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy from .._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MonitorManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class MonitorManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for MonitorManagementClient. Note that all parameters used to create this instance are saved as instance @@ -33,7 +31,6 @@ class MonitorManagementClientConfiguration(Configuration): # pylint: disable=to """ def __init__(self, credential: "AsyncTokenCredential", **kwargs: Any) -> None: - super(MonitorManagementClientConfiguration, self).__init__(**kwargs) api_version: str = kwargs.pop("api_version", "2017-12-01-preview") if credential is None: @@ -43,6 +40,7 @@ def __init__(self, credential: "AsyncTokenCredential", **kwargs: Any) -> None: self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-monitor/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -51,9 +49,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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_12_01_preview/aio/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_12_01_preview/aio/_monitor_management_client.py index 498ac4155778..24e30ca4f1b4 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_12_01_preview/aio/_monitor_management_client.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_12_01_preview/aio/_monitor_management_client.py @@ -8,9 +8,12 @@ from copy import deepcopy from typing import Any, Awaitable, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient +from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy from .. import models as _models from ..._serialization import Deserializer, Serializer @@ -18,11 +21,10 @@ from .operations import MetricNamespacesOperations if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MonitorManagementClient: # pylint: disable=client-accepts-api-version-keyword +class MonitorManagementClient: """Monitor Management Client. :ivar metric_namespaces: MetricNamespacesOperations operations @@ -41,17 +43,37 @@ def __init__( self, credential: "AsyncTokenCredential", base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: self._config = MonitorManagementClientConfiguration(credential=credential, **kwargs) - self._client: AsyncARMPipelineClient = AsyncARMPipelineClient(base_url=base_url, config=self._config, **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=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.metric_namespaces = MetricNamespacesOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2017-12-01-preview" ) - 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 @@ -71,12 +93,12 @@ 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) -> "MonitorManagementClient": + async def __aenter__(self) -> Self: await self._client.__aenter__() return self diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_12_01_preview/aio/operations/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_12_01_preview/aio/operations/__init__.py index b230e557d823..5b8e73c930c0 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_12_01_preview/aio/operations/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_12_01_preview/aio/operations/__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 ._metric_namespaces_operations import MetricNamespacesOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._metric_namespaces_operations import MetricNamespacesOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ "MetricNamespacesOperations", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_12_01_preview/aio/operations/_metric_namespaces_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_12_01_preview/aio/operations/_metric_namespaces_operations.py index 93f2ea7416a0..dfa02bd2ebf9 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_12_01_preview/aio/operations/_metric_namespaces_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_12_01_preview/aio/operations/_metric_namespaces_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,7 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar import urllib.parse @@ -19,16 +19,18 @@ 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 ...operations._metric_namespaces_operations import build_list_request +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -51,6 +53,7 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list( @@ -63,7 +66,6 @@ def list( :param start_time: The ISO 8601 conform Date start time from which to query for metric namespaces. Default value is None. :type start_time: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either MetricNamespace or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.monitor.v2017_12_01_preview.models.MetricNamespace] @@ -72,10 +74,12 @@ def list( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2017-12-01-preview") + ) cls: ClsType[_models.MetricNamespaceCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -86,16 +90,14 @@ def list( def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( resource_uri=resource_uri, start_time=start_time, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -106,14 +108,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("MetricNamespaceCollection", pipeline_response) @@ -123,11 +124,11 @@ async def extract_data(pipeline_response): return None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -139,5 +140,3 @@ async def get_next(next_link=None): return pipeline_response return AsyncItemPaged(get_next, extract_data) - - list.metadata = {"url": "/{resourceUri}/providers/microsoft.insights/metricNamespaces"} diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_12_01_preview/models/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_12_01_preview/models/__init__.py index f4b8efc1b5b0..ecbfedc8b2c5 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_12_01_preview/models/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_12_01_preview/models/__init__.py @@ -5,15 +5,26 @@ # 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 ErrorResponse -from ._models_py3 import MetricNamespace -from ._models_py3 import MetricNamespaceCollection -from ._models_py3 import MetricNamespaceName +from typing import TYPE_CHECKING -from ._monitor_management_client_enums import NamespaceClassification +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models_py3 import ( # type: ignore + ErrorResponse, + MetricNamespace, + MetricNamespaceCollection, + MetricNamespaceName, +) + +from ._monitor_management_client_enums import ( # type: ignore + NamespaceClassification, +) from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ @@ -23,5 +34,5 @@ "MetricNamespaceName", "NamespaceClassification", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_12_01_preview/models/_models_py3.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_12_01_preview/models/_models_py3.py index 693997b7abe7..b91eabee3adb 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_12_01_preview/models/_models_py3.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_12_01_preview/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. @@ -12,7 +11,6 @@ from ... import _serialization if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from .. import models as _models @@ -100,7 +98,7 @@ def __init__( class MetricNamespaceCollection(_serialization.Model): """Represents collection of metric namespaces. - 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 value: The values for the metric namespaces. Required. :vartype value: list[~azure.mgmt.monitor.v2017_12_01_preview.models.MetricNamespace] diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_12_01_preview/operations/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_12_01_preview/operations/__init__.py index b230e557d823..5b8e73c930c0 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_12_01_preview/operations/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_12_01_preview/operations/__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 ._metric_namespaces_operations import MetricNamespacesOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._metric_namespaces_operations import MetricNamespacesOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ "MetricNamespacesOperations", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_12_01_preview/operations/_metric_namespaces_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_12_01_preview/operations/_metric_namespaces_operations.py index 77c5e20d065d..fdb9de0edb82 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_12_01_preview/operations/_metric_namespaces_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_12_01_preview/operations/_metric_namespaces_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,7 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, Callable, Dict, Iterable, Optional, TypeVar import urllib.parse @@ -19,16 +19,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, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -49,7 +51,7 @@ def build_list_request(resource_uri: str, *, start_time: Optional[str] = None, * "resourceUri": _SERIALIZER.url("resource_uri", resource_uri, "str", skip_quote=True), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -80,6 +82,7 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list( @@ -92,7 +95,6 @@ def list( :param start_time: The ISO 8601 conform Date start time from which to query for metric namespaces. Default value is None. :type start_time: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either MetricNamespace or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.monitor.v2017_12_01_preview.models.MetricNamespace] @@ -101,10 +103,12 @@ def list( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2017-12-01-preview") + ) cls: ClsType[_models.MetricNamespaceCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -115,16 +119,14 @@ def list( def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( resource_uri=resource_uri, start_time=start_time, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -135,14 +137,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("MetricNamespaceCollection", pipeline_response) @@ -152,11 +153,11 @@ def extract_data(pipeline_response): return None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -168,5 +169,3 @@ def get_next(next_link=None): return pipeline_response return ItemPaged(get_next, extract_data) - - list.metadata = {"url": "/{resourceUri}/providers/microsoft.insights/metricNamespaces"} diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_01_01/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_01_01/__init__.py index 2c7733bfd566..42cc62301757 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_01_01/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_01_01/__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 ._monitor_management_client import MonitorManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._monitor_management_client import MonitorManagementClient # type: ignore from ._version import VERSION __version__ = VERSION try: from ._patch import __all__ as _patch_all - from ._patch import * # 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__ = [ "MonitorManagementClient", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_01_01/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_01_01/_configuration.py index dad9cbbe64f2..1931809b3546 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_01_01/_configuration.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_01_01/_configuration.py @@ -8,18 +8,16 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy from ._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MonitorManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class MonitorManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for MonitorManagementClient. Note that all parameters used to create this instance are saved as instance @@ -33,7 +31,6 @@ class MonitorManagementClientConfiguration(Configuration): # pylint: disable=to """ def __init__(self, credential: "TokenCredential", **kwargs: Any) -> None: - super(MonitorManagementClientConfiguration, self).__init__(**kwargs) api_version: str = kwargs.pop("api_version", "2018-01-01") if credential is None: @@ -43,6 +40,7 @@ def __init__(self, credential: "TokenCredential", **kwargs: Any) -> None: self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-monitor/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -51,9 +49,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.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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_01_01/_metadata.json b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_01_01/_metadata.json index 1079b3dba290..c23bbbd3faba 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_01_01/_metadata.json +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_01_01/_metadata.json @@ -8,10 +8,10 @@ "host_value": "\"https://management.azure.com\"", "parameterized_host_template": null, "azure_arm": true, - "has_lro_operations": false, + "has_public_lro_operations": false, "client_side_validation": false, - "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"sdkcore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMAutoResourceProviderRegistrationPolicy\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}, \"stdlib\": {\"typing_extensions\": [\"Self\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"sdkcore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"AsyncARMAutoResourceProviderRegistrationPolicy\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}, \"stdlib\": {\"typing_extensions\": [\"Self\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "global_parameters": { "sync": { @@ -88,8 +88,8 @@ "credential_scopes": ["https://management.azure.com/.default"], "credential_call_sync": "ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", "credential_call_async": "AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", - "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "sync_imports": "{\"regular\": {\"sdkcore\": {\"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"regular\": {\"sdkcore\": {\"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "operation_groups": { "metric_definitions": "MetricDefinitionsOperations", diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_01_01/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_01_01/_monitor_management_client.py index 7bbaa65c81e9..b72cf2c829d6 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_01_01/_monitor_management_client.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_01_01/_monitor_management_client.py @@ -8,9 +8,12 @@ from copy import deepcopy from typing import Any, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient +from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy from . import models as _models from .._serialization import Deserializer, Serializer @@ -18,11 +21,10 @@ from .operations import MetricDefinitionsOperations, MetricsOperations if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MonitorManagementClient: # pylint: disable=client-accepts-api-version-keyword +class MonitorManagementClient: """Monitor Management Client. :ivar metric_definitions: MetricDefinitionsOperations operations @@ -43,18 +45,36 @@ def __init__( self, credential: "TokenCredential", base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: self._config = MonitorManagementClientConfiguration(credential=credential, **kwargs) - self._client: ARMPipelineClient = ARMPipelineClient(base_url=base_url, config=self._config, **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), + 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=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.metric_definitions = MetricDefinitionsOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2018-01-01" ) - self.metrics = MetricsOperations(self._client, self._config, self._serialize, self._deserialize) + self.metrics = MetricsOperations(self._client, self._config, self._serialize, self._deserialize, "2018-01-01") - 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 @@ -74,12 +94,12 @@ 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) -> None: self._client.close() - def __enter__(self) -> "MonitorManagementClient": + def __enter__(self) -> Self: self._client.__enter__() return self diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_01_01/_vendor.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_01_01/_vendor.py deleted file mode 100644 index bd0df84f5319..000000000000 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_01_01/_vendor.py +++ /dev/null @@ -1,30 +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 typing import List, cast - -from azure.core.pipeline.transport import HttpRequest - - -def _convert_request(request, files=None): - data = request.content if not files else None - request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) - if files: - request.set_formdata_body(files) - return request - - -def _format_url_section(template, **kwargs): - components = template.split("/") - while components: - try: - return template.format(**kwargs) - except KeyError as key: - # Need the cast, as for some reasons "split" is typed as list[str | Any] - formatted_components = cast(List[str], template.split("/")) - components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] - template = "/".join(components) diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_01_01/_version.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_01_01/_version.py index 394ee7c0c03c..e5754a47ce68 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_01_01/_version.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_01_01/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "6.0.2" +VERSION = "1.0.0b1" diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_01_01/aio/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_01_01/aio/__init__.py index 2c151bb41c19..3df30ff42149 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_01_01/aio/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_01_01/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 ._monitor_management_client import MonitorManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._monitor_management_client import MonitorManagementClient # type: ignore try: from ._patch import __all__ as _patch_all - from ._patch import * # 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__ = [ "MonitorManagementClient", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_01_01/aio/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_01_01/aio/_configuration.py index 30af6193b9be..45917e9fb6c4 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_01_01/aio/_configuration.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_01_01/aio/_configuration.py @@ -8,18 +8,16 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy from .._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MonitorManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class MonitorManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for MonitorManagementClient. Note that all parameters used to create this instance are saved as instance @@ -33,7 +31,6 @@ class MonitorManagementClientConfiguration(Configuration): # pylint: disable=to """ def __init__(self, credential: "AsyncTokenCredential", **kwargs: Any) -> None: - super(MonitorManagementClientConfiguration, self).__init__(**kwargs) api_version: str = kwargs.pop("api_version", "2018-01-01") if credential is None: @@ -43,6 +40,7 @@ def __init__(self, credential: "AsyncTokenCredential", **kwargs: Any) -> None: self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-monitor/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -51,9 +49,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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_01_01/aio/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_01_01/aio/_monitor_management_client.py index 9d4f4ccbcc59..a4f878fae50c 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_01_01/aio/_monitor_management_client.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_01_01/aio/_monitor_management_client.py @@ -8,9 +8,12 @@ from copy import deepcopy from typing import Any, Awaitable, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient +from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy from .. import models as _models from ..._serialization import Deserializer, Serializer @@ -18,11 +21,10 @@ from .operations import MetricDefinitionsOperations, MetricsOperations if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MonitorManagementClient: # pylint: disable=client-accepts-api-version-keyword +class MonitorManagementClient: """Monitor Management Client. :ivar metric_definitions: MetricDefinitionsOperations operations @@ -43,18 +45,38 @@ def __init__( self, credential: "AsyncTokenCredential", base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: self._config = MonitorManagementClientConfiguration(credential=credential, **kwargs) - self._client: AsyncARMPipelineClient = AsyncARMPipelineClient(base_url=base_url, config=self._config, **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=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.metric_definitions = MetricDefinitionsOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2018-01-01" ) - self.metrics = MetricsOperations(self._client, self._config, self._serialize, self._deserialize) + self.metrics = MetricsOperations(self._client, self._config, self._serialize, self._deserialize, "2018-01-01") - 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 @@ -74,12 +96,12 @@ 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) -> "MonitorManagementClient": + async def __aenter__(self) -> Self: await self._client.__aenter__() return self diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_01_01/aio/operations/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_01_01/aio/operations/__init__.py index d46ec2816fa2..fea606c9eb1e 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_01_01/aio/operations/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_01_01/aio/operations/__init__.py @@ -5,17 +5,23 @@ # 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 ._metric_definitions_operations import MetricDefinitionsOperations -from ._metrics_operations import MetricsOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._metric_definitions_operations import MetricDefinitionsOperations # type: ignore +from ._metrics_operations import MetricsOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ "MetricDefinitionsOperations", "MetricsOperations", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_01_01/aio/operations/_metric_definitions_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_01_01/aio/operations/_metric_definitions_operations.py index 26fc057e4a01..b55a3c30d620 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_01_01/aio/operations/_metric_definitions_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_01_01/aio/operations/_metric_definitions_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,7 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar import urllib.parse @@ -19,16 +19,18 @@ 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 ...operations._metric_definitions_operations import build_list_request +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -51,6 +53,7 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list( @@ -63,7 +66,6 @@ def list( :param metricnamespace: Metric namespace to query metric definitions for. Default value is None. :type metricnamespace: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either MetricDefinition or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.monitor.v2018_01_01.models.MetricDefinition] @@ -72,10 +74,10 @@ def list( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2018-01-01")) cls: ClsType[_models.MetricDefinitionCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -86,16 +88,14 @@ def list( def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( resource_uri=resource_uri, metricnamespace=metricnamespace, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -106,14 +106,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("MetricDefinitionCollection", pipeline_response) @@ -123,11 +122,11 @@ async def extract_data(pipeline_response): return None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -139,5 +138,3 @@ async def get_next(next_link=None): return pipeline_response return AsyncItemPaged(get_next, extract_data) - - list.metadata = {"url": "/{resourceUri}/providers/Microsoft.Insights/metricDefinitions"} diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_01_01/aio/operations/_metrics_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_01_01/aio/operations/_metrics_operations.py index 5c172137628b..4c8df676dfab 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_01_01/aio/operations/_metrics_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_01_01/aio/operations/_metrics_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,7 +5,7 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import datetime +import sys from typing import Any, Callable, Dict, Optional, TypeVar, Union from azure.core.exceptions import ( @@ -18,16 +17,18 @@ 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_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._metrics_operations import build_list_request +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -50,13 +51,14 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace_async async def list( self, resource_uri: str, timespan: Optional[str] = None, - interval: Optional[datetime.timedelta] = None, + interval: Optional[str] = None, metricnames: Optional[str] = None, aggregation: Optional[str] = None, top: Optional[int] = None, @@ -73,8 +75,11 @@ async def list( :param timespan: The timespan of the query. It is a string with the following format 'startDateTime_ISO/endDateTime_ISO'. Default value is None. :type timespan: str - :param interval: The interval (i.e. timegrain) of the query. Default value is None. - :type interval: ~datetime.timedelta + :param interval: The interval (i.e. timegrain) of the query in ISO 8601 duration format. + Defaults to PT1M. Special case for 'FULL' value that returns single datapoint for entire time + span requested. + *Examples: PT15M, PT1H, P1D, FULL*. Default value is None. + :type interval: str :param metricnames: The names of the metrics (comma separated) to retrieve. Special case: If a metricname itself has a comma in it then use %2 to indicate it. Eg: 'Metric,Name1' should be **'Metric%2Name1'**. Default value is None. @@ -96,12 +101,12 @@ async def list( eq 'a1' and B eq 'b1' and C eq '*' or B = 'b2'** This is invalid because the logical or operator cannot separate two different metadata names. - Return all time series where A = a1, B = b1 and C = c1: **$filter=A eq 'a1' and B eq 'b1' and C eq 'c1'** - Return all time series - where A = a1 **$filter=A eq 'a1' and B eq '\ *' and C eq '*\ '**. Special case: When dimension - name or dimension value uses round brackets. Eg: When dimension name is **dim (test) 1** - Instead of using $filter= "dim (test) 1 eq '\ *' " use **$filter= "dim %2528test%2529 1 eq '*\ - ' "\ ** When dimension name is **\ dim (test) 3\ ** and dimension value is **\ dim3 (test) val\ - ** Instead of using $filter= "dim (test) 3 eq 'dim3 (test) val' " use **\ $filter= "dim - %2528test%2529 3 eq 'dim3 %2528test%2529 val' "**. Default value is None. + where A = a1 **$filter=A eq 'a1' and B eq '\\ *' and C eq '*\\ '**. Special case: When + dimension name or dimension value uses round brackets. Eg: When dimension name is **dim (test) + 1** Instead of using $filter= "dim (test) 1 eq '\\ *' " use **$filter= "dim %2528test%2529 1 eq + '*\\ ' "\\ ** When dimension name is **\\ dim (test) 3\\ ** and dimension value is **\\ dim3 + (test) val\\ ** Instead of using $filter= "dim (test) 3 eq 'dim3 (test) val' " use **\\ + $filter= "dim %2528test%2529 3 eq 'dim3 %2528test%2529 val' "**. Default value is None. :type filter: str :param result_type: Reduces the set of data collected. The syntax allowed depends on the operation. See the operation's description for details. Known values are: "Data" and @@ -110,12 +115,11 @@ async def list( :param metricnamespace: Metric namespace to query metric definitions for. Default value is None. :type metricnamespace: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: Response or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_01_01.models.Response :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -126,10 +130,10 @@ async def list( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2018-01-01")) cls: ClsType[_models.Response] = kwargs.pop("cls", None) - request = build_list_request( + _request = build_list_request( resource_uri=resource_uri, timespan=timespan, interval=interval, @@ -141,16 +145,14 @@ async def list( result_type=result_type, metricnamespace=metricnamespace, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -160,11 +162,9 @@ async def list( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("Response", pipeline_response) + deserialized = self._deserialize("Response", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - list.metadata = {"url": "/{resourceUri}/providers/Microsoft.Insights/metrics"} + return deserialized # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_01_01/models/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_01_01/models/__init__.py index f3737db3f508..fc39eea99f52 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_01_01/models/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_01_01/models/__init__.py @@ -5,24 +5,35 @@ # 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 ErrorResponse -from ._models_py3 import LocalizableString -from ._models_py3 import MetadataValue -from ._models_py3 import Metric -from ._models_py3 import MetricAvailability -from ._models_py3 import MetricDefinition -from ._models_py3 import MetricDefinitionCollection -from ._models_py3 import MetricValue -from ._models_py3 import Response -from ._models_py3 import TimeSeriesElement +from typing import TYPE_CHECKING -from ._monitor_management_client_enums import AggregationType -from ._monitor_management_client_enums import MetricClass -from ._monitor_management_client_enums import MetricUnit -from ._monitor_management_client_enums import ResultType +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models_py3 import ( # type: ignore + ErrorResponse, + LocalizableString, + MetadataValue, + Metric, + MetricAvailability, + MetricDefinition, + MetricDefinitionCollection, + MetricValue, + Response, + TimeSeriesElement, +) + +from ._monitor_management_client_enums import ( # type: ignore + AggregationType, + MetricClass, + MetricUnit, + ResultType, +) from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ @@ -41,5 +52,5 @@ "MetricUnit", "ResultType", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_01_01/models/_models_py3.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_01_01/models/_models_py3.py index 88a98ad0be9f..4d78711d0c5e 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_01_01/models/_models_py3.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_01_01/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. @@ -13,7 +12,6 @@ from ... import _serialization if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from .. import models as _models @@ -46,11 +44,11 @@ def __init__(self, *, code: Optional[str] = None, message: Optional[str] = None, class LocalizableString(_serialization.Model): """The localizable string class. - 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 value: the invariant value. Required. + :ivar value: The invariant value. Required. :vartype value: str - :ivar localized_value: the locale specific value. + :ivar localized_value: The display name. :vartype localized_value: str """ @@ -65,9 +63,9 @@ class LocalizableString(_serialization.Model): def __init__(self, *, value: str, localized_value: Optional[str] = None, **kwargs: Any) -> None: """ - :keyword value: the invariant value. Required. + :keyword value: The invariant value. Required. :paramtype value: str - :keyword localized_value: the locale specific value. + :keyword localized_value: The display name. :paramtype localized_value: str """ super().__init__(**kwargs) @@ -78,9 +76,9 @@ def __init__(self, *, value: str, localized_value: Optional[str] = None, **kwarg class MetadataValue(_serialization.Model): """Represents a metric metadata value. - :ivar name: the name of the metadata. + :ivar name: The name of the metadata. :vartype name: ~azure.mgmt.monitor.v2018_01_01.models.LocalizableString - :ivar value: the value of the metadata. + :ivar value: The value of the metadata. :vartype value: str """ @@ -93,9 +91,9 @@ def __init__( self, *, name: Optional["_models.LocalizableString"] = None, value: Optional[str] = None, **kwargs: Any ) -> None: """ - :keyword name: the name of the metadata. + :keyword name: The name of the metadata. :paramtype name: ~azure.mgmt.monitor.v2018_01_01.models.LocalizableString - :keyword value: the value of the metadata. + :keyword value: The value of the metadata. :paramtype value: str """ super().__init__(**kwargs) @@ -106,13 +104,13 @@ def __init__( class Metric(_serialization.Model): """The result data of a query. - 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: the metric Id. Required. + :ivar id: The metric Id. Required. :vartype id: str - :ivar type: the resource type of the metric resource. Required. + :ivar type: The resource type of the metric resource. Required. :vartype type: str - :ivar name: the name and the display name of the metric, i.e. it is localizable string. + :ivar name: The name and the display name of the metric, i.e. it is localizable string. Required. :vartype name: ~azure.mgmt.monitor.v2018_01_01.models.LocalizableString :ivar display_description: Detailed description of this metric. @@ -125,7 +123,7 @@ class Metric(_serialization.Model): "CountPerSecond", "BytesPerSecond", "Percent", "MilliSeconds", "ByteSeconds", "Unspecified", "Cores", "MilliCores", "NanoCores", and "BitsPerSecond". :vartype unit: str or ~azure.mgmt.monitor.v2018_01_01.models.MetricUnit - :ivar timeseries: the time series returned when a data query is performed. Required. + :ivar timeseries: The time series returned when a data query is performed. Required. :vartype timeseries: list[~azure.mgmt.monitor.v2018_01_01.models.TimeSeriesElement] """ @@ -162,11 +160,11 @@ def __init__( **kwargs: Any ) -> None: """ - :keyword id: the metric Id. Required. + :keyword id: The metric Id. Required. :paramtype id: str - :keyword type: the resource type of the metric resource. Required. + :keyword type: The resource type of the metric resource. Required. :paramtype type: str - :keyword name: the name and the display name of the metric, i.e. it is localizable string. + :keyword name: The name and the display name of the metric, i.e. it is localizable string. Required. :paramtype name: ~azure.mgmt.monitor.v2018_01_01.models.LocalizableString :keyword display_description: Detailed description of this metric. @@ -179,7 +177,7 @@ def __init__( "CountPerSecond", "BytesPerSecond", "Percent", "MilliSeconds", "ByteSeconds", "Unspecified", "Cores", "MilliCores", "NanoCores", and "BitsPerSecond". :paramtype unit: str or ~azure.mgmt.monitor.v2018_01_01.models.MetricUnit - :keyword timeseries: the time series returned when a data query is performed. Required. + :keyword timeseries: The time series returned when a data query is performed. Required. :paramtype timeseries: list[~azure.mgmt.monitor.v2018_01_01.models.TimeSeriesElement] """ super().__init__(**kwargs) @@ -230,7 +228,7 @@ def __init__( self.retention = retention -class MetricDefinition(_serialization.Model): # pylint: disable=too-many-instance-attributes +class MetricDefinition(_serialization.Model): """Metric definition class specifies the metadata for a metric. :ivar is_dimension_required: Flag to indicate whether the dimension is required. @@ -361,7 +359,7 @@ def __init__( class MetricDefinitionCollection(_serialization.Model): """Represents collection of metric definitions. - 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 value: the values for the metric definitions. Required. :vartype value: list[~azure.mgmt.monitor.v2018_01_01.models.MetricDefinition] @@ -387,19 +385,19 @@ def __init__(self, *, value: List["_models.MetricDefinition"], **kwargs: Any) -> class MetricValue(_serialization.Model): """Represents a metric value. - 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 time_stamp: the timestamp for the metric value in ISO 8601 format. Required. + :ivar time_stamp: The timestamp for the metric value in ISO 8601 format. Required. :vartype time_stamp: ~datetime.datetime - :ivar average: the average value in the time range. + :ivar average: The average value in the time range. :vartype average: float - :ivar minimum: the least value in the time range. + :ivar minimum: The least value in the time range. :vartype minimum: float - :ivar maximum: the greatest value in the time range. + :ivar maximum: The greatest value in the time range. :vartype maximum: float - :ivar total: the sum of all of the values in the time range. + :ivar total: The sum of all of the values in the time range. :vartype total: float - :ivar count: the number of samples in the time range. Can be used to determine the number of + :ivar count: The number of samples in the time range. Can be used to determine the number of values that contributed to the average value. :vartype count: float """ @@ -429,17 +427,17 @@ def __init__( **kwargs: Any ) -> None: """ - :keyword time_stamp: the timestamp for the metric value in ISO 8601 format. Required. + :keyword time_stamp: The timestamp for the metric value in ISO 8601 format. Required. :paramtype time_stamp: ~datetime.datetime - :keyword average: the average value in the time range. + :keyword average: The average value in the time range. :paramtype average: float - :keyword minimum: the least value in the time range. + :keyword minimum: The least value in the time range. :paramtype minimum: float - :keyword maximum: the greatest value in the time range. + :keyword maximum: The greatest value in the time range. :paramtype maximum: float - :keyword total: the sum of all of the values in the time range. + :keyword total: The sum of all of the values in the time range. :paramtype total: float - :keyword count: the number of samples in the time range. Can be used to determine the number of + :keyword count: The number of samples in the time range. Can be used to determine the number of values that contributed to the average value. :paramtype count: float """ @@ -455,7 +453,7 @@ def __init__( class Response(_serialization.Model): """The response to a metrics query. - 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 cost: The integer value representing the relative cost of the query. :vartype cost: int @@ -463,10 +461,12 @@ class Response(_serialization.Model): datetimes concatenated, separated by '/'. This may be adjusted in the future and returned back from what was originally requested. Required. :vartype timespan: str - :ivar interval: The interval (window size) for which the metric data was returned in. This may - be adjusted in the future and returned back from what was originally requested. This is not - present if a metadata request was made. - :vartype interval: ~datetime.timedelta + :ivar interval: The interval (window size) for which the metric data was returned in ISO 8601 + duration format with a special case for 'FULL' value that returns single datapoint for entire + time span requested (\\ *Examples: PT15M, PT1H, P1D, FULL*\\ ). + This may be adjusted and different from what was originally requested if + AutoAdjustTimegrain=true is specified. This is not present if a metadata request was made. + :vartype interval: str :ivar namespace: The namespace of the metrics being queried. :vartype namespace: str :ivar resourceregion: The region of the resource being queried for metrics. @@ -484,7 +484,7 @@ class Response(_serialization.Model): _attribute_map = { "cost": {"key": "cost", "type": "int"}, "timespan": {"key": "timespan", "type": "str"}, - "interval": {"key": "interval", "type": "duration"}, + "interval": {"key": "interval", "type": "str"}, "namespace": {"key": "namespace", "type": "str"}, "resourceregion": {"key": "resourceregion", "type": "str"}, "value": {"key": "value", "type": "[Metric]"}, @@ -496,7 +496,7 @@ def __init__( timespan: str, value: List["_models.Metric"], cost: Optional[int] = None, - interval: Optional[datetime.timedelta] = None, + interval: Optional[str] = None, namespace: Optional[str] = None, resourceregion: Optional[str] = None, **kwargs: Any @@ -508,10 +508,12 @@ def __init__( datetimes concatenated, separated by '/'. This may be adjusted in the future and returned back from what was originally requested. Required. :paramtype timespan: str - :keyword interval: The interval (window size) for which the metric data was returned in. This - may be adjusted in the future and returned back from what was originally requested. This is - not present if a metadata request was made. - :paramtype interval: ~datetime.timedelta + :keyword interval: The interval (window size) for which the metric data was returned in ISO + 8601 duration format with a special case for 'FULL' value that returns single datapoint for + entire time span requested (\\ *Examples: PT15M, PT1H, P1D, FULL*\\ ). + This may be adjusted and different from what was originally requested if + AutoAdjustTimegrain=true is specified. This is not present if a metadata request was made. + :paramtype interval: str :keyword namespace: The namespace of the metrics being queried. :paramtype namespace: str :keyword resourceregion: The region of the resource being queried for metrics. @@ -531,7 +533,7 @@ def __init__( class TimeSeriesElement(_serialization.Model): """A time series result type. The discriminator value is always TimeSeries in this case. - :ivar metadatavalues: the metadata values returned if $filter was specified in the call. + :ivar metadatavalues: The metadata values returned if $filter was specified in the call. :vartype metadatavalues: list[~azure.mgmt.monitor.v2018_01_01.models.MetadataValue] :ivar data: An array of data points representing the metric values. This is only returned if a result type of data is specified. @@ -551,7 +553,7 @@ def __init__( **kwargs: Any ) -> None: """ - :keyword metadatavalues: the metadata values returned if $filter was specified in the call. + :keyword metadatavalues: The metadata values returned if $filter was specified in the call. :paramtype metadatavalues: list[~azure.mgmt.monitor.v2018_01_01.models.MetadataValue] :keyword data: An array of data points representing the metric values. This is only returned if a result type of data is specified. diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_01_01/operations/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_01_01/operations/__init__.py index d46ec2816fa2..fea606c9eb1e 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_01_01/operations/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_01_01/operations/__init__.py @@ -5,17 +5,23 @@ # 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 ._metric_definitions_operations import MetricDefinitionsOperations -from ._metrics_operations import MetricsOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._metric_definitions_operations import MetricDefinitionsOperations # type: ignore +from ._metrics_operations import MetricsOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ "MetricDefinitionsOperations", "MetricsOperations", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_01_01/operations/_metric_definitions_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_01_01/operations/_metric_definitions_operations.py index e05031c23f5d..3176a26a8c42 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_01_01/operations/_metric_definitions_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_01_01/operations/_metric_definitions_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,7 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, Callable, Dict, Iterable, Optional, TypeVar import urllib.parse @@ -19,16 +19,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, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -49,7 +51,7 @@ def build_list_request(resource_uri: str, *, metricnamespace: Optional[str] = No "resourceUri": _SERIALIZER.url("resource_uri", resource_uri, "str", skip_quote=True), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -80,6 +82,7 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list( @@ -92,7 +95,6 @@ def list( :param metricnamespace: Metric namespace to query metric definitions for. Default value is None. :type metricnamespace: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either MetricDefinition or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.monitor.v2018_01_01.models.MetricDefinition] :raises ~azure.core.exceptions.HttpResponseError: @@ -100,10 +102,10 @@ def list( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2018-01-01")) cls: ClsType[_models.MetricDefinitionCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -114,16 +116,14 @@ def list( def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( resource_uri=resource_uri, metricnamespace=metricnamespace, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -134,14 +134,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("MetricDefinitionCollection", pipeline_response) @@ -151,11 +150,11 @@ def extract_data(pipeline_response): return None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -167,5 +166,3 @@ def get_next(next_link=None): return pipeline_response return ItemPaged(get_next, extract_data) - - list.metadata = {"url": "/{resourceUri}/providers/Microsoft.Insights/metricDefinitions"} diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_01_01/operations/_metrics_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_01_01/operations/_metrics_operations.py index 98a050c3c00f..674ff69399a9 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_01_01/operations/_metrics_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_01_01/operations/_metrics_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,7 +5,7 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import datetime +import sys from typing import Any, Callable, Dict, Optional, TypeVar, Union from azure.core.exceptions import ( @@ -18,16 +17,18 @@ map_error, ) 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 +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -39,7 +40,7 @@ def build_list_request( resource_uri: str, *, timespan: Optional[str] = None, - interval: Optional[datetime.timedelta] = None, + interval: Optional[str] = None, metricnames: Optional[str] = None, aggregation: Optional[str] = None, top: Optional[int] = None, @@ -61,13 +62,13 @@ def build_list_request( "resourceUri": _SERIALIZER.url("resource_uri", resource_uri, "str", skip_quote=True), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters if timespan is not None: _params["timespan"] = _SERIALIZER.query("timespan", timespan, "str") if interval is not None: - _params["interval"] = _SERIALIZER.query("interval", interval, "duration") + _params["interval"] = _SERIALIZER.query("interval", interval, "str") if metricnames is not None: _params["metricnames"] = _SERIALIZER.query("metricnames", metricnames, "str") if aggregation is not None: @@ -108,13 +109,14 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list( self, resource_uri: str, timespan: Optional[str] = None, - interval: Optional[datetime.timedelta] = None, + interval: Optional[str] = None, metricnames: Optional[str] = None, aggregation: Optional[str] = None, top: Optional[int] = None, @@ -131,8 +133,11 @@ def list( :param timespan: The timespan of the query. It is a string with the following format 'startDateTime_ISO/endDateTime_ISO'. Default value is None. :type timespan: str - :param interval: The interval (i.e. timegrain) of the query. Default value is None. - :type interval: ~datetime.timedelta + :param interval: The interval (i.e. timegrain) of the query in ISO 8601 duration format. + Defaults to PT1M. Special case for 'FULL' value that returns single datapoint for entire time + span requested. + *Examples: PT15M, PT1H, P1D, FULL*. Default value is None. + :type interval: str :param metricnames: The names of the metrics (comma separated) to retrieve. Special case: If a metricname itself has a comma in it then use %2 to indicate it. Eg: 'Metric,Name1' should be **'Metric%2Name1'**. Default value is None. @@ -154,12 +159,12 @@ def list( eq 'a1' and B eq 'b1' and C eq '*' or B = 'b2'** This is invalid because the logical or operator cannot separate two different metadata names. - Return all time series where A = a1, B = b1 and C = c1: **$filter=A eq 'a1' and B eq 'b1' and C eq 'c1'** - Return all time series - where A = a1 **$filter=A eq 'a1' and B eq '\ *' and C eq '*\ '**. Special case: When dimension - name or dimension value uses round brackets. Eg: When dimension name is **dim (test) 1** - Instead of using $filter= "dim (test) 1 eq '\ *' " use **$filter= "dim %2528test%2529 1 eq '*\ - ' "\ ** When dimension name is **\ dim (test) 3\ ** and dimension value is **\ dim3 (test) val\ - ** Instead of using $filter= "dim (test) 3 eq 'dim3 (test) val' " use **\ $filter= "dim - %2528test%2529 3 eq 'dim3 %2528test%2529 val' "**. Default value is None. + where A = a1 **$filter=A eq 'a1' and B eq '\\ *' and C eq '*\\ '**. Special case: When + dimension name or dimension value uses round brackets. Eg: When dimension name is **dim (test) + 1** Instead of using $filter= "dim (test) 1 eq '\\ *' " use **$filter= "dim %2528test%2529 1 eq + '*\\ ' "\\ ** When dimension name is **\\ dim (test) 3\\ ** and dimension value is **\\ dim3 + (test) val\\ ** Instead of using $filter= "dim (test) 3 eq 'dim3 (test) val' " use **\\ + $filter= "dim %2528test%2529 3 eq 'dim3 %2528test%2529 val' "**. Default value is None. :type filter: str :param result_type: Reduces the set of data collected. The syntax allowed depends on the operation. See the operation's description for details. Known values are: "Data" and @@ -168,12 +173,11 @@ def list( :param metricnamespace: Metric namespace to query metric definitions for. Default value is None. :type metricnamespace: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: Response or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_01_01.models.Response :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -184,10 +188,10 @@ def list( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2018-01-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2018-01-01")) cls: ClsType[_models.Response] = kwargs.pop("cls", None) - request = build_list_request( + _request = build_list_request( resource_uri=resource_uri, timespan=timespan, interval=interval, @@ -199,16 +203,14 @@ def list( result_type=result_type, metricnamespace=metricnamespace, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -218,11 +220,9 @@ def list( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("Response", pipeline_response) + deserialized = self._deserialize("Response", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - list.metadata = {"url": "/{resourceUri}/providers/Microsoft.Insights/metrics"} + return deserialized # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/__init__.py index 2c7733bfd566..42cc62301757 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/__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 ._monitor_management_client import MonitorManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._monitor_management_client import MonitorManagementClient # type: ignore from ._version import VERSION __version__ = VERSION try: from ._patch import __all__ as _patch_all - from ._patch import * # 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__ = [ "MonitorManagementClient", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/_configuration.py index 73b44f979f35..a85bfe06fd5c 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/_configuration.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/_configuration.py @@ -8,18 +8,16 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy from ._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MonitorManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class MonitorManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for MonitorManagementClient. Note that all parameters used to create this instance are saved as instance @@ -35,7 +33,6 @@ class MonitorManagementClientConfiguration(Configuration): # pylint: disable=to """ def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: - super(MonitorManagementClientConfiguration, self).__init__(**kwargs) api_version: str = kwargs.pop("api_version", "2018-03-01") if credential is None: @@ -48,6 +45,7 @@ def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-monitor/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -56,9 +54,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.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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/_metadata.json b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/_metadata.json index 4460b40de763..076013e057c6 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/_metadata.json +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/_metadata.json @@ -8,10 +8,10 @@ "host_value": "\"https://management.azure.com\"", "parameterized_host_template": null, "azure_arm": true, - "has_lro_operations": false, + "has_public_lro_operations": false, "client_side_validation": false, - "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"sdkcore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMAutoResourceProviderRegistrationPolicy\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}, \"stdlib\": {\"typing_extensions\": [\"Self\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"sdkcore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"AsyncARMAutoResourceProviderRegistrationPolicy\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}, \"stdlib\": {\"typing_extensions\": [\"Self\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "global_parameters": { "sync": { @@ -101,8 +101,8 @@ "credential_scopes": ["https://management.azure.com/.default"], "credential_call_sync": "ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", "credential_call_async": "AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", - "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "sync_imports": "{\"regular\": {\"sdkcore\": {\"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"regular\": {\"sdkcore\": {\"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "operation_groups": { "action_groups": "ActionGroupsOperations", diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/_monitor_management_client.py index 57c2ad370725..f366f0f4c31f 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/_monitor_management_client.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/_monitor_management_client.py @@ -8,9 +8,12 @@ from copy import deepcopy from typing import Any, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient +from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy from . import models as _models from .._serialization import Deserializer, Serializer @@ -18,11 +21,10 @@ from .operations import ActionGroupsOperations, MetricAlertsOperations, MetricAlertsStatusOperations if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MonitorManagementClient: # pylint: disable=client-accepts-api-version-keyword +class MonitorManagementClient: """Monitor Management Client. :ivar action_groups: ActionGroupsOperations operations @@ -53,19 +55,41 @@ def __init__( self._config = MonitorManagementClientConfiguration( credential=credential, subscription_id=subscription_id, **kwargs ) - self._client: ARMPipelineClient = ARMPipelineClient(base_url=base_url, config=self._config, **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), + 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=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.action_groups = ActionGroupsOperations(self._client, self._config, self._serialize, self._deserialize) - self.metric_alerts = MetricAlertsOperations(self._client, self._config, self._serialize, self._deserialize) + self.action_groups = ActionGroupsOperations( + self._client, self._config, self._serialize, self._deserialize, "2018-03-01" + ) + self.metric_alerts = MetricAlertsOperations( + self._client, self._config, self._serialize, self._deserialize, "2018-03-01" + ) self.metric_alerts_status = MetricAlertsStatusOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2018-03-01" ) - 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 @@ -85,12 +109,12 @@ 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) -> None: self._client.close() - def __enter__(self) -> "MonitorManagementClient": + def __enter__(self) -> Self: self._client.__enter__() return self diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/_vendor.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/_vendor.py deleted file mode 100644 index bd0df84f5319..000000000000 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/_vendor.py +++ /dev/null @@ -1,30 +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 typing import List, cast - -from azure.core.pipeline.transport import HttpRequest - - -def _convert_request(request, files=None): - data = request.content if not files else None - request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) - if files: - request.set_formdata_body(files) - return request - - -def _format_url_section(template, **kwargs): - components = template.split("/") - while components: - try: - return template.format(**kwargs) - except KeyError as key: - # Need the cast, as for some reasons "split" is typed as list[str | Any] - formatted_components = cast(List[str], template.split("/")) - components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] - template = "/".join(components) diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/_version.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/_version.py index 394ee7c0c03c..e5754a47ce68 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/_version.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "6.0.2" +VERSION = "1.0.0b1" diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/aio/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/aio/__init__.py index 2c151bb41c19..3df30ff42149 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/aio/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/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 ._monitor_management_client import MonitorManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._monitor_management_client import MonitorManagementClient # type: ignore try: from ._patch import __all__ as _patch_all - from ._patch import * # 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__ = [ "MonitorManagementClient", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/aio/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/aio/_configuration.py index 9b7f0bc7ffb4..35939a5f78ac 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/aio/_configuration.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/aio/_configuration.py @@ -8,18 +8,16 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy from .._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MonitorManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class MonitorManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for MonitorManagementClient. Note that all parameters used to create this instance are saved as instance @@ -35,7 +33,6 @@ class MonitorManagementClientConfiguration(Configuration): # pylint: disable=to """ def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: - super(MonitorManagementClientConfiguration, self).__init__(**kwargs) api_version: str = kwargs.pop("api_version", "2018-03-01") if credential is None: @@ -48,6 +45,7 @@ def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **k self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-monitor/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -56,9 +54,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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/aio/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/aio/_monitor_management_client.py index 73cd9dbc6178..9b2a8817323a 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/aio/_monitor_management_client.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/aio/_monitor_management_client.py @@ -8,9 +8,12 @@ from copy import deepcopy from typing import Any, Awaitable, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient +from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy from .. import models as _models from ..._serialization import Deserializer, Serializer @@ -18,11 +21,10 @@ from .operations import ActionGroupsOperations, MetricAlertsOperations, MetricAlertsStatusOperations if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MonitorManagementClient: # pylint: disable=client-accepts-api-version-keyword +class MonitorManagementClient: """Monitor Management Client. :ivar action_groups: ActionGroupsOperations operations @@ -53,19 +55,43 @@ def __init__( self._config = MonitorManagementClientConfiguration( credential=credential, subscription_id=subscription_id, **kwargs ) - self._client: AsyncARMPipelineClient = AsyncARMPipelineClient(base_url=base_url, config=self._config, **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=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.action_groups = ActionGroupsOperations(self._client, self._config, self._serialize, self._deserialize) - self.metric_alerts = MetricAlertsOperations(self._client, self._config, self._serialize, self._deserialize) + self.action_groups = ActionGroupsOperations( + self._client, self._config, self._serialize, self._deserialize, "2018-03-01" + ) + self.metric_alerts = MetricAlertsOperations( + self._client, self._config, self._serialize, self._deserialize, "2018-03-01" + ) self.metric_alerts_status = MetricAlertsStatusOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2018-03-01" ) - 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 @@ -85,12 +111,12 @@ 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) -> "MonitorManagementClient": + async def __aenter__(self) -> Self: await self._client.__aenter__() return self diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/aio/operations/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/aio/operations/__init__.py index 854cfe54a91d..00349dbee562 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/aio/operations/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/aio/operations/__init__.py @@ -5,13 +5,19 @@ # 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 ._action_groups_operations import ActionGroupsOperations -from ._metric_alerts_operations import MetricAlertsOperations -from ._metric_alerts_status_operations import MetricAlertsStatusOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._action_groups_operations import ActionGroupsOperations # type: ignore +from ._metric_alerts_operations import MetricAlertsOperations # type: ignore +from ._metric_alerts_status_operations import MetricAlertsStatusOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ @@ -19,5 +25,5 @@ "MetricAlertsOperations", "MetricAlertsStatusOperations", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/aio/operations/_action_groups_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/aio/operations/_action_groups_operations.py index 5e6c3dd5956c..1746b7bbcbef 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/aio/operations/_action_groups_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/aio/operations/_action_groups_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload import urllib.parse @@ -19,15 +20,13 @@ 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 ...operations._action_groups_operations import ( build_create_or_update_request, build_delete_request, @@ -38,6 +37,10 @@ build_update_request, ) +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -60,6 +63,7 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @overload async def create_or_update( @@ -83,7 +87,6 @@ async def create_or_update( :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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_03_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -94,7 +97,7 @@ async def create_or_update( self, resource_group_name: str, action_group_name: str, - action_group: IO, + action_group: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -107,11 +110,10 @@ async def create_or_update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group: The action group to create or use for the update. Required. - :type action_group: IO + :type action_group: 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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_03_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -122,7 +124,7 @@ async def create_or_update( self, resource_group_name: str, action_group_name: str, - action_group: Union[_models.ActionGroupResource, IO], + action_group: Union[_models.ActionGroupResource, IO[bytes]], **kwargs: Any ) -> _models.ActionGroupResource: """Create a new action group or update an existing one. @@ -133,17 +135,13 @@ async def create_or_update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group: The action group to create or use for the update. Is either a - ActionGroupResource type or a IO type. Required. - :type action_group: ~azure.mgmt.monitor.v2018_03_01.models.ActionGroupResource 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 + ActionGroupResource type or a IO[bytes] type. Required. + :type action_group: ~azure.mgmt.monitor.v2018_03_01.models.ActionGroupResource or IO[bytes] :return: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_03_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -154,19 +152,19 @@ async def create_or_update( _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", "2018-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2018-03-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ActionGroupResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(action_group, (IO, bytes)): + if isinstance(action_group, (IOBase, bytes)): _content = action_group else: _json = self._serialize.body(action_group, "ActionGroupResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, action_group_name=action_group_name, subscription_id=self._config.subscription_id, @@ -174,16 +172,14 @@ async def create_or_update( 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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -193,21 +189,13 @@ async def create_or_update( 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("ActionGroupResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("ActionGroupResource", pipeline_response) + deserialized = self._deserialize("ActionGroupResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/actionGroups/{actionGroupName}" - } - @distributed_trace_async async def get(self, resource_group_name: str, action_group_name: str, **kwargs: Any) -> _models.ActionGroupResource: """Get an action group. @@ -217,12 +205,11 @@ async def get(self, resource_group_name: str, action_group_name: str, **kwargs: :type resource_group_name: str :param action_group_name: The name of the action group. Required. :type action_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_03_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -233,24 +220,22 @@ async def get(self, resource_group_name: str, action_group_name: str, **kwargs: _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2018-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2018-03-01")) cls: ClsType[_models.ActionGroupResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, action_group_name=action_group_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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -260,21 +245,15 @@ async def get(self, resource_group_name: str, action_group_name: str, **kwargs: error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ActionGroupResource", pipeline_response) + deserialized = self._deserialize("ActionGroupResource", 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.insights/actionGroups/{actionGroupName}" - } + return deserialized # type: ignore @distributed_trace_async - async def delete( # pylint: disable=inconsistent-return-statements - self, resource_group_name: str, action_group_name: str, **kwargs: Any - ) -> None: + async def delete(self, resource_group_name: str, action_group_name: str, **kwargs: Any) -> None: """Delete an action group. :param resource_group_name: The name of the resource group. The name is case insensitive. @@ -282,12 +261,11 @@ async def delete( # pylint: disable=inconsistent-return-statements :type resource_group_name: str :param action_group_name: The name of the action group. Required. :type action_group_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, @@ -298,24 +276,22 @@ async def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2018-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2018-03-01")) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, action_group_name=action_group_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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -326,11 +302,7 @@ async def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/actionGroups/{actionGroupName}" - } + return cls(pipeline_response, None, {}) # type: ignore @overload async def update( @@ -354,7 +326,6 @@ async def update( :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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_03_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -365,7 +336,7 @@ async def update( self, resource_group_name: str, action_group_name: str, - action_group_patch: IO, + action_group_patch: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -378,11 +349,10 @@ async def update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group_patch: Parameters supplied to the operation. Required. - :type action_group_patch: IO + :type action_group_patch: 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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_03_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -393,7 +363,7 @@ async def update( self, resource_group_name: str, action_group_name: str, - action_group_patch: Union[_models.ActionGroupPatchBody, IO], + action_group_patch: Union[_models.ActionGroupPatchBody, IO[bytes]], **kwargs: Any ) -> _models.ActionGroupResource: """Updates an existing action group's tags. To update other fields use the CreateOrUpdate method. @@ -404,17 +374,14 @@ async def update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group_patch: Parameters supplied to the operation. Is either a - ActionGroupPatchBody type or a IO type. Required. - :type action_group_patch: ~azure.mgmt.monitor.v2018_03_01.models.ActionGroupPatchBody 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 + ActionGroupPatchBody type or a IO[bytes] type. Required. + :type action_group_patch: ~azure.mgmt.monitor.v2018_03_01.models.ActionGroupPatchBody or + IO[bytes] :return: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_03_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -425,19 +392,19 @@ async def update( _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", "2018-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2018-03-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ActionGroupResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(action_group_patch, (IO, bytes)): + if isinstance(action_group_patch, (IOBase, bytes)): _content = action_group_patch else: _json = self._serialize.body(action_group_patch, "ActionGroupPatchBody") - request = build_update_request( + _request = build_update_request( resource_group_name=resource_group_name, action_group_name=action_group_name, subscription_id=self._config.subscription_id, @@ -445,16 +412,14 @@ async def update( 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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -464,22 +429,17 @@ async def update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ActionGroupResource", pipeline_response) + deserialized = self._deserialize("ActionGroupResource", 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.insights/actionGroups/{actionGroupName}" - } + return deserialized # type: ignore @distributed_trace def list_by_subscription_id(self, **kwargs: Any) -> AsyncIterable["_models.ActionGroupResource"]: """Get a list of all action groups in a subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ActionGroupResource or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.monitor.v2018_03_01.models.ActionGroupResource] @@ -488,10 +448,10 @@ def list_by_subscription_id(self, **kwargs: Any) -> AsyncIterable["_models.Actio _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2018-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2018-03-01")) cls: ClsType[_models.ActionGroupList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -502,15 +462,13 @@ def list_by_subscription_id(self, **kwargs: Any) -> AsyncIterable["_models.Actio def prepare_request(next_link=None): if not next_link: - request = build_list_by_subscription_id_request( + _request = build_list_by_subscription_id_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_subscription_id.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -521,14 +479,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("ActionGroupList", pipeline_response) @@ -538,11 +495,11 @@ async def extract_data(pipeline_response): return None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -555,10 +512,6 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_by_subscription_id.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/microsoft.insights/actionGroups" - } - @distributed_trace def list_by_resource_group( self, resource_group_name: str, **kwargs: Any @@ -568,7 +521,6 @@ def list_by_resource_group( :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ActionGroupResource or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.monitor.v2018_03_01.models.ActionGroupResource] @@ -577,10 +529,10 @@ def list_by_resource_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2018-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2018-03-01")) cls: ClsType[_models.ActionGroupList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -591,16 +543,14 @@ 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_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -611,14 +561,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("ActionGroupList", pipeline_response) @@ -628,11 +577,11 @@ async def extract_data(pipeline_response): return None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -645,12 +594,8 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/actionGroups" - } - @overload - async def enable_receiver( # pylint: disable=inconsistent-return-statements + async def enable_receiver( self, resource_group_name: str, action_group_name: str, @@ -672,18 +617,17 @@ async def enable_receiver( # pylint: disable=inconsistent-return-statements :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: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def enable_receiver( # pylint: disable=inconsistent-return-statements + async def enable_receiver( self, resource_group_name: str, action_group_name: str, - enable_request: IO, + enable_request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -697,22 +641,21 @@ async def enable_receiver( # pylint: disable=inconsistent-return-statements :param action_group_name: The name of the action group. Required. :type action_group_name: str :param enable_request: The receiver to re-enable. Required. - :type enable_request: IO + :type enable_request: 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: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async - async def enable_receiver( # pylint: disable=inconsistent-return-statements + async def enable_receiver( self, resource_group_name: str, action_group_name: str, - enable_request: Union[_models.EnableRequest, IO], + enable_request: Union[_models.EnableRequest, IO[bytes]], **kwargs: Any ) -> None: """Enable a receiver in an action group. This changes the receiver's status from Disabled to @@ -723,18 +666,14 @@ async def enable_receiver( # pylint: disable=inconsistent-return-statements :type resource_group_name: str :param action_group_name: The name of the action group. Required. :type action_group_name: str - :param enable_request: The receiver to re-enable. Is either a EnableRequest type or a IO type. - Required. - :type enable_request: ~azure.mgmt.monitor.v2018_03_01.models.EnableRequest 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 + :param enable_request: The receiver to re-enable. Is either a EnableRequest type or a IO[bytes] + type. Required. + :type enable_request: ~azure.mgmt.monitor.v2018_03_01.models.EnableRequest or IO[bytes] :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, @@ -745,19 +684,19 @@ async def enable_receiver( # pylint: disable=inconsistent-return-statements _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", "2018-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2018-03-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[None] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(enable_request, (IO, bytes)): + if isinstance(enable_request, (IOBase, bytes)): _content = enable_request else: _json = self._serialize.body(enable_request, "EnableRequest") - request = build_enable_receiver_request( + _request = build_enable_receiver_request( resource_group_name=resource_group_name, action_group_name=action_group_name, subscription_id=self._config.subscription_id, @@ -765,16 +704,14 @@ async def enable_receiver( # pylint: disable=inconsistent-return-statements content_type=content_type, json=_json, content=_content, - template_url=self.enable_receiver.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -785,8 +722,4 @@ async def enable_receiver( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - enable_receiver.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/actionGroups/{actionGroupName}/subscribe" - } + return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/aio/operations/_metric_alerts_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/aio/operations/_metric_alerts_operations.py index 3a7754a8b6fa..7d5ea7666e3e 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/aio/operations/_metric_alerts_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/aio/operations/_metric_alerts_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload import urllib.parse @@ -19,15 +20,13 @@ 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 ...operations._metric_alerts_operations import ( build_create_or_update_request, build_delete_request, @@ -37,6 +36,10 @@ build_update_request, ) +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -59,12 +62,12 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.MetricAlertResource"]: """Retrieve alert rule definitions in a subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either MetricAlertResource or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.monitor.v2018_03_01.models.MetricAlertResource] @@ -73,10 +76,10 @@ def list_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.MetricAl _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2018-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2018-03-01")) cls: ClsType[_models.MetricAlertResourceCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -87,15 +90,13 @@ def list_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.MetricAl def prepare_request(next_link=None): if not next_link: - request = build_list_by_subscription_request( + _request = build_list_by_subscription_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_subscription.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -106,14 +107,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("MetricAlertResourceCollection", pipeline_response) @@ -123,11 +123,11 @@ async def extract_data(pipeline_response): return None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -140,8 +140,6 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_by_subscription.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/metricAlerts"} - @distributed_trace def list_by_resource_group( self, resource_group_name: str, **kwargs: Any @@ -151,7 +149,6 @@ def list_by_resource_group( :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either MetricAlertResource or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.monitor.v2018_03_01.models.MetricAlertResource] @@ -160,10 +157,10 @@ def list_by_resource_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2018-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2018-03-01")) cls: ClsType[_models.MetricAlertResourceCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -174,16 +171,14 @@ 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_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -194,14 +189,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("MetricAlertResourceCollection", pipeline_response) @@ -211,11 +205,11 @@ async def extract_data(pipeline_response): return None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -228,10 +222,6 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/metricAlerts" - } - @distributed_trace_async async def get(self, resource_group_name: str, rule_name: str, **kwargs: Any) -> _models.MetricAlertResource: """Retrieve an alert rule definition. @@ -241,12 +231,11 @@ async def get(self, resource_group_name: str, rule_name: str, **kwargs: Any) -> :type resource_group_name: str :param rule_name: The name of the rule. Required. :type rule_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: MetricAlertResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_03_01.models.MetricAlertResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -257,24 +246,22 @@ async def get(self, resource_group_name: str, rule_name: str, **kwargs: Any) -> _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2018-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2018-03-01")) cls: ClsType[_models.MetricAlertResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, rule_name=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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -284,16 +271,12 @@ async def get(self, resource_group_name: str, rule_name: str, **kwargs: Any) -> error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("MetricAlertResource", pipeline_response) + deserialized = self._deserialize("MetricAlertResource", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - get.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/metricAlerts/{ruleName}" - } + return deserialized # type: ignore @overload async def create_or_update( @@ -317,7 +300,6 @@ async def create_or_update( :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: MetricAlertResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_03_01.models.MetricAlertResource :raises ~azure.core.exceptions.HttpResponseError: @@ -328,7 +310,7 @@ async def create_or_update( self, resource_group_name: str, rule_name: str, - parameters: IO, + parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -341,11 +323,10 @@ async def create_or_update( :param rule_name: The name of the rule. Required. :type rule_name: str :param parameters: The parameters of the rule to create or update. Required. - :type parameters: IO + :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: MetricAlertResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_03_01.models.MetricAlertResource :raises ~azure.core.exceptions.HttpResponseError: @@ -356,7 +337,7 @@ async def create_or_update( self, resource_group_name: str, rule_name: str, - parameters: Union[_models.MetricAlertResource, IO], + parameters: Union[_models.MetricAlertResource, IO[bytes]], **kwargs: Any ) -> _models.MetricAlertResource: """Create or update an metric alert definition. @@ -367,17 +348,13 @@ async def create_or_update( :param rule_name: The name of the rule. Required. :type rule_name: str :param parameters: The parameters of the rule to create or update. Is either a - MetricAlertResource type or a IO type. Required. - :type parameters: ~azure.mgmt.monitor.v2018_03_01.models.MetricAlertResource 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 + MetricAlertResource type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.monitor.v2018_03_01.models.MetricAlertResource or IO[bytes] :return: MetricAlertResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_03_01.models.MetricAlertResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -388,19 +365,19 @@ async def create_or_update( _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", "2018-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2018-03-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.MetricAlertResource] = 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, "MetricAlertResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, rule_name=rule_name, subscription_id=self._config.subscription_id, @@ -408,16 +385,14 @@ async def create_or_update( 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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -427,16 +402,12 @@ async def create_or_update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("MetricAlertResource", pipeline_response) + deserialized = self._deserialize("MetricAlertResource", 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.Insights/metricAlerts/{ruleName}" - } + return deserialized # type: ignore @overload async def update( @@ -460,7 +431,6 @@ async def update( :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: MetricAlertResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_03_01.models.MetricAlertResource :raises ~azure.core.exceptions.HttpResponseError: @@ -471,7 +441,7 @@ async def update( self, resource_group_name: str, rule_name: str, - parameters: IO, + parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -484,11 +454,10 @@ async def update( :param rule_name: The name of the rule. Required. :type rule_name: str :param parameters: The parameters of the rule to update. Required. - :type parameters: IO + :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: MetricAlertResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_03_01.models.MetricAlertResource :raises ~azure.core.exceptions.HttpResponseError: @@ -499,7 +468,7 @@ async def update( self, resource_group_name: str, rule_name: str, - parameters: Union[_models.MetricAlertResourcePatch, IO], + parameters: Union[_models.MetricAlertResourcePatch, IO[bytes]], **kwargs: Any ) -> _models.MetricAlertResource: """Update an metric alert definition. @@ -510,17 +479,13 @@ async def update( :param rule_name: The name of the rule. Required. :type rule_name: str :param parameters: The parameters of the rule to update. Is either a MetricAlertResourcePatch - type or a IO type. Required. - :type parameters: ~azure.mgmt.monitor.v2018_03_01.models.MetricAlertResourcePatch 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 + type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.monitor.v2018_03_01.models.MetricAlertResourcePatch or IO[bytes] :return: MetricAlertResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_03_01.models.MetricAlertResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -531,19 +496,19 @@ async def update( _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", "2018-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2018-03-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.MetricAlertResource] = 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, "MetricAlertResourcePatch") - request = build_update_request( + _request = build_update_request( resource_group_name=resource_group_name, rule_name=rule_name, subscription_id=self._config.subscription_id, @@ -551,16 +516,14 @@ async def update( 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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -570,21 +533,15 @@ async def update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("MetricAlertResource", pipeline_response) + deserialized = self._deserialize("MetricAlertResource", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/metricAlerts/{ruleName}" - } + return deserialized # type: ignore @distributed_trace_async - async def delete( # pylint: disable=inconsistent-return-statements - self, resource_group_name: str, rule_name: str, **kwargs: Any - ) -> None: + async def delete(self, resource_group_name: str, rule_name: str, **kwargs: Any) -> None: """Delete an alert rule definition. :param resource_group_name: The name of the resource group. The name is case insensitive. @@ -592,12 +549,11 @@ async def delete( # pylint: disable=inconsistent-return-statements :type resource_group_name: str :param rule_name: The name of the rule. Required. :type 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, @@ -608,24 +564,22 @@ async def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2018-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2018-03-01")) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, rule_name=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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -636,8 +590,4 @@ async def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/metricAlerts/{ruleName}" - } + return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/aio/operations/_metric_alerts_status_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/aio/operations/_metric_alerts_status_operations.py index 356ee548b29c..c9609b28cea4 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/aio/operations/_metric_alerts_status_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/aio/operations/_metric_alerts_status_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,7 @@ # 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 ( @@ -17,16 +17,18 @@ 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_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._metric_alerts_status_operations import build_list_by_name_request, build_list_request +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -49,6 +51,7 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace_async async def list( @@ -61,12 +64,11 @@ async def list( :type resource_group_name: str :param rule_name: The name of the rule. Required. :type rule_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: MetricAlertStatusCollection or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_03_01.models.MetricAlertStatusCollection :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -77,24 +79,22 @@ async def list( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2018-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2018-03-01")) cls: ClsType[_models.MetricAlertStatusCollection] = kwargs.pop("cls", None) - request = build_list_request( + _request = build_list_request( resource_group_name=resource_group_name, rule_name=rule_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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -104,16 +104,12 @@ async def list( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("MetricAlertStatusCollection", pipeline_response) + deserialized = self._deserialize("MetricAlertStatusCollection", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - list.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/metricAlerts/{ruleName}/status" - } + return deserialized # type: ignore @distributed_trace_async async def list_by_name( @@ -128,12 +124,11 @@ async def list_by_name( :type rule_name: str :param status_name: The name of the status. Required. :type status_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: MetricAlertStatusCollection or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_03_01.models.MetricAlertStatusCollection :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -144,25 +139,23 @@ async def list_by_name( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2018-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2018-03-01")) cls: ClsType[_models.MetricAlertStatusCollection] = kwargs.pop("cls", None) - request = build_list_by_name_request( + _request = build_list_by_name_request( resource_group_name=resource_group_name, rule_name=rule_name, status_name=status_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_name.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -172,13 +165,9 @@ async def list_by_name( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("MetricAlertStatusCollection", pipeline_response) + deserialized = self._deserialize("MetricAlertStatusCollection", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - list_by_name.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/metricAlerts/{ruleName}/status/{statusName}" - } + return deserialized # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/models/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/models/__init__.py index 8dd7a2ac99a2..c9384636e88c 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/models/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/models/__init__.py @@ -5,48 +5,59 @@ # 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 ActionGroupList -from ._models_py3 import ActionGroupPatchBody -from ._models_py3 import ActionGroupResource -from ._models_py3 import AutomationRunbookReceiver -from ._models_py3 import AzureAppPushReceiver -from ._models_py3 import AzureFunctionReceiver -from ._models_py3 import DynamicMetricCriteria -from ._models_py3 import DynamicThresholdFailingPeriods -from ._models_py3 import EmailReceiver -from ._models_py3 import EnableRequest -from ._models_py3 import ErrorResponse -from ._models_py3 import ItsmReceiver -from ._models_py3 import LogicAppReceiver -from ._models_py3 import MetricAlertAction -from ._models_py3 import MetricAlertCriteria -from ._models_py3 import MetricAlertMultipleResourceMultipleMetricCriteria -from ._models_py3 import MetricAlertResource -from ._models_py3 import MetricAlertResourceCollection -from ._models_py3 import MetricAlertResourcePatch -from ._models_py3 import MetricAlertSingleResourceMultipleMetricCriteria -from ._models_py3 import MetricAlertStatus -from ._models_py3 import MetricAlertStatusCollection -from ._models_py3 import MetricAlertStatusProperties -from ._models_py3 import MetricCriteria -from ._models_py3 import MetricDimension -from ._models_py3 import MultiMetricCriteria -from ._models_py3 import Resource -from ._models_py3 import SmsReceiver -from ._models_py3 import VoiceReceiver -from ._models_py3 import WebhookReceiver -from ._models_py3 import WebtestLocationAvailabilityCriteria +from typing import TYPE_CHECKING -from ._monitor_management_client_enums import AggregationTypeEnum -from ._monitor_management_client_enums import CriterionType -from ._monitor_management_client_enums import DynamicThresholdOperator -from ._monitor_management_client_enums import DynamicThresholdSensitivity -from ._monitor_management_client_enums import Odatatype -from ._monitor_management_client_enums import Operator -from ._monitor_management_client_enums import ReceiverStatus +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models_py3 import ( # type: ignore + ActionGroupList, + ActionGroupPatchBody, + ActionGroupResource, + AutomationRunbookReceiver, + AzureAppPushReceiver, + AzureFunctionReceiver, + DynamicMetricCriteria, + DynamicThresholdFailingPeriods, + EmailReceiver, + EnableRequest, + ErrorResponse, + ItsmReceiver, + LogicAppReceiver, + MetricAlertAction, + MetricAlertCriteria, + MetricAlertMultipleResourceMultipleMetricCriteria, + MetricAlertResource, + MetricAlertResourceCollection, + MetricAlertResourcePatch, + MetricAlertSingleResourceMultipleMetricCriteria, + MetricAlertStatus, + MetricAlertStatusCollection, + MetricAlertStatusProperties, + MetricCriteria, + MetricDimension, + MultiMetricCriteria, + Resource, + SmsReceiver, + VoiceReceiver, + WebhookReceiver, + WebtestLocationAvailabilityCriteria, +) + +from ._monitor_management_client_enums import ( # type: ignore + AggregationTypeEnum, + CriterionType, + DynamicThresholdOperator, + DynamicThresholdSensitivity, + Odatatype, + Operator, + ReceiverStatus, +) from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ @@ -89,5 +100,5 @@ "Operator", "ReceiverStatus", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/models/_models_py3.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/models/_models_py3.py index d842e635ffdd..5910120fa788 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/models/_models_py3.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/models/_models_py3.py @@ -1,5 +1,5 @@ -# coding=utf-8 # 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. @@ -16,10 +16,9 @@ if sys.version_info >= (3, 9): from collections.abc import MutableMapping else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports + from typing import MutableMapping # type: ignore if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from .. import models as _models JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object @@ -89,7 +88,7 @@ class Resource(_serialization.Model): 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: Azure resource Id. :vartype id: str @@ -133,12 +132,12 @@ def __init__(self, *, location: str, tags: Optional[Dict[str, str]] = None, **kw self.tags = tags -class ActionGroupResource(Resource): # pylint: disable=too-many-instance-attributes +class ActionGroupResource(Resource): """An action group 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: Azure resource Id. :vartype id: str @@ -283,7 +282,7 @@ def __init__( class AutomationRunbookReceiver(_serialization.Model): """The Azure Automation Runbook notification receiver. - 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 automation_account_id: The Azure automation account Id which holds this runbook and authenticate to Azure resource. Required. @@ -354,7 +353,7 @@ def __init__( class AzureAppPushReceiver(_serialization.Model): """The Azure mobile App push notification receiver. - 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 name of the Azure mobile app push receiver. Names must be unique across all receivers within an action group. Required. @@ -389,7 +388,7 @@ def __init__(self, *, name: str, email_address: str, **kwargs: Any) -> None: class AzureFunctionReceiver(_serialization.Model): """An azure function receiver. - 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 name of the azure function receiver. Names must be unique across all receivers within an action group. Required. @@ -443,7 +442,7 @@ class MultiMetricCriteria(_serialization.Model): You probably want to use the sub-classes and not this class directly. Known sub-classes are: DynamicMetricCriteria, MetricCriteria - 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 additional_properties: Unmatched properties from the message are deserialized to this collection. @@ -534,10 +533,10 @@ def __init__( self.skip_metric_validation = skip_metric_validation -class DynamicMetricCriteria(MultiMetricCriteria): # pylint: disable=too-many-instance-attributes +class DynamicMetricCriteria(MultiMetricCriteria): """Criterion for dynamic threshold. - 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 additional_properties: Unmatched properties from the message are deserialized to this collection. @@ -671,7 +670,7 @@ class DynamicThresholdFailingPeriods(_serialization.Model): """The minimum number of violations required within the selected lookback time window required to raise an alert. - 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 number_of_evaluation_periods: The number of aggregated lookback points. The lookback time window is calculated based on the aggregation granularity (windowSize) and the selected number @@ -714,7 +713,7 @@ class EmailReceiver(_serialization.Model): 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 name: The name of the email receiver. Names must be unique across all receivers within an action group. Required. @@ -755,7 +754,7 @@ def __init__(self, *, name: str, email_address: str, **kwargs: Any) -> None: class EnableRequest(_serialization.Model): """Describes a receiver that should be resubscribed. - 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 receiver_name: The name of the receiver to resubscribe. Required. :vartype receiver_name: str @@ -807,7 +806,7 @@ def __init__(self, *, code: Optional[str] = None, message: Optional[str] = None, class ItsmReceiver(_serialization.Model): """An Itsm receiver. - 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 name of the Itsm receiver. Names must be unique across all receivers within an action group. Required. @@ -821,7 +820,7 @@ class ItsmReceiver(_serialization.Model): CreateMultipleWorkItems option will be part of this blob as well. Required. :vartype ticket_configuration: str :ivar region: Region in which workspace resides. Supported - values:'centralindia','japaneast','southeastasia','australiasoutheast','uksouth','westcentralus','canadacentral','eastus','westeurope'. + values:'centralindia','japaneast','southeastasia','australiasoutheast','uksouth','westcentralus','canadacentral','eastus','westeurope'. # pylint: disable=line-too-long Required. :vartype region: str """ @@ -858,7 +857,7 @@ def __init__( CreateMultipleWorkItems option will be part of this blob as well. Required. :paramtype ticket_configuration: str :keyword region: Region in which workspace resides. Supported - values:'centralindia','japaneast','southeastasia','australiasoutheast','uksouth','westcentralus','canadacentral','eastus','westeurope'. + values:'centralindia','japaneast','southeastasia','australiasoutheast','uksouth','westcentralus','canadacentral','eastus','westeurope'. # pylint: disable=line-too-long Required. :paramtype region: str """ @@ -873,7 +872,7 @@ def __init__( class LogicAppReceiver(_serialization.Model): """A logic app receiver. - 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 name of the logic app receiver. Names must be unique across all receivers within an action group. Required. @@ -953,7 +952,7 @@ class MetricAlertCriteria(_serialization.Model): MetricAlertMultipleResourceMultipleMetricCriteria, MetricAlertSingleResourceMultipleMetricCriteria, WebtestLocationAvailabilityCriteria - 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 additional_properties: Unmatched properties from the message are deserialized to this collection. @@ -993,10 +992,10 @@ def __init__(self, *, additional_properties: Optional[Dict[str, JSON]] = None, * self.odata_type: Optional[str] = None -class MetricAlertMultipleResourceMultipleMetricCriteria(MetricAlertCriteria): +class MetricAlertMultipleResourceMultipleMetricCriteria(MetricAlertCriteria): # pylint: disable=name-too-long """Specifies the metric alert criteria for multiple resource that has multiple metric criteria. - 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 additional_properties: Unmatched properties from the message are deserialized to this collection. @@ -1039,12 +1038,12 @@ def __init__( self.all_of = all_of -class MetricAlertResource(Resource): # pylint: disable=too-many-instance-attributes +class MetricAlertResource(Resource): """The metric alert 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: Azure resource Id. :vartype id: str @@ -1220,7 +1219,7 @@ def __init__(self, *, value: Optional[List["_models.MetricAlertResource"]] = Non self.value = value -class MetricAlertResourcePatch(_serialization.Model): # pylint: disable=too-many-instance-attributes +class MetricAlertResourcePatch(_serialization.Model): """The metric alert resource for patch operations. Variables are only populated by the server, and will be ignored when sending a request. @@ -1351,10 +1350,10 @@ def __init__( self.is_migrated = None -class MetricAlertSingleResourceMultipleMetricCriteria(MetricAlertCriteria): +class MetricAlertSingleResourceMultipleMetricCriteria(MetricAlertCriteria): # pylint: disable=name-too-long """Specifies the metric alert criteria for a single resource that has multiple metric criteria. - 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 additional_properties: Unmatched properties from the message are deserialized to this collection. @@ -1505,7 +1504,7 @@ def __init__( class MetricCriteria(MultiMetricCriteria): """Criterion to filter metrics. - 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 additional_properties: Unmatched properties from the message are deserialized to this collection. @@ -1612,7 +1611,7 @@ def __init__( class MetricDimension(_serialization.Model): """Specifies a metric dimension. - 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: Name of the dimension. Required. :vartype name: str @@ -1655,7 +1654,7 @@ class SmsReceiver(_serialization.Model): 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 name: The name of the SMS receiver. Names must be unique across all receivers within an action group. Required. @@ -1703,7 +1702,7 @@ def __init__(self, *, name: str, country_code: str, phone_number: str, **kwargs: class VoiceReceiver(_serialization.Model): """A voice receiver. - 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 name of the voice receiver. Names must be unique across all receivers within an action group. Required. @@ -1745,7 +1744,7 @@ def __init__(self, *, name: str, country_code: str, phone_number: str, **kwargs: class WebhookReceiver(_serialization.Model): """A webhook receiver. - 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 name of the webhook receiver. Names must be unique across all receivers within an action group. Required. @@ -1780,7 +1779,7 @@ def __init__(self, *, name: str, service_uri: str, **kwargs: Any) -> None: class WebtestLocationAvailabilityCriteria(MetricAlertCriteria): """Specifies the metric alert rule criteria for a web test resource. - 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 additional_properties: Unmatched properties from the message are deserialized to this collection. diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/operations/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/operations/__init__.py index 854cfe54a91d..00349dbee562 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/operations/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/operations/__init__.py @@ -5,13 +5,19 @@ # 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 ._action_groups_operations import ActionGroupsOperations -from ._metric_alerts_operations import MetricAlertsOperations -from ._metric_alerts_status_operations import MetricAlertsStatusOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._action_groups_operations import ActionGroupsOperations # type: ignore +from ._metric_alerts_operations import MetricAlertsOperations # type: ignore +from ._metric_alerts_status_operations import MetricAlertsStatusOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ @@ -19,5 +25,5 @@ "MetricAlertsOperations", "MetricAlertsStatusOperations", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/operations/_action_groups_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/operations/_action_groups_operations.py index 8940343c2b86..1bb8009d5f76 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/operations/_action_groups_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/operations/_action_groups_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload import urllib.parse @@ -19,16 +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, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -59,7 +62,7 @@ def build_create_or_update_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -94,7 +97,7 @@ def build_get_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -127,7 +130,7 @@ def build_delete_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -161,7 +164,7 @@ def build_update_request( "actionGroupName": _SERIALIZER.url("action_group_name", action_group_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -187,7 +190,7 @@ def build_list_by_subscription_id_request(subscription_id: str, **kwargs: Any) - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -217,7 +220,7 @@ def build_list_by_resource_group_request(resource_group_name: str, subscription_ "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -251,7 +254,7 @@ def build_enable_receiver_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -282,6 +285,7 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @overload def create_or_update( @@ -305,7 +309,6 @@ def create_or_update( :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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_03_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -316,7 +319,7 @@ def create_or_update( self, resource_group_name: str, action_group_name: str, - action_group: IO, + action_group: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -329,11 +332,10 @@ def create_or_update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group: The action group to create or use for the update. Required. - :type action_group: IO + :type action_group: 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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_03_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -344,7 +346,7 @@ def create_or_update( self, resource_group_name: str, action_group_name: str, - action_group: Union[_models.ActionGroupResource, IO], + action_group: Union[_models.ActionGroupResource, IO[bytes]], **kwargs: Any ) -> _models.ActionGroupResource: """Create a new action group or update an existing one. @@ -355,17 +357,13 @@ def create_or_update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group: The action group to create or use for the update. Is either a - ActionGroupResource type or a IO type. Required. - :type action_group: ~azure.mgmt.monitor.v2018_03_01.models.ActionGroupResource 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 + ActionGroupResource type or a IO[bytes] type. Required. + :type action_group: ~azure.mgmt.monitor.v2018_03_01.models.ActionGroupResource or IO[bytes] :return: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_03_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -376,19 +374,19 @@ def create_or_update( _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", "2018-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2018-03-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ActionGroupResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(action_group, (IO, bytes)): + if isinstance(action_group, (IOBase, bytes)): _content = action_group else: _json = self._serialize.body(action_group, "ActionGroupResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, action_group_name=action_group_name, subscription_id=self._config.subscription_id, @@ -396,16 +394,14 @@ def create_or_update( 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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -415,21 +411,13 @@ def create_or_update( 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("ActionGroupResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("ActionGroupResource", pipeline_response) + deserialized = self._deserialize("ActionGroupResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/actionGroups/{actionGroupName}" - } - @distributed_trace def get(self, resource_group_name: str, action_group_name: str, **kwargs: Any) -> _models.ActionGroupResource: """Get an action group. @@ -439,12 +427,11 @@ def get(self, resource_group_name: str, action_group_name: str, **kwargs: Any) - :type resource_group_name: str :param action_group_name: The name of the action group. Required. :type action_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_03_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -455,24 +442,22 @@ def get(self, resource_group_name: str, action_group_name: str, **kwargs: Any) - _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2018-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2018-03-01")) cls: ClsType[_models.ActionGroupResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, action_group_name=action_group_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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -482,16 +467,12 @@ def get(self, resource_group_name: str, action_group_name: str, **kwargs: Any) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ActionGroupResource", pipeline_response) + deserialized = self._deserialize("ActionGroupResource", 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.insights/actionGroups/{actionGroupName}" - } + return deserialized # type: ignore @distributed_trace def delete( # pylint: disable=inconsistent-return-statements @@ -504,12 +485,11 @@ def delete( # pylint: disable=inconsistent-return-statements :type resource_group_name: str :param action_group_name: The name of the action group. Required. :type action_group_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, @@ -520,24 +500,22 @@ def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2018-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2018-03-01")) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, action_group_name=action_group_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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -548,11 +526,7 @@ def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/actionGroups/{actionGroupName}" - } + return cls(pipeline_response, None, {}) # type: ignore @overload def update( @@ -576,7 +550,6 @@ def update( :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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_03_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -587,7 +560,7 @@ def update( self, resource_group_name: str, action_group_name: str, - action_group_patch: IO, + action_group_patch: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -600,11 +573,10 @@ def update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group_patch: Parameters supplied to the operation. Required. - :type action_group_patch: IO + :type action_group_patch: 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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_03_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -615,7 +587,7 @@ def update( self, resource_group_name: str, action_group_name: str, - action_group_patch: Union[_models.ActionGroupPatchBody, IO], + action_group_patch: Union[_models.ActionGroupPatchBody, IO[bytes]], **kwargs: Any ) -> _models.ActionGroupResource: """Updates an existing action group's tags. To update other fields use the CreateOrUpdate method. @@ -626,17 +598,14 @@ def update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group_patch: Parameters supplied to the operation. Is either a - ActionGroupPatchBody type or a IO type. Required. - :type action_group_patch: ~azure.mgmt.monitor.v2018_03_01.models.ActionGroupPatchBody 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 + ActionGroupPatchBody type or a IO[bytes] type. Required. + :type action_group_patch: ~azure.mgmt.monitor.v2018_03_01.models.ActionGroupPatchBody or + IO[bytes] :return: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_03_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -647,19 +616,19 @@ def update( _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", "2018-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2018-03-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ActionGroupResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(action_group_patch, (IO, bytes)): + if isinstance(action_group_patch, (IOBase, bytes)): _content = action_group_patch else: _json = self._serialize.body(action_group_patch, "ActionGroupPatchBody") - request = build_update_request( + _request = build_update_request( resource_group_name=resource_group_name, action_group_name=action_group_name, subscription_id=self._config.subscription_id, @@ -667,16 +636,14 @@ def update( 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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -686,22 +653,17 @@ def update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ActionGroupResource", pipeline_response) + deserialized = self._deserialize("ActionGroupResource", 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.insights/actionGroups/{actionGroupName}" - } + return deserialized # type: ignore @distributed_trace def list_by_subscription_id(self, **kwargs: Any) -> Iterable["_models.ActionGroupResource"]: """Get a list of all action groups in a subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ActionGroupResource or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.monitor.v2018_03_01.models.ActionGroupResource] @@ -710,10 +672,10 @@ def list_by_subscription_id(self, **kwargs: Any) -> Iterable["_models.ActionGrou _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2018-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2018-03-01")) cls: ClsType[_models.ActionGroupList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -724,15 +686,13 @@ def list_by_subscription_id(self, **kwargs: Any) -> Iterable["_models.ActionGrou def prepare_request(next_link=None): if not next_link: - request = build_list_by_subscription_id_request( + _request = build_list_by_subscription_id_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_subscription_id.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -743,14 +703,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("ActionGroupList", pipeline_response) @@ -760,11 +719,11 @@ def extract_data(pipeline_response): return None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -777,10 +736,6 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_by_subscription_id.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/microsoft.insights/actionGroups" - } - @distributed_trace def list_by_resource_group( self, resource_group_name: str, **kwargs: Any @@ -790,7 +745,6 @@ def list_by_resource_group( :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ActionGroupResource or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.monitor.v2018_03_01.models.ActionGroupResource] @@ -799,10 +753,10 @@ def list_by_resource_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2018-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2018-03-01")) cls: ClsType[_models.ActionGroupList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -813,16 +767,14 @@ 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_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -833,14 +785,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("ActionGroupList", pipeline_response) @@ -850,11 +801,11 @@ def extract_data(pipeline_response): return None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -867,12 +818,8 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/actionGroups" - } - @overload - def enable_receiver( # pylint: disable=inconsistent-return-statements + def enable_receiver( self, resource_group_name: str, action_group_name: str, @@ -894,18 +841,17 @@ def enable_receiver( # pylint: disable=inconsistent-return-statements :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: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def enable_receiver( # pylint: disable=inconsistent-return-statements + def enable_receiver( self, resource_group_name: str, action_group_name: str, - enable_request: IO, + enable_request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -919,11 +865,10 @@ def enable_receiver( # pylint: disable=inconsistent-return-statements :param action_group_name: The name of the action group. Required. :type action_group_name: str :param enable_request: The receiver to re-enable. Required. - :type enable_request: IO + :type enable_request: 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: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -934,7 +879,7 @@ def enable_receiver( # pylint: disable=inconsistent-return-statements self, resource_group_name: str, action_group_name: str, - enable_request: Union[_models.EnableRequest, IO], + enable_request: Union[_models.EnableRequest, IO[bytes]], **kwargs: Any ) -> None: """Enable a receiver in an action group. This changes the receiver's status from Disabled to @@ -945,18 +890,14 @@ def enable_receiver( # pylint: disable=inconsistent-return-statements :type resource_group_name: str :param action_group_name: The name of the action group. Required. :type action_group_name: str - :param enable_request: The receiver to re-enable. Is either a EnableRequest type or a IO type. - Required. - :type enable_request: ~azure.mgmt.monitor.v2018_03_01.models.EnableRequest 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 + :param enable_request: The receiver to re-enable. Is either a EnableRequest type or a IO[bytes] + type. Required. + :type enable_request: ~azure.mgmt.monitor.v2018_03_01.models.EnableRequest or IO[bytes] :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, @@ -967,19 +908,19 @@ def enable_receiver( # pylint: disable=inconsistent-return-statements _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", "2018-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2018-03-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[None] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(enable_request, (IO, bytes)): + if isinstance(enable_request, (IOBase, bytes)): _content = enable_request else: _json = self._serialize.body(enable_request, "EnableRequest") - request = build_enable_receiver_request( + _request = build_enable_receiver_request( resource_group_name=resource_group_name, action_group_name=action_group_name, subscription_id=self._config.subscription_id, @@ -987,16 +928,14 @@ def enable_receiver( # pylint: disable=inconsistent-return-statements content_type=content_type, json=_json, content=_content, - template_url=self.enable_receiver.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1007,8 +946,4 @@ def enable_receiver( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - enable_receiver.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/actionGroups/{actionGroupName}/subscribe" - } + return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/operations/_metric_alerts_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/operations/_metric_alerts_operations.py index 9e32945a64e1..797f2cc8e6c6 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/operations/_metric_alerts_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/operations/_metric_alerts_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload import urllib.parse @@ -19,16 +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, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -49,7 +52,7 @@ def build_list_by_subscription_request(subscription_id: str, **kwargs: Any) -> H "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -79,7 +82,7 @@ def build_list_by_resource_group_request(resource_group_name: str, subscription_ ), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -110,7 +113,7 @@ def build_get_request(resource_group_name: str, rule_name: str, subscription_id: "ruleName": _SERIALIZER.url("rule_name", rule_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -144,7 +147,7 @@ def build_create_or_update_request( "ruleName": _SERIALIZER.url("rule_name", rule_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -178,7 +181,7 @@ def build_update_request(resource_group_name: str, rule_name: str, subscription_ "ruleName": _SERIALIZER.url("rule_name", rule_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -211,7 +214,7 @@ def build_delete_request(resource_group_name: str, rule_name: str, subscription_ "ruleName": _SERIALIZER.url("rule_name", rule_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -240,12 +243,12 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list_by_subscription(self, **kwargs: Any) -> Iterable["_models.MetricAlertResource"]: """Retrieve alert rule definitions in a subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either MetricAlertResource or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.monitor.v2018_03_01.models.MetricAlertResource] @@ -254,10 +257,10 @@ def list_by_subscription(self, **kwargs: Any) -> Iterable["_models.MetricAlertRe _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2018-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2018-03-01")) cls: ClsType[_models.MetricAlertResourceCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -268,15 +271,13 @@ def list_by_subscription(self, **kwargs: Any) -> Iterable["_models.MetricAlertRe def prepare_request(next_link=None): if not next_link: - request = build_list_by_subscription_request( + _request = build_list_by_subscription_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_subscription.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -287,14 +288,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("MetricAlertResourceCollection", pipeline_response) @@ -304,11 +304,11 @@ def extract_data(pipeline_response): return None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -321,8 +321,6 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_by_subscription.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/metricAlerts"} - @distributed_trace def list_by_resource_group( self, resource_group_name: str, **kwargs: Any @@ -332,7 +330,6 @@ def list_by_resource_group( :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either MetricAlertResource or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.monitor.v2018_03_01.models.MetricAlertResource] @@ -341,10 +338,10 @@ def list_by_resource_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2018-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2018-03-01")) cls: ClsType[_models.MetricAlertResourceCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -355,16 +352,14 @@ 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_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -375,14 +370,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("MetricAlertResourceCollection", pipeline_response) @@ -392,11 +386,11 @@ def extract_data(pipeline_response): return None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -409,10 +403,6 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/metricAlerts" - } - @distributed_trace def get(self, resource_group_name: str, rule_name: str, **kwargs: Any) -> _models.MetricAlertResource: """Retrieve an alert rule definition. @@ -422,12 +412,11 @@ def get(self, resource_group_name: str, rule_name: str, **kwargs: Any) -> _model :type resource_group_name: str :param rule_name: The name of the rule. Required. :type rule_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: MetricAlertResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_03_01.models.MetricAlertResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -438,24 +427,22 @@ def get(self, resource_group_name: str, rule_name: str, **kwargs: Any) -> _model _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2018-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2018-03-01")) cls: ClsType[_models.MetricAlertResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, rule_name=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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -465,16 +452,12 @@ def get(self, resource_group_name: str, rule_name: str, **kwargs: Any) -> _model error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("MetricAlertResource", pipeline_response) + deserialized = self._deserialize("MetricAlertResource", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - get.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/metricAlerts/{ruleName}" - } + return deserialized # type: ignore @overload def create_or_update( @@ -498,7 +481,6 @@ def create_or_update( :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: MetricAlertResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_03_01.models.MetricAlertResource :raises ~azure.core.exceptions.HttpResponseError: @@ -509,7 +491,7 @@ def create_or_update( self, resource_group_name: str, rule_name: str, - parameters: IO, + parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -522,11 +504,10 @@ def create_or_update( :param rule_name: The name of the rule. Required. :type rule_name: str :param parameters: The parameters of the rule to create or update. Required. - :type parameters: IO + :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: MetricAlertResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_03_01.models.MetricAlertResource :raises ~azure.core.exceptions.HttpResponseError: @@ -537,7 +518,7 @@ def create_or_update( self, resource_group_name: str, rule_name: str, - parameters: Union[_models.MetricAlertResource, IO], + parameters: Union[_models.MetricAlertResource, IO[bytes]], **kwargs: Any ) -> _models.MetricAlertResource: """Create or update an metric alert definition. @@ -548,17 +529,13 @@ def create_or_update( :param rule_name: The name of the rule. Required. :type rule_name: str :param parameters: The parameters of the rule to create or update. Is either a - MetricAlertResource type or a IO type. Required. - :type parameters: ~azure.mgmt.monitor.v2018_03_01.models.MetricAlertResource 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 + MetricAlertResource type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.monitor.v2018_03_01.models.MetricAlertResource or IO[bytes] :return: MetricAlertResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_03_01.models.MetricAlertResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -569,19 +546,19 @@ def create_or_update( _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", "2018-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2018-03-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.MetricAlertResource] = 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, "MetricAlertResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, rule_name=rule_name, subscription_id=self._config.subscription_id, @@ -589,16 +566,14 @@ def create_or_update( 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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -608,16 +583,12 @@ def create_or_update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("MetricAlertResource", pipeline_response) + deserialized = self._deserialize("MetricAlertResource", 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.Insights/metricAlerts/{ruleName}" - } + return deserialized # type: ignore @overload def update( @@ -641,7 +612,6 @@ def update( :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: MetricAlertResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_03_01.models.MetricAlertResource :raises ~azure.core.exceptions.HttpResponseError: @@ -652,7 +622,7 @@ def update( self, resource_group_name: str, rule_name: str, - parameters: IO, + parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -665,11 +635,10 @@ def update( :param rule_name: The name of the rule. Required. :type rule_name: str :param parameters: The parameters of the rule to update. Required. - :type parameters: IO + :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: MetricAlertResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_03_01.models.MetricAlertResource :raises ~azure.core.exceptions.HttpResponseError: @@ -680,7 +649,7 @@ def update( self, resource_group_name: str, rule_name: str, - parameters: Union[_models.MetricAlertResourcePatch, IO], + parameters: Union[_models.MetricAlertResourcePatch, IO[bytes]], **kwargs: Any ) -> _models.MetricAlertResource: """Update an metric alert definition. @@ -691,17 +660,13 @@ def update( :param rule_name: The name of the rule. Required. :type rule_name: str :param parameters: The parameters of the rule to update. Is either a MetricAlertResourcePatch - type or a IO type. Required. - :type parameters: ~azure.mgmt.monitor.v2018_03_01.models.MetricAlertResourcePatch 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 + type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.monitor.v2018_03_01.models.MetricAlertResourcePatch or IO[bytes] :return: MetricAlertResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_03_01.models.MetricAlertResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -712,19 +677,19 @@ def update( _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", "2018-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2018-03-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.MetricAlertResource] = 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, "MetricAlertResourcePatch") - request = build_update_request( + _request = build_update_request( resource_group_name=resource_group_name, rule_name=rule_name, subscription_id=self._config.subscription_id, @@ -732,16 +697,14 @@ def update( 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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -751,16 +714,12 @@ def update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("MetricAlertResource", pipeline_response) + deserialized = self._deserialize("MetricAlertResource", 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.Insights/metricAlerts/{ruleName}" - } + return deserialized # type: ignore @distributed_trace def delete( # pylint: disable=inconsistent-return-statements @@ -773,12 +732,11 @@ def delete( # pylint: disable=inconsistent-return-statements :type resource_group_name: str :param rule_name: The name of the rule. Required. :type 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, @@ -789,24 +747,22 @@ def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2018-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2018-03-01")) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, rule_name=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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -817,8 +773,4 @@ def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/metricAlerts/{ruleName}" - } + return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/operations/_metric_alerts_status_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/operations/_metric_alerts_status_operations.py index 95fde4631f7c..a89321385c6b 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/operations/_metric_alerts_status_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/operations/_metric_alerts_status_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,7 @@ # 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 ( @@ -17,16 +17,18 @@ map_error, ) 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 +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -54,7 +56,7 @@ def build_list_request(resource_group_name: str, rule_name: str, subscription_id "ruleName": _SERIALIZER.url("rule_name", rule_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -88,7 +90,7 @@ def build_list_by_name_request( "statusName": _SERIALIZER.url("status_name", status_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -117,6 +119,7 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list(self, resource_group_name: str, rule_name: str, **kwargs: Any) -> _models.MetricAlertStatusCollection: @@ -127,12 +130,11 @@ def list(self, resource_group_name: str, rule_name: str, **kwargs: Any) -> _mode :type resource_group_name: str :param rule_name: The name of the rule. Required. :type rule_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: MetricAlertStatusCollection or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_03_01.models.MetricAlertStatusCollection :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -143,24 +145,22 @@ def list(self, resource_group_name: str, rule_name: str, **kwargs: Any) -> _mode _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2018-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2018-03-01")) cls: ClsType[_models.MetricAlertStatusCollection] = kwargs.pop("cls", None) - request = build_list_request( + _request = build_list_request( resource_group_name=resource_group_name, rule_name=rule_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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -170,16 +170,12 @@ def list(self, resource_group_name: str, rule_name: str, **kwargs: Any) -> _mode error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("MetricAlertStatusCollection", pipeline_response) + deserialized = self._deserialize("MetricAlertStatusCollection", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - list.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/metricAlerts/{ruleName}/status" - } + return deserialized # type: ignore @distributed_trace def list_by_name( @@ -194,12 +190,11 @@ def list_by_name( :type rule_name: str :param status_name: The name of the status. Required. :type status_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: MetricAlertStatusCollection or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_03_01.models.MetricAlertStatusCollection :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -210,25 +205,23 @@ def list_by_name( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2018-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2018-03-01")) cls: ClsType[_models.MetricAlertStatusCollection] = kwargs.pop("cls", None) - request = build_list_by_name_request( + _request = build_list_by_name_request( resource_group_name=resource_group_name, rule_name=rule_name, status_name=status_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_name.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -238,13 +231,9 @@ def list_by_name( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("MetricAlertStatusCollection", pipeline_response) + deserialized = self._deserialize("MetricAlertStatusCollection", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - list_by_name.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/metricAlerts/{ruleName}/status/{statusName}" - } + return deserialized # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_04_16/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_04_16/__init__.py index 2c7733bfd566..42cc62301757 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_04_16/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_04_16/__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 ._monitor_management_client import MonitorManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._monitor_management_client import MonitorManagementClient # type: ignore from ._version import VERSION __version__ = VERSION try: from ._patch import __all__ as _patch_all - from ._patch import * # 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__ = [ "MonitorManagementClient", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_04_16/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_04_16/_configuration.py index c762f34e7a72..a23425f155a7 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_04_16/_configuration.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_04_16/_configuration.py @@ -8,18 +8,16 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy from ._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MonitorManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class MonitorManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for MonitorManagementClient. Note that all parameters used to create this instance are saved as instance @@ -35,7 +33,6 @@ class MonitorManagementClientConfiguration(Configuration): # pylint: disable=to """ def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: - super(MonitorManagementClientConfiguration, self).__init__(**kwargs) api_version: str = kwargs.pop("api_version", "2018-04-16") if credential is None: @@ -48,6 +45,7 @@ def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-monitor/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -56,9 +54,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.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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_04_16/_metadata.json b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_04_16/_metadata.json index 23673fec1434..01b0822370e9 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_04_16/_metadata.json +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_04_16/_metadata.json @@ -8,10 +8,10 @@ "host_value": "\"https://management.azure.com\"", "parameterized_host_template": null, "azure_arm": true, - "has_lro_operations": false, + "has_public_lro_operations": false, "client_side_validation": false, - "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"sdkcore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMAutoResourceProviderRegistrationPolicy\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}, \"stdlib\": {\"typing_extensions\": [\"Self\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"sdkcore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"AsyncARMAutoResourceProviderRegistrationPolicy\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}, \"stdlib\": {\"typing_extensions\": [\"Self\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "global_parameters": { "sync": { @@ -101,8 +101,8 @@ "credential_scopes": ["https://management.azure.com/.default"], "credential_call_sync": "ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", "credential_call_async": "AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", - "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "sync_imports": "{\"regular\": {\"sdkcore\": {\"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"regular\": {\"sdkcore\": {\"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "operation_groups": { "scheduled_query_rules": "ScheduledQueryRulesOperations" diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_04_16/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_04_16/_monitor_management_client.py index c022f2b49f74..e81ee41b5a53 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_04_16/_monitor_management_client.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_04_16/_monitor_management_client.py @@ -8,9 +8,12 @@ from copy import deepcopy from typing import Any, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient +from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy from . import models as _models from .._serialization import Deserializer, Serializer @@ -18,11 +21,10 @@ from .operations import ScheduledQueryRulesOperations if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MonitorManagementClient: # pylint: disable=client-accepts-api-version-keyword +class MonitorManagementClient: """Monitor Management Client. :ivar scheduled_query_rules: ScheduledQueryRulesOperations operations @@ -49,17 +51,35 @@ def __init__( self._config = MonitorManagementClientConfiguration( credential=credential, subscription_id=subscription_id, **kwargs ) - self._client: ARMPipelineClient = ARMPipelineClient(base_url=base_url, config=self._config, **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), + 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=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.scheduled_query_rules = ScheduledQueryRulesOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2018-04-16" ) - 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 @@ -79,12 +99,12 @@ 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) -> None: self._client.close() - def __enter__(self) -> "MonitorManagementClient": + def __enter__(self) -> Self: self._client.__enter__() return self diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_04_16/_vendor.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_04_16/_vendor.py deleted file mode 100644 index bd0df84f5319..000000000000 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_04_16/_vendor.py +++ /dev/null @@ -1,30 +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 typing import List, cast - -from azure.core.pipeline.transport import HttpRequest - - -def _convert_request(request, files=None): - data = request.content if not files else None - request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) - if files: - request.set_formdata_body(files) - return request - - -def _format_url_section(template, **kwargs): - components = template.split("/") - while components: - try: - return template.format(**kwargs) - except KeyError as key: - # Need the cast, as for some reasons "split" is typed as list[str | Any] - formatted_components = cast(List[str], template.split("/")) - components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] - template = "/".join(components) diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_04_16/_version.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_04_16/_version.py index 394ee7c0c03c..e5754a47ce68 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_04_16/_version.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_04_16/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "6.0.2" +VERSION = "1.0.0b1" diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_04_16/aio/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_04_16/aio/__init__.py index 2c151bb41c19..3df30ff42149 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_04_16/aio/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_04_16/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 ._monitor_management_client import MonitorManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._monitor_management_client import MonitorManagementClient # type: ignore try: from ._patch import __all__ as _patch_all - from ._patch import * # 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__ = [ "MonitorManagementClient", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_04_16/aio/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_04_16/aio/_configuration.py index 9b10881a577b..19c89595233d 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_04_16/aio/_configuration.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_04_16/aio/_configuration.py @@ -8,18 +8,16 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy from .._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MonitorManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class MonitorManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for MonitorManagementClient. Note that all parameters used to create this instance are saved as instance @@ -35,7 +33,6 @@ class MonitorManagementClientConfiguration(Configuration): # pylint: disable=to """ def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: - super(MonitorManagementClientConfiguration, self).__init__(**kwargs) api_version: str = kwargs.pop("api_version", "2018-04-16") if credential is None: @@ -48,6 +45,7 @@ def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **k self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-monitor/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -56,9 +54,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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_04_16/aio/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_04_16/aio/_monitor_management_client.py index b8dca5d39113..1ebb38e10bee 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_04_16/aio/_monitor_management_client.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_04_16/aio/_monitor_management_client.py @@ -8,9 +8,12 @@ from copy import deepcopy from typing import Any, Awaitable, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient +from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy from .. import models as _models from ..._serialization import Deserializer, Serializer @@ -18,11 +21,10 @@ from .operations import ScheduledQueryRulesOperations if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MonitorManagementClient: # pylint: disable=client-accepts-api-version-keyword +class MonitorManagementClient: """Monitor Management Client. :ivar scheduled_query_rules: ScheduledQueryRulesOperations operations @@ -49,17 +51,37 @@ def __init__( self._config = MonitorManagementClientConfiguration( credential=credential, subscription_id=subscription_id, **kwargs ) - self._client: AsyncARMPipelineClient = AsyncARMPipelineClient(base_url=base_url, config=self._config, **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=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.scheduled_query_rules = ScheduledQueryRulesOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2018-04-16" ) - 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 @@ -79,12 +101,12 @@ 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) -> "MonitorManagementClient": + async def __aenter__(self) -> Self: await self._client.__aenter__() return self diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_04_16/aio/operations/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_04_16/aio/operations/__init__.py index e010c281d4fc..795e91ef6843 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_04_16/aio/operations/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_04_16/aio/operations/__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 ._scheduled_query_rules_operations import ScheduledQueryRulesOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._scheduled_query_rules_operations import ScheduledQueryRulesOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ "ScheduledQueryRulesOperations", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_04_16/aio/operations/_scheduled_query_rules_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_04_16/aio/operations/_scheduled_query_rules_operations.py index a57ab86c2b03..1daee8357545 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_04_16/aio/operations/_scheduled_query_rules_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_04_16/aio/operations/_scheduled_query_rules_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload import urllib.parse @@ -19,15 +20,13 @@ 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 ...operations._scheduled_query_rules_operations import ( build_create_or_update_request, build_delete_request, @@ -37,6 +36,10 @@ build_update_request, ) +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -59,6 +62,7 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @overload async def create_or_update( @@ -82,7 +86,6 @@ async def create_or_update( :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: LogSearchRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_04_16.models.LogSearchRuleResource :raises ~azure.core.exceptions.HttpResponseError: @@ -93,7 +96,7 @@ async def create_or_update( self, resource_group_name: str, rule_name: str, - parameters: IO, + parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -106,11 +109,10 @@ async def create_or_update( :param rule_name: The name of the rule. Required. :type rule_name: str :param parameters: The parameters of the rule to create or update. Required. - :type parameters: IO + :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: LogSearchRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_04_16.models.LogSearchRuleResource :raises ~azure.core.exceptions.HttpResponseError: @@ -121,7 +123,7 @@ async def create_or_update( self, resource_group_name: str, rule_name: str, - parameters: Union[_models.LogSearchRuleResource, IO], + parameters: Union[_models.LogSearchRuleResource, IO[bytes]], **kwargs: Any ) -> _models.LogSearchRuleResource: """Creates or updates an log search rule. @@ -132,17 +134,13 @@ async def create_or_update( :param rule_name: The name of the rule. Required. :type rule_name: str :param parameters: The parameters of the rule to create or update. Is either a - LogSearchRuleResource type or a IO type. Required. - :type parameters: ~azure.mgmt.monitor.v2018_04_16.models.LogSearchRuleResource 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 + LogSearchRuleResource type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.monitor.v2018_04_16.models.LogSearchRuleResource or IO[bytes] :return: LogSearchRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_04_16.models.LogSearchRuleResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -153,19 +151,19 @@ async def create_or_update( _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", "2018-04-16")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2018-04-16")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.LogSearchRuleResource] = 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, "LogSearchRuleResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, rule_name=rule_name, subscription_id=self._config.subscription_id, @@ -173,16 +171,14 @@ async def create_or_update( 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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -192,21 +188,13 @@ async def create_or_update( error = self._deserialize.failsafe_deserialize(_models.ErrorContract, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if response.status_code == 200: - deserialized = self._deserialize("LogSearchRuleResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("LogSearchRuleResource", pipeline_response) + deserialized = self._deserialize("LogSearchRuleResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/scheduledQueryRules/{ruleName}" - } - @distributed_trace_async async def get(self, resource_group_name: str, rule_name: str, **kwargs: Any) -> _models.LogSearchRuleResource: """Gets an Log Search rule. @@ -216,12 +204,11 @@ async def get(self, resource_group_name: str, rule_name: str, **kwargs: Any) -> :type resource_group_name: str :param rule_name: The name of the rule. Required. :type rule_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: LogSearchRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_04_16.models.LogSearchRuleResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -232,24 +219,22 @@ async def get(self, resource_group_name: str, rule_name: str, **kwargs: Any) -> _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2018-04-16")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2018-04-16")) cls: ClsType[_models.LogSearchRuleResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, rule_name=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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -259,16 +244,12 @@ async def get(self, resource_group_name: str, rule_name: str, **kwargs: Any) -> error = self._deserialize.failsafe_deserialize(_models.ErrorContract, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("LogSearchRuleResource", pipeline_response) + deserialized = self._deserialize("LogSearchRuleResource", 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.Insights/scheduledQueryRules/{ruleName}" - } + return deserialized # type: ignore @overload async def update( @@ -292,7 +273,6 @@ async def update( :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: LogSearchRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_04_16.models.LogSearchRuleResource :raises ~azure.core.exceptions.HttpResponseError: @@ -303,7 +283,7 @@ async def update( self, resource_group_name: str, rule_name: str, - parameters: IO, + parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -316,11 +296,10 @@ async def update( :param rule_name: The name of the rule. Required. :type rule_name: str :param parameters: The parameters of the rule to update. Required. - :type parameters: IO + :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: LogSearchRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_04_16.models.LogSearchRuleResource :raises ~azure.core.exceptions.HttpResponseError: @@ -331,7 +310,7 @@ async def update( self, resource_group_name: str, rule_name: str, - parameters: Union[_models.LogSearchRuleResourcePatch, IO], + parameters: Union[_models.LogSearchRuleResourcePatch, IO[bytes]], **kwargs: Any ) -> _models.LogSearchRuleResource: """Update log search Rule. @@ -342,17 +321,14 @@ async def update( :param rule_name: The name of the rule. Required. :type rule_name: str :param parameters: The parameters of the rule to update. Is either a LogSearchRuleResourcePatch - type or a IO type. Required. - :type parameters: ~azure.mgmt.monitor.v2018_04_16.models.LogSearchRuleResourcePatch 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 + type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.monitor.v2018_04_16.models.LogSearchRuleResourcePatch or + IO[bytes] :return: LogSearchRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_04_16.models.LogSearchRuleResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -363,19 +339,19 @@ async def update( _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", "2018-04-16")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2018-04-16")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.LogSearchRuleResource] = 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, "LogSearchRuleResourcePatch") - request = build_update_request( + _request = build_update_request( resource_group_name=resource_group_name, rule_name=rule_name, subscription_id=self._config.subscription_id, @@ -383,16 +359,14 @@ async def update( 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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -402,21 +376,15 @@ async def update( error = self._deserialize.failsafe_deserialize(_models.ErrorContract, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("LogSearchRuleResource", pipeline_response) + deserialized = self._deserialize("LogSearchRuleResource", 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.Insights/scheduledQueryRules/{ruleName}" - } + return deserialized # type: ignore @distributed_trace_async - async def delete( # pylint: disable=inconsistent-return-statements - self, resource_group_name: str, rule_name: str, **kwargs: Any - ) -> None: + async def delete(self, resource_group_name: str, rule_name: str, **kwargs: Any) -> None: """Deletes a Log Search rule. :param resource_group_name: The name of the resource group. The name is case insensitive. @@ -424,12 +392,11 @@ async def delete( # pylint: disable=inconsistent-return-statements :type resource_group_name: str :param rule_name: The name of the rule. Required. :type 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, @@ -440,24 +407,22 @@ async def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2018-04-16")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2018-04-16")) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, rule_name=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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -468,11 +433,7 @@ async def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/scheduledQueryRules/{ruleName}" - } + return cls(pipeline_response, None, {}) # type: ignore @distributed_trace def list_by_subscription( @@ -483,7 +444,6 @@ def list_by_subscription( :param filter: The filter to apply on the operation. For more information please see https://msdn.microsoft.com/en-us/library/azure/dn931934.aspx. Default value is None. :type filter: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either LogSearchRuleResource or the result of cls(response) :rtype: @@ -493,10 +453,10 @@ def list_by_subscription( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2018-04-16")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2018-04-16")) cls: ClsType[_models.LogSearchRuleResourceCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -507,16 +467,14 @@ def list_by_subscription( def prepare_request(next_link=None): if not next_link: - request = build_list_by_subscription_request( + _request = build_list_by_subscription_request( subscription_id=self._config.subscription_id, filter=filter, api_version=api_version, - template_url=self.list_by_subscription.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -527,14 +485,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("LogSearchRuleResourceCollection", pipeline_response) @@ -544,11 +501,11 @@ async def extract_data(pipeline_response): return None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -561,10 +518,6 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_by_subscription.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/scheduledQueryRules" - } - @distributed_trace def list_by_resource_group( self, resource_group_name: str, filter: Optional[str] = None, **kwargs: Any @@ -577,7 +530,6 @@ def list_by_resource_group( :param filter: The filter to apply on the operation. For more information please see https://msdn.microsoft.com/en-us/library/azure/dn931934.aspx. Default value is None. :type filter: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either LogSearchRuleResource or the result of cls(response) :rtype: @@ -587,10 +539,10 @@ def list_by_resource_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2018-04-16")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2018-04-16")) cls: ClsType[_models.LogSearchRuleResourceCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -601,17 +553,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_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, filter=filter, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -622,14 +572,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("LogSearchRuleResourceCollection", pipeline_response) @@ -639,11 +588,11 @@ async def extract_data(pipeline_response): return None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -655,7 +604,3 @@ async def get_next(next_link=None): return pipeline_response return AsyncItemPaged(get_next, extract_data) - - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/scheduledQueryRules" - } diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_04_16/models/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_04_16/models/__init__.py index 72a250bda7be..993848a5a13e 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_04_16/models/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_04_16/models/__init__.py @@ -5,33 +5,44 @@ # 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 Action -from ._models_py3 import AlertingAction -from ._models_py3 import AzNsActionGroup -from ._models_py3 import Criteria -from ._models_py3 import Dimension -from ._models_py3 import ErrorContract -from ._models_py3 import ErrorResponse -from ._models_py3 import LogMetricTrigger -from ._models_py3 import LogSearchRuleResource -from ._models_py3 import LogSearchRuleResourceCollection -from ._models_py3 import LogSearchRuleResourcePatch -from ._models_py3 import LogToMetricAction -from ._models_py3 import Resource -from ._models_py3 import Schedule -from ._models_py3 import Source -from ._models_py3 import TriggerCondition +from typing import TYPE_CHECKING -from ._monitor_management_client_enums import AlertSeverity -from ._monitor_management_client_enums import ConditionalOperator -from ._monitor_management_client_enums import Enabled -from ._monitor_management_client_enums import MetricTriggerType -from ._monitor_management_client_enums import Operator -from ._monitor_management_client_enums import ProvisioningState -from ._monitor_management_client_enums import QueryType +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models_py3 import ( # type: ignore + Action, + AlertingAction, + AzNsActionGroup, + Criteria, + Dimension, + ErrorContract, + ErrorResponse, + LogMetricTrigger, + LogSearchRuleResource, + LogSearchRuleResourceCollection, + LogSearchRuleResourcePatch, + LogToMetricAction, + Resource, + Schedule, + Source, + TriggerCondition, +) + +from ._monitor_management_client_enums import ( # type: ignore + AlertSeverity, + ConditionalOperator, + Enabled, + MetricTriggerType, + Operator, + ProvisioningState, + QueryType, +) from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ @@ -59,5 +70,5 @@ "ProvisioningState", "QueryType", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_04_16/models/_models_py3.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_04_16/models/_models_py3.py index df113d7354f1..9b77dab4f7e2 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_04_16/models/_models_py3.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_04_16/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. @@ -12,7 +11,6 @@ from ... import _serialization if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from .. import models as _models @@ -22,7 +20,7 @@ class Action(_serialization.Model): You probably want to use the sub-classes and not this class directly. Known sub-classes are: AlertingAction, LogToMetricAction - 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 odata_type: Specifies the action. Supported values - AlertingAction, LogToMetricAction. Required. @@ -53,7 +51,7 @@ def __init__(self, **kwargs: Any) -> None: class AlertingAction(Action): """Specify action need to be taken when rule type is Alert. - 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 odata_type: Specifies the action. Supported values - AlertingAction, LogToMetricAction. Required. @@ -104,7 +102,9 @@ def __init__( :paramtype trigger: ~azure.mgmt.monitor.v2018_04_16.models.TriggerCondition """ super().__init__(**kwargs) - self.odata_type: str = "Microsoft.WindowsAzure.Management.Monitoring.Alerts.Models.Microsoft.AppInsights.Nexus.DataContracts.Resources.ScheduledQueryRules.AlertingAction" + self.odata_type: str = ( + "Microsoft.WindowsAzure.Management.Monitoring.Alerts.Models.Microsoft.AppInsights.Nexus.DataContracts.Resources.ScheduledQueryRules.AlertingAction" + ) self.severity = severity self.azns_action = azns_action self.throttling_in_min = throttling_in_min @@ -155,7 +155,7 @@ def __init__( class Criteria(_serialization.Model): """Specifies the criteria for converting log to metric. - 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 metric_name: Name of the metric. Required. :vartype metric_name: str @@ -189,7 +189,7 @@ def __init__( class Dimension(_serialization.Model): """Specifies the criteria for converting log to metric. - 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: Name of the dimension. Required. :vartype name: str @@ -332,7 +332,7 @@ class Resource(_serialization.Model): 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: Azure resource Id. :vartype id: str @@ -392,12 +392,12 @@ def __init__(self, *, location: str, tags: Optional[Dict[str, str]] = None, **kw self.etag = None -class LogSearchRuleResource(Resource): # pylint: disable=too-many-instance-attributes +class LogSearchRuleResource(Resource): """The Log Search Rule 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: Azure resource Id. :vartype id: str @@ -591,7 +591,7 @@ def __init__( class LogToMetricAction(Action): """Specify action need to be taken when rule type is converting log to metric. - 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 odata_type: Specifies the action. Supported values - AlertingAction, LogToMetricAction. Required. @@ -616,14 +616,16 @@ def __init__(self, *, criteria: List["_models.Criteria"], **kwargs: Any) -> None :paramtype criteria: list[~azure.mgmt.monitor.v2018_04_16.models.Criteria] """ super().__init__(**kwargs) - self.odata_type: str = "Microsoft.WindowsAzure.Management.Monitoring.Alerts.Models.Microsoft.AppInsights.Nexus.DataContracts.Resources.ScheduledQueryRules.LogToMetricAction" + self.odata_type: str = ( + "Microsoft.WindowsAzure.Management.Monitoring.Alerts.Models.Microsoft.AppInsights.Nexus.DataContracts.Resources.ScheduledQueryRules.LogToMetricAction" + ) self.criteria = criteria class Schedule(_serialization.Model): """Defines how often to run the search and the time interval. - 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 frequency_in_minutes: frequency (in minutes) at which rule condition should be evaluated. Required. @@ -660,7 +662,7 @@ def __init__(self, *, frequency_in_minutes: int, time_window_in_minutes: int, ** class Source(_serialization.Model): """Specifies the log search query. - 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 query: Log search query. Required for action type - AlertingAction. :vartype query: str @@ -712,7 +714,7 @@ def __init__( class TriggerCondition(_serialization.Model): """The condition that results in the Log Search rule. - 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 threshold_operator: Evaluation operation for rule - 'GreaterThan' or 'LessThan. Known values are: "GreaterThanOrEqual", "LessThanOrEqual", "GreaterThan", "LessThan", and "Equal". diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_04_16/operations/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_04_16/operations/__init__.py index e010c281d4fc..795e91ef6843 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_04_16/operations/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_04_16/operations/__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 ._scheduled_query_rules_operations import ScheduledQueryRulesOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._scheduled_query_rules_operations import ScheduledQueryRulesOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ "ScheduledQueryRulesOperations", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_04_16/operations/_scheduled_query_rules_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_04_16/operations/_scheduled_query_rules_operations.py index 6b70283f25a0..430664d4ea6b 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_04_16/operations/_scheduled_query_rules_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_04_16/operations/_scheduled_query_rules_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload import urllib.parse @@ -19,16 +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, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -59,7 +62,7 @@ def build_create_or_update_request( "ruleName": _SERIALIZER.url("rule_name", rule_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -92,7 +95,7 @@ def build_get_request(resource_group_name: str, rule_name: str, subscription_id: "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -124,7 +127,7 @@ def build_update_request(resource_group_name: str, rule_name: str, subscription_ "ruleName": _SERIALIZER.url("rule_name", rule_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -157,7 +160,7 @@ def build_delete_request(resource_group_name: str, rule_name: str, subscription_ "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -185,7 +188,7 @@ def build_list_by_subscription_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -219,7 +222,7 @@ def build_list_by_resource_group_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -250,6 +253,7 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @overload def create_or_update( @@ -273,7 +277,6 @@ def create_or_update( :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: LogSearchRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_04_16.models.LogSearchRuleResource :raises ~azure.core.exceptions.HttpResponseError: @@ -284,7 +287,7 @@ def create_or_update( self, resource_group_name: str, rule_name: str, - parameters: IO, + parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -297,11 +300,10 @@ def create_or_update( :param rule_name: The name of the rule. Required. :type rule_name: str :param parameters: The parameters of the rule to create or update. Required. - :type parameters: IO + :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: LogSearchRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_04_16.models.LogSearchRuleResource :raises ~azure.core.exceptions.HttpResponseError: @@ -312,7 +314,7 @@ def create_or_update( self, resource_group_name: str, rule_name: str, - parameters: Union[_models.LogSearchRuleResource, IO], + parameters: Union[_models.LogSearchRuleResource, IO[bytes]], **kwargs: Any ) -> _models.LogSearchRuleResource: """Creates or updates an log search rule. @@ -323,17 +325,13 @@ def create_or_update( :param rule_name: The name of the rule. Required. :type rule_name: str :param parameters: The parameters of the rule to create or update. Is either a - LogSearchRuleResource type or a IO type. Required. - :type parameters: ~azure.mgmt.monitor.v2018_04_16.models.LogSearchRuleResource 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 + LogSearchRuleResource type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.monitor.v2018_04_16.models.LogSearchRuleResource or IO[bytes] :return: LogSearchRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_04_16.models.LogSearchRuleResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -344,19 +342,19 @@ def create_or_update( _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", "2018-04-16")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2018-04-16")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.LogSearchRuleResource] = 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, "LogSearchRuleResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, rule_name=rule_name, subscription_id=self._config.subscription_id, @@ -364,16 +362,14 @@ def create_or_update( 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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -383,21 +379,13 @@ def create_or_update( error = self._deserialize.failsafe_deserialize(_models.ErrorContract, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if response.status_code == 200: - deserialized = self._deserialize("LogSearchRuleResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("LogSearchRuleResource", pipeline_response) + deserialized = self._deserialize("LogSearchRuleResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/scheduledQueryRules/{ruleName}" - } - @distributed_trace def get(self, resource_group_name: str, rule_name: str, **kwargs: Any) -> _models.LogSearchRuleResource: """Gets an Log Search rule. @@ -407,12 +395,11 @@ def get(self, resource_group_name: str, rule_name: str, **kwargs: Any) -> _model :type resource_group_name: str :param rule_name: The name of the rule. Required. :type rule_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: LogSearchRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_04_16.models.LogSearchRuleResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -423,24 +410,22 @@ def get(self, resource_group_name: str, rule_name: str, **kwargs: Any) -> _model _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2018-04-16")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2018-04-16")) cls: ClsType[_models.LogSearchRuleResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, rule_name=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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -450,16 +435,12 @@ def get(self, resource_group_name: str, rule_name: str, **kwargs: Any) -> _model error = self._deserialize.failsafe_deserialize(_models.ErrorContract, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("LogSearchRuleResource", pipeline_response) + deserialized = self._deserialize("LogSearchRuleResource", 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.Insights/scheduledQueryRules/{ruleName}" - } + return deserialized # type: ignore @overload def update( @@ -483,7 +464,6 @@ def update( :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: LogSearchRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_04_16.models.LogSearchRuleResource :raises ~azure.core.exceptions.HttpResponseError: @@ -494,7 +474,7 @@ def update( self, resource_group_name: str, rule_name: str, - parameters: IO, + parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -507,11 +487,10 @@ def update( :param rule_name: The name of the rule. Required. :type rule_name: str :param parameters: The parameters of the rule to update. Required. - :type parameters: IO + :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: LogSearchRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_04_16.models.LogSearchRuleResource :raises ~azure.core.exceptions.HttpResponseError: @@ -522,7 +501,7 @@ def update( self, resource_group_name: str, rule_name: str, - parameters: Union[_models.LogSearchRuleResourcePatch, IO], + parameters: Union[_models.LogSearchRuleResourcePatch, IO[bytes]], **kwargs: Any ) -> _models.LogSearchRuleResource: """Update log search Rule. @@ -533,17 +512,14 @@ def update( :param rule_name: The name of the rule. Required. :type rule_name: str :param parameters: The parameters of the rule to update. Is either a LogSearchRuleResourcePatch - type or a IO type. Required. - :type parameters: ~azure.mgmt.monitor.v2018_04_16.models.LogSearchRuleResourcePatch 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 + type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.monitor.v2018_04_16.models.LogSearchRuleResourcePatch or + IO[bytes] :return: LogSearchRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_04_16.models.LogSearchRuleResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -554,19 +530,19 @@ def update( _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", "2018-04-16")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2018-04-16")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.LogSearchRuleResource] = 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, "LogSearchRuleResourcePatch") - request = build_update_request( + _request = build_update_request( resource_group_name=resource_group_name, rule_name=rule_name, subscription_id=self._config.subscription_id, @@ -574,16 +550,14 @@ def update( 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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -593,16 +567,12 @@ def update( error = self._deserialize.failsafe_deserialize(_models.ErrorContract, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("LogSearchRuleResource", pipeline_response) + deserialized = self._deserialize("LogSearchRuleResource", 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.Insights/scheduledQueryRules/{ruleName}" - } + return deserialized # type: ignore @distributed_trace def delete( # pylint: disable=inconsistent-return-statements @@ -615,12 +585,11 @@ def delete( # pylint: disable=inconsistent-return-statements :type resource_group_name: str :param rule_name: The name of the rule. Required. :type 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, @@ -631,24 +600,22 @@ def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2018-04-16")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2018-04-16")) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, rule_name=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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -659,11 +626,7 @@ def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/scheduledQueryRules/{ruleName}" - } + return cls(pipeline_response, None, {}) # type: ignore @distributed_trace def list_by_subscription( @@ -674,7 +637,6 @@ def list_by_subscription( :param filter: The filter to apply on the operation. For more information please see https://msdn.microsoft.com/en-us/library/azure/dn931934.aspx. Default value is None. :type filter: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either LogSearchRuleResource or the result of cls(response) :rtype: @@ -684,10 +646,10 @@ def list_by_subscription( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2018-04-16")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2018-04-16")) cls: ClsType[_models.LogSearchRuleResourceCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -698,16 +660,14 @@ def list_by_subscription( def prepare_request(next_link=None): if not next_link: - request = build_list_by_subscription_request( + _request = build_list_by_subscription_request( subscription_id=self._config.subscription_id, filter=filter, api_version=api_version, - template_url=self.list_by_subscription.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -718,14 +678,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("LogSearchRuleResourceCollection", pipeline_response) @@ -735,11 +694,11 @@ def extract_data(pipeline_response): return None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -752,10 +711,6 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_by_subscription.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/scheduledQueryRules" - } - @distributed_trace def list_by_resource_group( self, resource_group_name: str, filter: Optional[str] = None, **kwargs: Any @@ -768,7 +723,6 @@ def list_by_resource_group( :param filter: The filter to apply on the operation. For more information please see https://msdn.microsoft.com/en-us/library/azure/dn931934.aspx. Default value is None. :type filter: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either LogSearchRuleResource or the result of cls(response) :rtype: @@ -778,10 +732,10 @@ def list_by_resource_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2018-04-16")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2018-04-16")) cls: ClsType[_models.LogSearchRuleResourceCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -792,17 +746,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_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, filter=filter, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -813,14 +765,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("LogSearchRuleResourceCollection", pipeline_response) @@ -830,11 +781,11 @@ def extract_data(pipeline_response): return None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -846,7 +797,3 @@ def get_next(next_link=None): return pipeline_response return ItemPaged(get_next, extract_data) - - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/scheduledQueryRules" - } diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_06_01_preview/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_06_01_preview/__init__.py index 2c7733bfd566..42cc62301757 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_06_01_preview/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_06_01_preview/__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 ._monitor_management_client import MonitorManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._monitor_management_client import MonitorManagementClient # type: ignore from ._version import VERSION __version__ = VERSION try: from ._patch import __all__ as _patch_all - from ._patch import * # 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__ = [ "MonitorManagementClient", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_06_01_preview/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_06_01_preview/_configuration.py index 31454ff2ef96..f2ca10001189 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_06_01_preview/_configuration.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_06_01_preview/_configuration.py @@ -8,18 +8,16 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy from ._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MonitorManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class MonitorManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for MonitorManagementClient. Note that all parameters used to create this instance are saved as instance @@ -35,7 +33,6 @@ class MonitorManagementClientConfiguration(Configuration): # pylint: disable=to """ def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: - super(MonitorManagementClientConfiguration, self).__init__(**kwargs) api_version: str = kwargs.pop("api_version", "2018-06-01-preview") if credential is None: @@ -48,6 +45,7 @@ def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-monitor/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -56,9 +54,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.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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_06_01_preview/_metadata.json b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_06_01_preview/_metadata.json index a48d09b87bd5..3e9dec993bf3 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_06_01_preview/_metadata.json +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_06_01_preview/_metadata.json @@ -8,10 +8,10 @@ "host_value": "\"https://management.azure.com\"", "parameterized_host_template": null, "azure_arm": true, - "has_lro_operations": false, + "has_public_lro_operations": false, "client_side_validation": false, - "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"sdkcore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMAutoResourceProviderRegistrationPolicy\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}, \"stdlib\": {\"typing_extensions\": [\"Self\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"sdkcore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"AsyncARMAutoResourceProviderRegistrationPolicy\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}, \"stdlib\": {\"typing_extensions\": [\"Self\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "global_parameters": { "sync": { @@ -101,8 +101,8 @@ "credential_scopes": ["https://management.azure.com/.default"], "credential_call_sync": "ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", "credential_call_async": "AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", - "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "sync_imports": "{\"regular\": {\"sdkcore\": {\"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"regular\": {\"sdkcore\": {\"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "operation_groups": { "guest_diagnostics_settings_association": "GuestDiagnosticsSettingsAssociationOperations", diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_06_01_preview/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_06_01_preview/_monitor_management_client.py index 33794da101b2..b2e315bbe579 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_06_01_preview/_monitor_management_client.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_06_01_preview/_monitor_management_client.py @@ -8,9 +8,12 @@ from copy import deepcopy from typing import Any, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient +from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy from . import models as _models from .._serialization import Deserializer, Serializer @@ -18,11 +21,10 @@ from .operations import GuestDiagnosticsSettingsAssociationOperations, GuestDiagnosticsSettingsOperations if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MonitorManagementClient: # pylint: disable=client-accepts-api-version-keyword +class MonitorManagementClient: """Monitor Management Client. :ivar guest_diagnostics_settings_association: GuestDiagnosticsSettingsAssociationOperations @@ -53,20 +55,38 @@ def __init__( self._config = MonitorManagementClientConfiguration( credential=credential, subscription_id=subscription_id, **kwargs ) - self._client: ARMPipelineClient = ARMPipelineClient(base_url=base_url, config=self._config, **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), + 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=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.guest_diagnostics_settings_association = GuestDiagnosticsSettingsAssociationOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2018-06-01-preview" ) self.guest_diagnostics_settings = GuestDiagnosticsSettingsOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2018-06-01-preview" ) - 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 @@ -86,12 +106,12 @@ 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) -> None: self._client.close() - def __enter__(self) -> "MonitorManagementClient": + def __enter__(self) -> Self: self._client.__enter__() return self diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_06_01_preview/_vendor.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_06_01_preview/_vendor.py deleted file mode 100644 index bd0df84f5319..000000000000 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_06_01_preview/_vendor.py +++ /dev/null @@ -1,30 +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 typing import List, cast - -from azure.core.pipeline.transport import HttpRequest - - -def _convert_request(request, files=None): - data = request.content if not files else None - request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) - if files: - request.set_formdata_body(files) - return request - - -def _format_url_section(template, **kwargs): - components = template.split("/") - while components: - try: - return template.format(**kwargs) - except KeyError as key: - # Need the cast, as for some reasons "split" is typed as list[str | Any] - formatted_components = cast(List[str], template.split("/")) - components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] - template = "/".join(components) diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_06_01_preview/_version.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_06_01_preview/_version.py index 394ee7c0c03c..e5754a47ce68 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_06_01_preview/_version.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_06_01_preview/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "6.0.2" +VERSION = "1.0.0b1" diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_06_01_preview/aio/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_06_01_preview/aio/__init__.py index 2c151bb41c19..3df30ff42149 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_06_01_preview/aio/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_06_01_preview/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 ._monitor_management_client import MonitorManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._monitor_management_client import MonitorManagementClient # type: ignore try: from ._patch import __all__ as _patch_all - from ._patch import * # 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__ = [ "MonitorManagementClient", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_06_01_preview/aio/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_06_01_preview/aio/_configuration.py index 44fe163ef869..01ddfbb008e4 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_06_01_preview/aio/_configuration.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_06_01_preview/aio/_configuration.py @@ -8,18 +8,16 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy from .._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MonitorManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class MonitorManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for MonitorManagementClient. Note that all parameters used to create this instance are saved as instance @@ -35,7 +33,6 @@ class MonitorManagementClientConfiguration(Configuration): # pylint: disable=to """ def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: - super(MonitorManagementClientConfiguration, self).__init__(**kwargs) api_version: str = kwargs.pop("api_version", "2018-06-01-preview") if credential is None: @@ -48,6 +45,7 @@ def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **k self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-monitor/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -56,9 +54,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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_06_01_preview/aio/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_06_01_preview/aio/_monitor_management_client.py index c395f083fff5..75f2327bcab3 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_06_01_preview/aio/_monitor_management_client.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_06_01_preview/aio/_monitor_management_client.py @@ -8,9 +8,12 @@ from copy import deepcopy from typing import Any, Awaitable, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient +from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy from .. import models as _models from ..._serialization import Deserializer, Serializer @@ -18,11 +21,10 @@ from .operations import GuestDiagnosticsSettingsAssociationOperations, GuestDiagnosticsSettingsOperations if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MonitorManagementClient: # pylint: disable=client-accepts-api-version-keyword +class MonitorManagementClient: """Monitor Management Client. :ivar guest_diagnostics_settings_association: GuestDiagnosticsSettingsAssociationOperations @@ -53,20 +55,40 @@ def __init__( self._config = MonitorManagementClientConfiguration( credential=credential, subscription_id=subscription_id, **kwargs ) - self._client: AsyncARMPipelineClient = AsyncARMPipelineClient(base_url=base_url, config=self._config, **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=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.guest_diagnostics_settings_association = GuestDiagnosticsSettingsAssociationOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2018-06-01-preview" ) self.guest_diagnostics_settings = GuestDiagnosticsSettingsOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2018-06-01-preview" ) - 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 @@ -86,12 +108,12 @@ 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) -> "MonitorManagementClient": + async def __aenter__(self) -> Self: await self._client.__aenter__() return self diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_06_01_preview/aio/operations/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_06_01_preview/aio/operations/__init__.py index 2f4965e07c4c..402790b802c9 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_06_01_preview/aio/operations/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_06_01_preview/aio/operations/__init__.py @@ -5,17 +5,23 @@ # 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 ._guest_diagnostics_settings_association_operations import GuestDiagnosticsSettingsAssociationOperations -from ._guest_diagnostics_settings_operations import GuestDiagnosticsSettingsOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._guest_diagnostics_settings_association_operations import GuestDiagnosticsSettingsAssociationOperations # type: ignore +from ._guest_diagnostics_settings_operations import GuestDiagnosticsSettingsOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ "GuestDiagnosticsSettingsAssociationOperations", "GuestDiagnosticsSettingsOperations", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_06_01_preview/aio/operations/_guest_diagnostics_settings_association_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_06_01_preview/aio/operations/_guest_diagnostics_settings_association_operations.py index 26aa8584c5dd..d8fd4c1af1bc 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_06_01_preview/aio/operations/_guest_diagnostics_settings_association_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_06_01_preview/aio/operations/_guest_diagnostics_settings_association_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload import urllib.parse @@ -19,15 +20,13 @@ 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 ...operations._guest_diagnostics_settings_association_operations import ( build_create_or_update_request, build_delete_request, @@ -37,11 +36,15 @@ build_update_request, ) +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class GuestDiagnosticsSettingsAssociationOperations: +class GuestDiagnosticsSettingsAssociationOperations: # pylint: disable=name-too-long """ .. warning:: **DO NOT** instantiate this class directly. @@ -59,6 +62,7 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @overload async def create_or_update( @@ -84,7 +88,6 @@ async def create_or_update( :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: GuestDiagnosticSettingsAssociationResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_06_01_preview.models.GuestDiagnosticSettingsAssociationResource @@ -96,7 +99,7 @@ async def create_or_update( self, resource_uri: str, association_name: str, - diagnostic_settings_association: IO, + diagnostic_settings_association: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -110,11 +113,10 @@ async def create_or_update( :type association_name: str :param diagnostic_settings_association: The diagnostic settings association to create or update. Required. - :type diagnostic_settings_association: IO + :type diagnostic_settings_association: 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: GuestDiagnosticSettingsAssociationResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_06_01_preview.models.GuestDiagnosticSettingsAssociationResource @@ -126,7 +128,7 @@ async def create_or_update( self, resource_uri: str, association_name: str, - diagnostic_settings_association: Union[_models.GuestDiagnosticSettingsAssociationResource, IO], + diagnostic_settings_association: Union[_models.GuestDiagnosticSettingsAssociationResource, IO[bytes]], **kwargs: Any ) -> _models.GuestDiagnosticSettingsAssociationResource: """Creates or updates guest diagnostics settings association. @@ -137,19 +139,17 @@ async def create_or_update( :param association_name: The name of the diagnostic settings association. Required. :type association_name: str :param diagnostic_settings_association: The diagnostic settings association to create or - update. Is either a GuestDiagnosticSettingsAssociationResource type or a IO type. Required. + update. Is either a GuestDiagnosticSettingsAssociationResource type or a IO[bytes] type. + Required. :type diagnostic_settings_association: - ~azure.mgmt.monitor.v2018_06_01_preview.models.GuestDiagnosticSettingsAssociationResource 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 + ~azure.mgmt.monitor.v2018_06_01_preview.models.GuestDiagnosticSettingsAssociationResource or + IO[bytes] :return: GuestDiagnosticSettingsAssociationResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_06_01_preview.models.GuestDiagnosticSettingsAssociationResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -160,35 +160,35 @@ async def create_or_update( _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", "2018-06-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2018-06-01-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.GuestDiagnosticSettingsAssociationResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(diagnostic_settings_association, (IO, bytes)): + if isinstance(diagnostic_settings_association, (IOBase, bytes)): _content = diagnostic_settings_association else: _json = self._serialize.body(diagnostic_settings_association, "GuestDiagnosticSettingsAssociationResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_uri=resource_uri, association_name=association_name, 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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -198,21 +198,13 @@ async def create_or_update( 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("GuestDiagnosticSettingsAssociationResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("GuestDiagnosticSettingsAssociationResource", pipeline_response) + deserialized = self._deserialize("GuestDiagnosticSettingsAssociationResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create_or_update.metadata = { - "url": "/{resourceUri}/providers/microsoft.insights/guestDiagnosticSettingsAssociation/{associationName}" - } - @distributed_trace_async async def get( self, resource_uri: str, association_name: str, **kwargs: Any @@ -224,13 +216,12 @@ async def get( :type resource_uri: str :param association_name: The name of the diagnostic settings association. Required. :type association_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: GuestDiagnosticSettingsAssociationResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_06_01_preview.models.GuestDiagnosticSettingsAssociationResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -241,23 +232,23 @@ async def get( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2018-06-01-preview") + ) cls: ClsType[_models.GuestDiagnosticSettingsAssociationResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_uri=resource_uri, association_name=association_name, api_version=api_version, - template_url=self.get.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -267,21 +258,15 @@ async def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("GuestDiagnosticSettingsAssociationResource", pipeline_response) + deserialized = self._deserialize("GuestDiagnosticSettingsAssociationResource", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get.metadata = { - "url": "/{resourceUri}/providers/microsoft.insights/guestDiagnosticSettingsAssociation/{associationName}" - } + return deserialized # type: ignore @distributed_trace_async - async def delete( # pylint: disable=inconsistent-return-statements - self, resource_uri: str, association_name: str, **kwargs: Any - ) -> None: + async def delete(self, resource_uri: str, association_name: str, **kwargs: Any) -> None: """Delete guest diagnostics association settings. :param resource_uri: The fully qualified ID of the resource, including the resource name and @@ -289,12 +274,11 @@ async def delete( # pylint: disable=inconsistent-return-statements :type resource_uri: str :param association_name: The name of the diagnostic settings association. Required. :type association_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, @@ -305,23 +289,23 @@ async def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2018-06-01-preview") + ) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_uri=resource_uri, association_name=association_name, api_version=api_version, - template_url=self.delete.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -332,11 +316,7 @@ async def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/{resourceUri}/providers/microsoft.insights/guestDiagnosticSettingsAssociation/{associationName}" - } + return cls(pipeline_response, None, {}) # type: ignore @overload async def update( @@ -362,7 +342,6 @@ async def update( :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: GuestDiagnosticSettingsAssociationResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_06_01_preview.models.GuestDiagnosticSettingsAssociationResource @@ -374,7 +353,7 @@ async def update( self, resource_uri: str, association_name: str, - parameters: IO, + parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -388,11 +367,10 @@ async def update( :param association_name: The name of the diagnostic settings association. Required. :type association_name: str :param parameters: Parameters supplied to the operation. Required. - :type parameters: IO + :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: GuestDiagnosticSettingsAssociationResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_06_01_preview.models.GuestDiagnosticSettingsAssociationResource @@ -404,7 +382,7 @@ async def update( self, resource_uri: str, association_name: str, - parameters: Union[_models.GuestDiagnosticSettingsAssociationResourcePatch, IO], + parameters: Union[_models.GuestDiagnosticSettingsAssociationResourcePatch, IO[bytes]], **kwargs: Any ) -> _models.GuestDiagnosticSettingsAssociationResource: """Updates an existing guestDiagnosticsSettingsAssociation Resource. To update other fields use @@ -416,20 +394,16 @@ async def update( :param association_name: The name of the diagnostic settings association. Required. :type association_name: str :param parameters: Parameters supplied to the operation. Is either a - GuestDiagnosticSettingsAssociationResourcePatch type or a IO type. Required. + GuestDiagnosticSettingsAssociationResourcePatch type or a IO[bytes] type. Required. :type parameters: ~azure.mgmt.monitor.v2018_06_01_preview.models.GuestDiagnosticSettingsAssociationResourcePatch - 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 + or IO[bytes] :return: GuestDiagnosticSettingsAssociationResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_06_01_preview.models.GuestDiagnosticSettingsAssociationResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -440,35 +414,35 @@ async def update( _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", "2018-06-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2018-06-01-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.GuestDiagnosticSettingsAssociationResource] = 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, "GuestDiagnosticSettingsAssociationResourcePatch") - request = build_update_request( + _request = build_update_request( resource_uri=resource_uri, association_name=association_name, 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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -478,22 +452,18 @@ async def update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("GuestDiagnosticSettingsAssociationResource", pipeline_response) + deserialized = self._deserialize("GuestDiagnosticSettingsAssociationResource", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - update.metadata = { - "url": "/{resourceUri}/providers/microsoft.insights/guestDiagnosticSettingsAssociation/{associationName}" - } + return deserialized # type: ignore @distributed_trace def list(self, **kwargs: Any) -> AsyncIterable["_models.GuestDiagnosticSettingsAssociationResource"]: + # pylint: disable=line-too-long """Get a list of all guest diagnostic settings association in a subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either GuestDiagnosticSettingsAssociationResource or the result of cls(response) :rtype: @@ -503,10 +473,12 @@ def list(self, **kwargs: Any) -> AsyncIterable["_models.GuestDiagnosticSettingsA _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2018-06-01-preview") + ) cls: ClsType[_models.GuestDiagnosticSettingsAssociationList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -517,15 +489,13 @@ def list(self, **kwargs: Any) -> AsyncIterable["_models.GuestDiagnosticSettingsA def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _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) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -536,14 +506,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("GuestDiagnosticSettingsAssociationList", pipeline_response) @@ -553,11 +522,11 @@ async def extract_data(pipeline_response): return None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -570,20 +539,16 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/microsoft.insights/guestDiagnosticSettingsAssociations" - } - @distributed_trace def list_by_resource_group( self, resource_group_name: str, **kwargs: Any ) -> AsyncIterable["_models.GuestDiagnosticSettingsAssociationResource"]: + # pylint: disable=line-too-long """Get a list of all guest diagnostic settings association in a resource group. :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either GuestDiagnosticSettingsAssociationResource or the result of cls(response) :rtype: @@ -593,10 +558,12 @@ def list_by_resource_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2018-06-01-preview") + ) cls: ClsType[_models.GuestDiagnosticSettingsAssociationList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -607,16 +574,14 @@ 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_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -627,14 +592,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("GuestDiagnosticSettingsAssociationList", pipeline_response) @@ -644,11 +608,11 @@ async def extract_data(pipeline_response): return None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -660,7 +624,3 @@ async def get_next(next_link=None): return pipeline_response return AsyncItemPaged(get_next, extract_data) - - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/guestDiagnosticSettingsAssociations" - } diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_06_01_preview/aio/operations/_guest_diagnostics_settings_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_06_01_preview/aio/operations/_guest_diagnostics_settings_operations.py index 8096714e84e2..48b878181694 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_06_01_preview/aio/operations/_guest_diagnostics_settings_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_06_01_preview/aio/operations/_guest_diagnostics_settings_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload import urllib.parse @@ -19,15 +20,13 @@ 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 ...operations._guest_diagnostics_settings_operations import ( build_create_or_update_request, build_delete_request, @@ -37,6 +36,10 @@ build_update_request, ) +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -59,6 +62,7 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @overload async def create_or_update( @@ -83,7 +87,6 @@ async def create_or_update( :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: GuestDiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_06_01_preview.models.GuestDiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: @@ -94,7 +97,7 @@ async def create_or_update( self, resource_group_name: str, diagnostic_settings_name: str, - diagnostic_settings: IO, + diagnostic_settings: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -107,11 +110,10 @@ async def create_or_update( :param diagnostic_settings_name: The name of the diagnostic setting. Required. :type diagnostic_settings_name: str :param diagnostic_settings: The configuration to create or update. Required. - :type diagnostic_settings: IO + :type diagnostic_settings: 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: GuestDiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_06_01_preview.models.GuestDiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: @@ -122,7 +124,7 @@ async def create_or_update( self, resource_group_name: str, diagnostic_settings_name: str, - diagnostic_settings: Union[_models.GuestDiagnosticSettingsResource, IO], + diagnostic_settings: Union[_models.GuestDiagnosticSettingsResource, IO[bytes]], **kwargs: Any ) -> _models.GuestDiagnosticSettingsResource: """Creates or updates guest diagnostics settings. @@ -133,18 +135,14 @@ async def create_or_update( :param diagnostic_settings_name: The name of the diagnostic setting. Required. :type diagnostic_settings_name: str :param diagnostic_settings: The configuration to create or update. Is either a - GuestDiagnosticSettingsResource type or a IO type. Required. + GuestDiagnosticSettingsResource type or a IO[bytes] type. Required. :type diagnostic_settings: - ~azure.mgmt.monitor.v2018_06_01_preview.models.GuestDiagnosticSettingsResource 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 + ~azure.mgmt.monitor.v2018_06_01_preview.models.GuestDiagnosticSettingsResource or IO[bytes] :return: GuestDiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_06_01_preview.models.GuestDiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -155,19 +153,21 @@ async def create_or_update( _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", "2018-06-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2018-06-01-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.GuestDiagnosticSettingsResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(diagnostic_settings, (IO, bytes)): + if isinstance(diagnostic_settings, (IOBase, bytes)): _content = diagnostic_settings else: _json = self._serialize.body(diagnostic_settings, "GuestDiagnosticSettingsResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, diagnostic_settings_name=diagnostic_settings_name, subscription_id=self._config.subscription_id, @@ -175,16 +175,14 @@ async def create_or_update( 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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -194,21 +192,13 @@ async def create_or_update( 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("GuestDiagnosticSettingsResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("GuestDiagnosticSettingsResource", pipeline_response) + deserialized = self._deserialize("GuestDiagnosticSettingsResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/microsoft.insights/guestDiagnosticSettings/{diagnosticSettingsName}" - } - @distributed_trace_async async def get( self, resource_group_name: str, diagnostic_settings_name: str, **kwargs: Any @@ -220,12 +210,11 @@ async def get( :type resource_group_name: str :param diagnostic_settings_name: The name of the diagnostic setting. Required. :type diagnostic_settings_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: GuestDiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_06_01_preview.models.GuestDiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -236,24 +225,24 @@ async def get( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2018-06-01-preview") + ) cls: ClsType[_models.GuestDiagnosticSettingsResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, diagnostic_settings_name=diagnostic_settings_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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -263,16 +252,12 @@ async def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("GuestDiagnosticSettingsResource", pipeline_response) + deserialized = self._deserialize("GuestDiagnosticSettingsResource", 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.insights/guestDiagnosticSettings/{diagnosticSettingsName}" - } + return deserialized # type: ignore @overload async def update( @@ -297,7 +282,6 @@ async def update( :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: GuestDiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_06_01_preview.models.GuestDiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: @@ -308,7 +292,7 @@ async def update( self, resource_group_name: str, diagnostic_settings_name: str, - parameters: IO, + parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -321,11 +305,10 @@ async def update( :param diagnostic_settings_name: The name of the diagnostic setting. Required. :type diagnostic_settings_name: str :param parameters: The configuration to patch. Required. - :type parameters: IO + :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: GuestDiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_06_01_preview.models.GuestDiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: @@ -336,7 +319,7 @@ async def update( self, resource_group_name: str, diagnostic_settings_name: str, - parameters: Union[_models.GuestDiagnosticSettingsPatchResource, IO], + parameters: Union[_models.GuestDiagnosticSettingsPatchResource, IO[bytes]], **kwargs: Any ) -> _models.GuestDiagnosticSettingsResource: """Updates guest diagnostics settings. @@ -347,18 +330,15 @@ async def update( :param diagnostic_settings_name: The name of the diagnostic setting. Required. :type diagnostic_settings_name: str :param parameters: The configuration to patch. Is either a GuestDiagnosticSettingsPatchResource - type or a IO type. Required. + type or a IO[bytes] type. Required. :type parameters: - ~azure.mgmt.monitor.v2018_06_01_preview.models.GuestDiagnosticSettingsPatchResource 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 + ~azure.mgmt.monitor.v2018_06_01_preview.models.GuestDiagnosticSettingsPatchResource or + IO[bytes] :return: GuestDiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_06_01_preview.models.GuestDiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -369,19 +349,21 @@ async def update( _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", "2018-06-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2018-06-01-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.GuestDiagnosticSettingsResource] = 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, "GuestDiagnosticSettingsPatchResource") - request = build_update_request( + _request = build_update_request( resource_group_name=resource_group_name, diagnostic_settings_name=diagnostic_settings_name, subscription_id=self._config.subscription_id, @@ -389,16 +371,14 @@ async def update( 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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -408,25 +388,15 @@ async def update( 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("GuestDiagnosticSettingsResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("GuestDiagnosticSettingsResource", pipeline_response) + deserialized = self._deserialize("GuestDiagnosticSettingsResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/microsoft.insights/guestDiagnosticSettings/{diagnosticSettingsName}" - } - @distributed_trace_async - async def delete( # pylint: disable=inconsistent-return-statements - self, resource_group_name: str, diagnostic_settings_name: str, **kwargs: Any - ) -> None: + async def delete(self, resource_group_name: str, diagnostic_settings_name: str, **kwargs: Any) -> None: """Delete guest diagnostics settings. :param resource_group_name: The name of the resource group. The name is case insensitive. @@ -434,12 +404,11 @@ async def delete( # pylint: disable=inconsistent-return-statements :type resource_group_name: str :param diagnostic_settings_name: The name of the diagnostic setting. Required. :type diagnostic_settings_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, @@ -450,24 +419,24 @@ async def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2018-06-01-preview") + ) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, diagnostic_settings_name=diagnostic_settings_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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -478,17 +447,13 @@ async def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/microsoft.insights/guestDiagnosticSettings/{diagnosticSettingsName}" - } + return cls(pipeline_response, None, {}) # type: ignore @distributed_trace def list(self, **kwargs: Any) -> AsyncIterable["_models.GuestDiagnosticSettingsResource"]: + # pylint: disable=line-too-long """Get a list of all guest diagnostic settings in a subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either GuestDiagnosticSettingsResource or the result of cls(response) :rtype: @@ -498,10 +463,12 @@ def list(self, **kwargs: Any) -> AsyncIterable["_models.GuestDiagnosticSettingsR _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2018-06-01-preview") + ) cls: ClsType[_models.GuestDiagnosticSettingsList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -512,15 +479,13 @@ def list(self, **kwargs: Any) -> AsyncIterable["_models.GuestDiagnosticSettingsR def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _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) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -531,14 +496,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("GuestDiagnosticSettingsList", pipeline_response) @@ -548,11 +512,11 @@ async def extract_data(pipeline_response): return None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -565,18 +529,16 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/microsoft.insights/guestDiagnosticSettings"} - @distributed_trace def list_by_resource_group( self, resource_group_name: str, **kwargs: Any ) -> AsyncIterable["_models.GuestDiagnosticSettingsResource"]: + # pylint: disable=line-too-long """Get a list of all guest diagnostic settings in a resource group. :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either GuestDiagnosticSettingsResource or the result of cls(response) :rtype: @@ -586,10 +548,12 @@ def list_by_resource_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2018-06-01-preview") + ) cls: ClsType[_models.GuestDiagnosticSettingsList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -600,16 +564,14 @@ 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_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -620,14 +582,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("GuestDiagnosticSettingsList", pipeline_response) @@ -637,11 +598,11 @@ async def extract_data(pipeline_response): return None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -653,7 +614,3 @@ async def get_next(next_link=None): return pipeline_response return AsyncItemPaged(get_next, extract_data) - - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/guestDiagnosticSettings" - } diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_06_01_preview/models/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_06_01_preview/models/__init__.py index 4fa4abe4c38f..de9f4b599f20 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_06_01_preview/models/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_06_01_preview/models/__init__.py @@ -5,28 +5,39 @@ # 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 DataSource -from ._models_py3 import DataSourceConfiguration -from ._models_py3 import ErrorResponse -from ._models_py3 import EtwEventConfiguration -from ._models_py3 import EtwProviderConfiguration -from ._models_py3 import EventLogConfiguration -from ._models_py3 import GuestDiagnosticSettingsAssociationList -from ._models_py3 import GuestDiagnosticSettingsAssociationResource -from ._models_py3 import GuestDiagnosticSettingsAssociationResourcePatch -from ._models_py3 import GuestDiagnosticSettingsList -from ._models_py3 import GuestDiagnosticSettingsPatchResource -from ._models_py3 import GuestDiagnosticSettingsResource -from ._models_py3 import PerformanceCounterConfiguration -from ._models_py3 import Resource -from ._models_py3 import SinkConfiguration +from typing import TYPE_CHECKING -from ._monitor_management_client_enums import DataSourceKind -from ._monitor_management_client_enums import GuestDiagnosticSettingsOsType -from ._monitor_management_client_enums import SinkConfigurationKind +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models_py3 import ( # type: ignore + DataSource, + DataSourceConfiguration, + ErrorResponse, + EtwEventConfiguration, + EtwProviderConfiguration, + EventLogConfiguration, + GuestDiagnosticSettingsAssociationList, + GuestDiagnosticSettingsAssociationResource, + GuestDiagnosticSettingsAssociationResourcePatch, + GuestDiagnosticSettingsList, + GuestDiagnosticSettingsPatchResource, + GuestDiagnosticSettingsResource, + PerformanceCounterConfiguration, + Resource, + SinkConfiguration, +) + +from ._monitor_management_client_enums import ( # type: ignore + DataSourceKind, + GuestDiagnosticSettingsOsType, + SinkConfigurationKind, +) from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ @@ -49,5 +60,5 @@ "GuestDiagnosticSettingsOsType", "SinkConfigurationKind", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_06_01_preview/models/_models_py3.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_06_01_preview/models/_models_py3.py index afe945cc42d1..73cafb330d33 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_06_01_preview/models/_models_py3.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_06_01_preview/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. @@ -12,7 +11,6 @@ from ... import _serialization if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from .. import models as _models @@ -20,7 +18,7 @@ class DataSource(_serialization.Model): """Data source object contains configuration to collect telemetry and one or more sinks to send that telemetry data to. - 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 kind: Datasource kind. Required. Known values are: "PerformanceCounter", "ETWProviders", and "WindowsEventLogs". @@ -140,7 +138,7 @@ def __init__(self, *, code: Optional[str] = None, message: Optional[str] = None, class EtwEventConfiguration(_serialization.Model): """EtwEventConfiguration. - 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: Required. :vartype name: str @@ -186,7 +184,7 @@ def __init__( class EtwProviderConfiguration(_serialization.Model): """EtwProviderConfiguration. - 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: Required. :vartype id: str @@ -225,7 +223,7 @@ def __init__( class EventLogConfiguration(_serialization.Model): """EventLogConfiguration. - 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 log_name: Required. :vartype log_name: str @@ -295,7 +293,7 @@ class Resource(_serialization.Model): 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: Azure resource Id. :vartype id: str @@ -339,12 +337,12 @@ def __init__(self, *, location: str, tags: Optional[Dict[str, str]] = None, **kw self.tags = tags -class GuestDiagnosticSettingsAssociationResource(Resource): +class GuestDiagnosticSettingsAssociationResource(Resource): # pylint: disable=name-too-long """Virtual machine guest diagnostic settings 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: Azure resource Id. :vartype id: str @@ -397,7 +395,7 @@ def __init__( self.guest_diagnostic_settings_name = guest_diagnostic_settings_name -class GuestDiagnosticSettingsAssociationResourcePatch(_serialization.Model): +class GuestDiagnosticSettingsAssociationResourcePatch(_serialization.Model): # pylint: disable=name-too-long """Guest diagnostic setting resource for patch operations. :ivar tags: Resource tags. @@ -520,7 +518,7 @@ class GuestDiagnosticSettingsResource(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: Azure resource Id. :vartype id: str @@ -595,7 +593,7 @@ def __init__( class PerformanceCounterConfiguration(_serialization.Model): """PerformanceCounterConfiguration. - 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: Required. :vartype name: str @@ -634,7 +632,7 @@ def __init__(self, *, name: str, sampling_period: str, instance: Optional[str] = class SinkConfiguration(_serialization.Model): """SinkConfiguration. - 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 kind: Required. Known values are: "EventHub", "ApplicationInsights", and "LogAnalytics". :vartype kind: str or ~azure.mgmt.monitor.v2018_06_01_preview.models.SinkConfigurationKind diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_06_01_preview/operations/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_06_01_preview/operations/__init__.py index 2f4965e07c4c..402790b802c9 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_06_01_preview/operations/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_06_01_preview/operations/__init__.py @@ -5,17 +5,23 @@ # 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 ._guest_diagnostics_settings_association_operations import GuestDiagnosticsSettingsAssociationOperations -from ._guest_diagnostics_settings_operations import GuestDiagnosticsSettingsOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._guest_diagnostics_settings_association_operations import GuestDiagnosticsSettingsAssociationOperations # type: ignore +from ._guest_diagnostics_settings_operations import GuestDiagnosticsSettingsOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ "GuestDiagnosticsSettingsAssociationOperations", "GuestDiagnosticsSettingsOperations", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_06_01_preview/operations/_guest_diagnostics_settings_association_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_06_01_preview/operations/_guest_diagnostics_settings_association_operations.py index ca480b1c92cd..47ba8f1de02a 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_06_01_preview/operations/_guest_diagnostics_settings_association_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_06_01_preview/operations/_guest_diagnostics_settings_association_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload import urllib.parse @@ -19,16 +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, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -54,7 +57,7 @@ def build_create_or_update_request(resource_uri: str, association_name: str, **k "associationName": _SERIALIZER.url("association_name", association_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -84,7 +87,7 @@ def build_get_request(resource_uri: str, association_name: str, **kwargs: Any) - "associationName": _SERIALIZER.url("association_name", association_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -112,7 +115,7 @@ def build_delete_request(resource_uri: str, association_name: str, **kwargs: Any "associationName": _SERIALIZER.url("association_name", association_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -141,7 +144,7 @@ def build_update_request(resource_uri: str, association_name: str, **kwargs: Any "associationName": _SERIALIZER.url("association_name", association_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -170,7 +173,7 @@ def build_list_request(subscription_id: str, **kwargs: Any) -> HttpRequest: "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -200,7 +203,7 @@ def build_list_by_resource_group_request(resource_group_name: str, subscription_ "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -211,7 +214,7 @@ def build_list_by_resource_group_request(resource_group_name: str, subscription_ return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -class GuestDiagnosticsSettingsAssociationOperations: +class GuestDiagnosticsSettingsAssociationOperations: # pylint: disable=name-too-long """ .. warning:: **DO NOT** instantiate this class directly. @@ -229,6 +232,7 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @overload def create_or_update( @@ -254,7 +258,6 @@ def create_or_update( :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: GuestDiagnosticSettingsAssociationResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_06_01_preview.models.GuestDiagnosticSettingsAssociationResource @@ -266,7 +269,7 @@ def create_or_update( self, resource_uri: str, association_name: str, - diagnostic_settings_association: IO, + diagnostic_settings_association: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -280,11 +283,10 @@ def create_or_update( :type association_name: str :param diagnostic_settings_association: The diagnostic settings association to create or update. Required. - :type diagnostic_settings_association: IO + :type diagnostic_settings_association: 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: GuestDiagnosticSettingsAssociationResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_06_01_preview.models.GuestDiagnosticSettingsAssociationResource @@ -296,7 +298,7 @@ def create_or_update( self, resource_uri: str, association_name: str, - diagnostic_settings_association: Union[_models.GuestDiagnosticSettingsAssociationResource, IO], + diagnostic_settings_association: Union[_models.GuestDiagnosticSettingsAssociationResource, IO[bytes]], **kwargs: Any ) -> _models.GuestDiagnosticSettingsAssociationResource: """Creates or updates guest diagnostics settings association. @@ -307,19 +309,17 @@ def create_or_update( :param association_name: The name of the diagnostic settings association. Required. :type association_name: str :param diagnostic_settings_association: The diagnostic settings association to create or - update. Is either a GuestDiagnosticSettingsAssociationResource type or a IO type. Required. + update. Is either a GuestDiagnosticSettingsAssociationResource type or a IO[bytes] type. + Required. :type diagnostic_settings_association: - ~azure.mgmt.monitor.v2018_06_01_preview.models.GuestDiagnosticSettingsAssociationResource 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 + ~azure.mgmt.monitor.v2018_06_01_preview.models.GuestDiagnosticSettingsAssociationResource or + IO[bytes] :return: GuestDiagnosticSettingsAssociationResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_06_01_preview.models.GuestDiagnosticSettingsAssociationResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -330,35 +330,35 @@ def create_or_update( _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", "2018-06-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2018-06-01-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.GuestDiagnosticSettingsAssociationResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(diagnostic_settings_association, (IO, bytes)): + if isinstance(diagnostic_settings_association, (IOBase, bytes)): _content = diagnostic_settings_association else: _json = self._serialize.body(diagnostic_settings_association, "GuestDiagnosticSettingsAssociationResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_uri=resource_uri, association_name=association_name, 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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -368,21 +368,13 @@ def create_or_update( 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("GuestDiagnosticSettingsAssociationResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("GuestDiagnosticSettingsAssociationResource", pipeline_response) + deserialized = self._deserialize("GuestDiagnosticSettingsAssociationResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create_or_update.metadata = { - "url": "/{resourceUri}/providers/microsoft.insights/guestDiagnosticSettingsAssociation/{associationName}" - } - @distributed_trace def get( self, resource_uri: str, association_name: str, **kwargs: Any @@ -394,13 +386,12 @@ def get( :type resource_uri: str :param association_name: The name of the diagnostic settings association. Required. :type association_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: GuestDiagnosticSettingsAssociationResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_06_01_preview.models.GuestDiagnosticSettingsAssociationResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -411,23 +402,23 @@ def get( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2018-06-01-preview") + ) cls: ClsType[_models.GuestDiagnosticSettingsAssociationResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_uri=resource_uri, association_name=association_name, api_version=api_version, - template_url=self.get.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -437,16 +428,12 @@ def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("GuestDiagnosticSettingsAssociationResource", pipeline_response) + deserialized = self._deserialize("GuestDiagnosticSettingsAssociationResource", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get.metadata = { - "url": "/{resourceUri}/providers/microsoft.insights/guestDiagnosticSettingsAssociation/{associationName}" - } + return deserialized # type: ignore @distributed_trace def delete( # pylint: disable=inconsistent-return-statements @@ -459,12 +446,11 @@ def delete( # pylint: disable=inconsistent-return-statements :type resource_uri: str :param association_name: The name of the diagnostic settings association. Required. :type association_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, @@ -475,23 +461,23 @@ def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2018-06-01-preview") + ) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_uri=resource_uri, association_name=association_name, api_version=api_version, - template_url=self.delete.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -502,11 +488,7 @@ def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/{resourceUri}/providers/microsoft.insights/guestDiagnosticSettingsAssociation/{associationName}" - } + return cls(pipeline_response, None, {}) # type: ignore @overload def update( @@ -532,7 +514,6 @@ def update( :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: GuestDiagnosticSettingsAssociationResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_06_01_preview.models.GuestDiagnosticSettingsAssociationResource @@ -544,7 +525,7 @@ def update( self, resource_uri: str, association_name: str, - parameters: IO, + parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -558,11 +539,10 @@ def update( :param association_name: The name of the diagnostic settings association. Required. :type association_name: str :param parameters: Parameters supplied to the operation. Required. - :type parameters: IO + :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: GuestDiagnosticSettingsAssociationResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_06_01_preview.models.GuestDiagnosticSettingsAssociationResource @@ -574,7 +554,7 @@ def update( self, resource_uri: str, association_name: str, - parameters: Union[_models.GuestDiagnosticSettingsAssociationResourcePatch, IO], + parameters: Union[_models.GuestDiagnosticSettingsAssociationResourcePatch, IO[bytes]], **kwargs: Any ) -> _models.GuestDiagnosticSettingsAssociationResource: """Updates an existing guestDiagnosticsSettingsAssociation Resource. To update other fields use @@ -586,20 +566,16 @@ def update( :param association_name: The name of the diagnostic settings association. Required. :type association_name: str :param parameters: Parameters supplied to the operation. Is either a - GuestDiagnosticSettingsAssociationResourcePatch type or a IO type. Required. + GuestDiagnosticSettingsAssociationResourcePatch type or a IO[bytes] type. Required. :type parameters: ~azure.mgmt.monitor.v2018_06_01_preview.models.GuestDiagnosticSettingsAssociationResourcePatch - 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 + or IO[bytes] :return: GuestDiagnosticSettingsAssociationResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_06_01_preview.models.GuestDiagnosticSettingsAssociationResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -610,35 +586,35 @@ def update( _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", "2018-06-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2018-06-01-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.GuestDiagnosticSettingsAssociationResource] = 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, "GuestDiagnosticSettingsAssociationResourcePatch") - request = build_update_request( + _request = build_update_request( resource_uri=resource_uri, association_name=association_name, 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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -648,22 +624,18 @@ def update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("GuestDiagnosticSettingsAssociationResource", pipeline_response) + deserialized = self._deserialize("GuestDiagnosticSettingsAssociationResource", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - update.metadata = { - "url": "/{resourceUri}/providers/microsoft.insights/guestDiagnosticSettingsAssociation/{associationName}" - } + return deserialized # type: ignore @distributed_trace def list(self, **kwargs: Any) -> Iterable["_models.GuestDiagnosticSettingsAssociationResource"]: + # pylint: disable=line-too-long """Get a list of all guest diagnostic settings association in a subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either GuestDiagnosticSettingsAssociationResource or the result of cls(response) :rtype: @@ -673,10 +645,12 @@ def list(self, **kwargs: Any) -> Iterable["_models.GuestDiagnosticSettingsAssoci _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2018-06-01-preview") + ) cls: ClsType[_models.GuestDiagnosticSettingsAssociationList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -687,15 +661,13 @@ def list(self, **kwargs: Any) -> Iterable["_models.GuestDiagnosticSettingsAssoci def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _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) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -706,14 +678,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("GuestDiagnosticSettingsAssociationList", pipeline_response) @@ -723,11 +694,11 @@ def extract_data(pipeline_response): return None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -740,20 +711,16 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/microsoft.insights/guestDiagnosticSettingsAssociations" - } - @distributed_trace def list_by_resource_group( self, resource_group_name: str, **kwargs: Any ) -> Iterable["_models.GuestDiagnosticSettingsAssociationResource"]: + # pylint: disable=line-too-long """Get a list of all guest diagnostic settings association in a resource group. :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either GuestDiagnosticSettingsAssociationResource or the result of cls(response) :rtype: @@ -763,10 +730,12 @@ def list_by_resource_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2018-06-01-preview") + ) cls: ClsType[_models.GuestDiagnosticSettingsAssociationList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -777,16 +746,14 @@ 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_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -797,14 +764,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("GuestDiagnosticSettingsAssociationList", pipeline_response) @@ -814,11 +780,11 @@ def extract_data(pipeline_response): return None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -830,7 +796,3 @@ def get_next(next_link=None): return pipeline_response return ItemPaged(get_next, extract_data) - - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/guestDiagnosticSettingsAssociations" - } diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_06_01_preview/operations/_guest_diagnostics_settings_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_06_01_preview/operations/_guest_diagnostics_settings_operations.py index c27ec6eebc81..cab437f27c9d 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_06_01_preview/operations/_guest_diagnostics_settings_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_06_01_preview/operations/_guest_diagnostics_settings_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload import urllib.parse @@ -19,16 +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, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -59,7 +62,7 @@ def build_create_or_update_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -94,7 +97,7 @@ def build_get_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -128,7 +131,7 @@ def build_update_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -163,7 +166,7 @@ def build_delete_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -189,7 +192,7 @@ def build_list_request(subscription_id: str, **kwargs: Any) -> HttpRequest: "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -219,7 +222,7 @@ def build_list_by_resource_group_request(resource_group_name: str, subscription_ "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -248,6 +251,7 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @overload def create_or_update( @@ -272,7 +276,6 @@ def create_or_update( :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: GuestDiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_06_01_preview.models.GuestDiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: @@ -283,7 +286,7 @@ def create_or_update( self, resource_group_name: str, diagnostic_settings_name: str, - diagnostic_settings: IO, + diagnostic_settings: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -296,11 +299,10 @@ def create_or_update( :param diagnostic_settings_name: The name of the diagnostic setting. Required. :type diagnostic_settings_name: str :param diagnostic_settings: The configuration to create or update. Required. - :type diagnostic_settings: IO + :type diagnostic_settings: 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: GuestDiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_06_01_preview.models.GuestDiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: @@ -311,7 +313,7 @@ def create_or_update( self, resource_group_name: str, diagnostic_settings_name: str, - diagnostic_settings: Union[_models.GuestDiagnosticSettingsResource, IO], + diagnostic_settings: Union[_models.GuestDiagnosticSettingsResource, IO[bytes]], **kwargs: Any ) -> _models.GuestDiagnosticSettingsResource: """Creates or updates guest diagnostics settings. @@ -322,18 +324,14 @@ def create_or_update( :param diagnostic_settings_name: The name of the diagnostic setting. Required. :type diagnostic_settings_name: str :param diagnostic_settings: The configuration to create or update. Is either a - GuestDiagnosticSettingsResource type or a IO type. Required. + GuestDiagnosticSettingsResource type or a IO[bytes] type. Required. :type diagnostic_settings: - ~azure.mgmt.monitor.v2018_06_01_preview.models.GuestDiagnosticSettingsResource 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 + ~azure.mgmt.monitor.v2018_06_01_preview.models.GuestDiagnosticSettingsResource or IO[bytes] :return: GuestDiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_06_01_preview.models.GuestDiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -344,19 +342,21 @@ def create_or_update( _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", "2018-06-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2018-06-01-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.GuestDiagnosticSettingsResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(diagnostic_settings, (IO, bytes)): + if isinstance(diagnostic_settings, (IOBase, bytes)): _content = diagnostic_settings else: _json = self._serialize.body(diagnostic_settings, "GuestDiagnosticSettingsResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, diagnostic_settings_name=diagnostic_settings_name, subscription_id=self._config.subscription_id, @@ -364,16 +364,14 @@ def create_or_update( 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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -383,21 +381,13 @@ def create_or_update( 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("GuestDiagnosticSettingsResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("GuestDiagnosticSettingsResource", pipeline_response) + deserialized = self._deserialize("GuestDiagnosticSettingsResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/microsoft.insights/guestDiagnosticSettings/{diagnosticSettingsName}" - } - @distributed_trace def get( self, resource_group_name: str, diagnostic_settings_name: str, **kwargs: Any @@ -409,12 +399,11 @@ def get( :type resource_group_name: str :param diagnostic_settings_name: The name of the diagnostic setting. Required. :type diagnostic_settings_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: GuestDiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_06_01_preview.models.GuestDiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -425,24 +414,24 @@ def get( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2018-06-01-preview") + ) cls: ClsType[_models.GuestDiagnosticSettingsResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, diagnostic_settings_name=diagnostic_settings_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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -452,16 +441,12 @@ def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("GuestDiagnosticSettingsResource", pipeline_response) + deserialized = self._deserialize("GuestDiagnosticSettingsResource", 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.insights/guestDiagnosticSettings/{diagnosticSettingsName}" - } + return deserialized # type: ignore @overload def update( @@ -486,7 +471,6 @@ def update( :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: GuestDiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_06_01_preview.models.GuestDiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: @@ -497,7 +481,7 @@ def update( self, resource_group_name: str, diagnostic_settings_name: str, - parameters: IO, + parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -510,11 +494,10 @@ def update( :param diagnostic_settings_name: The name of the diagnostic setting. Required. :type diagnostic_settings_name: str :param parameters: The configuration to patch. Required. - :type parameters: IO + :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: GuestDiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_06_01_preview.models.GuestDiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: @@ -525,7 +508,7 @@ def update( self, resource_group_name: str, diagnostic_settings_name: str, - parameters: Union[_models.GuestDiagnosticSettingsPatchResource, IO], + parameters: Union[_models.GuestDiagnosticSettingsPatchResource, IO[bytes]], **kwargs: Any ) -> _models.GuestDiagnosticSettingsResource: """Updates guest diagnostics settings. @@ -536,18 +519,15 @@ def update( :param diagnostic_settings_name: The name of the diagnostic setting. Required. :type diagnostic_settings_name: str :param parameters: The configuration to patch. Is either a GuestDiagnosticSettingsPatchResource - type or a IO type. Required. + type or a IO[bytes] type. Required. :type parameters: - ~azure.mgmt.monitor.v2018_06_01_preview.models.GuestDiagnosticSettingsPatchResource 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 + ~azure.mgmt.monitor.v2018_06_01_preview.models.GuestDiagnosticSettingsPatchResource or + IO[bytes] :return: GuestDiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_06_01_preview.models.GuestDiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -558,19 +538,21 @@ def update( _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", "2018-06-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2018-06-01-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.GuestDiagnosticSettingsResource] = 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, "GuestDiagnosticSettingsPatchResource") - request = build_update_request( + _request = build_update_request( resource_group_name=resource_group_name, diagnostic_settings_name=diagnostic_settings_name, subscription_id=self._config.subscription_id, @@ -578,16 +560,14 @@ def update( 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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -597,21 +577,13 @@ def update( 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("GuestDiagnosticSettingsResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("GuestDiagnosticSettingsResource", pipeline_response) + deserialized = self._deserialize("GuestDiagnosticSettingsResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/microsoft.insights/guestDiagnosticSettings/{diagnosticSettingsName}" - } - @distributed_trace def delete( # pylint: disable=inconsistent-return-statements self, resource_group_name: str, diagnostic_settings_name: str, **kwargs: Any @@ -623,12 +595,11 @@ def delete( # pylint: disable=inconsistent-return-statements :type resource_group_name: str :param diagnostic_settings_name: The name of the diagnostic setting. Required. :type diagnostic_settings_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, @@ -639,24 +610,24 @@ def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2018-06-01-preview") + ) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, diagnostic_settings_name=diagnostic_settings_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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -667,17 +638,12 @@ def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/microsoft.insights/guestDiagnosticSettings/{diagnosticSettingsName}" - } + return cls(pipeline_response, None, {}) # type: ignore @distributed_trace def list(self, **kwargs: Any) -> Iterable["_models.GuestDiagnosticSettingsResource"]: """Get a list of all guest diagnostic settings in a subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either GuestDiagnosticSettingsResource or the result of cls(response) :rtype: @@ -687,10 +653,12 @@ def list(self, **kwargs: Any) -> Iterable["_models.GuestDiagnosticSettingsResour _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2018-06-01-preview") + ) cls: ClsType[_models.GuestDiagnosticSettingsList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -701,15 +669,13 @@ def list(self, **kwargs: Any) -> Iterable["_models.GuestDiagnosticSettingsResour def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _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) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -720,14 +686,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("GuestDiagnosticSettingsList", pipeline_response) @@ -737,11 +702,11 @@ def extract_data(pipeline_response): return None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -754,8 +719,6 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/microsoft.insights/guestDiagnosticSettings"} - @distributed_trace def list_by_resource_group( self, resource_group_name: str, **kwargs: Any @@ -765,7 +728,6 @@ def list_by_resource_group( :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either GuestDiagnosticSettingsResource or the result of cls(response) :rtype: @@ -775,10 +737,12 @@ def list_by_resource_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2018-06-01-preview") + ) cls: ClsType[_models.GuestDiagnosticSettingsList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -789,16 +753,14 @@ 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_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -809,14 +771,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("GuestDiagnosticSettingsList", pipeline_response) @@ -826,11 +787,11 @@ def extract_data(pipeline_response): return None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -842,7 +803,3 @@ def get_next(next_link=None): return pipeline_response return ItemPaged(get_next, extract_data) - - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/guestDiagnosticSettings" - } diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_09_01/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_09_01/__init__.py index 2c7733bfd566..42cc62301757 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_09_01/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_09_01/__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 ._monitor_management_client import MonitorManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._monitor_management_client import MonitorManagementClient # type: ignore from ._version import VERSION __version__ = VERSION try: from ._patch import __all__ as _patch_all - from ._patch import * # 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__ = [ "MonitorManagementClient", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_09_01/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_09_01/_configuration.py index 20fa7a982473..95fa0f8e1911 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_09_01/_configuration.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_09_01/_configuration.py @@ -8,18 +8,16 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy from ._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MonitorManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class MonitorManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for MonitorManagementClient. Note that all parameters used to create this instance are saved as instance @@ -35,7 +33,6 @@ class MonitorManagementClientConfiguration(Configuration): # pylint: disable=to """ def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: - super(MonitorManagementClientConfiguration, self).__init__(**kwargs) api_version: str = kwargs.pop("api_version", "2018-09-01") if credential is None: @@ -48,6 +45,7 @@ def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-monitor/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -56,9 +54,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.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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_09_01/_metadata.json b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_09_01/_metadata.json index 729ae3d52af8..4aff7c799459 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_09_01/_metadata.json +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_09_01/_metadata.json @@ -8,10 +8,10 @@ "host_value": "\"https://management.azure.com\"", "parameterized_host_template": null, "azure_arm": true, - "has_lro_operations": false, + "has_public_lro_operations": false, "client_side_validation": false, - "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"sdkcore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMAutoResourceProviderRegistrationPolicy\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}, \"stdlib\": {\"typing_extensions\": [\"Self\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"sdkcore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"AsyncARMAutoResourceProviderRegistrationPolicy\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}, \"stdlib\": {\"typing_extensions\": [\"Self\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "global_parameters": { "sync": { @@ -101,8 +101,8 @@ "credential_scopes": ["https://management.azure.com/.default"], "credential_call_sync": "ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", "credential_call_async": "AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", - "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "sync_imports": "{\"regular\": {\"sdkcore\": {\"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"regular\": {\"sdkcore\": {\"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "operation_groups": { "action_groups": "ActionGroupsOperations", diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_09_01/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_09_01/_monitor_management_client.py index b3a942c1f3a3..952edec5f4f0 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_09_01/_monitor_management_client.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_09_01/_monitor_management_client.py @@ -8,9 +8,12 @@ from copy import deepcopy from typing import Any, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient +from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy from . import models as _models from .._serialization import Deserializer, Serializer @@ -18,11 +21,10 @@ from .operations import ActionGroupsOperations, BaselinesOperations if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MonitorManagementClient: # pylint: disable=client-accepts-api-version-keyword +class MonitorManagementClient: """Monitor Management Client. :ivar action_groups: ActionGroupsOperations operations @@ -50,16 +52,38 @@ def __init__( self._config = MonitorManagementClientConfiguration( credential=credential, subscription_id=subscription_id, **kwargs ) - self._client: ARMPipelineClient = ARMPipelineClient(base_url=base_url, config=self._config, **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), + 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=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.action_groups = ActionGroupsOperations(self._client, self._config, self._serialize, self._deserialize) - self.baselines = BaselinesOperations(self._client, self._config, self._serialize, self._deserialize) + self.action_groups = ActionGroupsOperations( + self._client, self._config, self._serialize, self._deserialize, "2018-09-01" + ) + self.baselines = BaselinesOperations( + self._client, self._config, self._serialize, self._deserialize, "2018-09-01" + ) - 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 @@ -79,12 +103,12 @@ 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) -> None: self._client.close() - def __enter__(self) -> "MonitorManagementClient": + def __enter__(self) -> Self: self._client.__enter__() return self diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_09_01/_vendor.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_09_01/_vendor.py deleted file mode 100644 index bd0df84f5319..000000000000 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_09_01/_vendor.py +++ /dev/null @@ -1,30 +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 typing import List, cast - -from azure.core.pipeline.transport import HttpRequest - - -def _convert_request(request, files=None): - data = request.content if not files else None - request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) - if files: - request.set_formdata_body(files) - return request - - -def _format_url_section(template, **kwargs): - components = template.split("/") - while components: - try: - return template.format(**kwargs) - except KeyError as key: - # Need the cast, as for some reasons "split" is typed as list[str | Any] - formatted_components = cast(List[str], template.split("/")) - components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] - template = "/".join(components) diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_09_01/_version.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_09_01/_version.py index 394ee7c0c03c..e5754a47ce68 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_09_01/_version.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_09_01/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "6.0.2" +VERSION = "1.0.0b1" diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_09_01/aio/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_09_01/aio/__init__.py index 2c151bb41c19..3df30ff42149 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_09_01/aio/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_09_01/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 ._monitor_management_client import MonitorManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._monitor_management_client import MonitorManagementClient # type: ignore try: from ._patch import __all__ as _patch_all - from ._patch import * # 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__ = [ "MonitorManagementClient", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_09_01/aio/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_09_01/aio/_configuration.py index a71fe19692e2..f4d9be2a1793 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_09_01/aio/_configuration.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_09_01/aio/_configuration.py @@ -8,18 +8,16 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy from .._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MonitorManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class MonitorManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for MonitorManagementClient. Note that all parameters used to create this instance are saved as instance @@ -35,7 +33,6 @@ class MonitorManagementClientConfiguration(Configuration): # pylint: disable=to """ def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: - super(MonitorManagementClientConfiguration, self).__init__(**kwargs) api_version: str = kwargs.pop("api_version", "2018-09-01") if credential is None: @@ -48,6 +45,7 @@ def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **k self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-monitor/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -56,9 +54,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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_09_01/aio/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_09_01/aio/_monitor_management_client.py index 8046bc9f7c14..b9048318cf04 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_09_01/aio/_monitor_management_client.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_09_01/aio/_monitor_management_client.py @@ -8,9 +8,12 @@ from copy import deepcopy from typing import Any, Awaitable, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient +from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy from .. import models as _models from ..._serialization import Deserializer, Serializer @@ -18,11 +21,10 @@ from .operations import ActionGroupsOperations, BaselinesOperations if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MonitorManagementClient: # pylint: disable=client-accepts-api-version-keyword +class MonitorManagementClient: """Monitor Management Client. :ivar action_groups: ActionGroupsOperations operations @@ -50,16 +52,40 @@ def __init__( self._config = MonitorManagementClientConfiguration( credential=credential, subscription_id=subscription_id, **kwargs ) - self._client: AsyncARMPipelineClient = AsyncARMPipelineClient(base_url=base_url, config=self._config, **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=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.action_groups = ActionGroupsOperations(self._client, self._config, self._serialize, self._deserialize) - self.baselines = BaselinesOperations(self._client, self._config, self._serialize, self._deserialize) + self.action_groups = ActionGroupsOperations( + self._client, self._config, self._serialize, self._deserialize, "2018-09-01" + ) + self.baselines = BaselinesOperations( + self._client, self._config, self._serialize, self._deserialize, "2018-09-01" + ) - 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 @@ -79,12 +105,12 @@ 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) -> "MonitorManagementClient": + async def __aenter__(self) -> Self: await self._client.__aenter__() return self diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_09_01/aio/operations/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_09_01/aio/operations/__init__.py index ea540c4b7b93..bc857528406a 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_09_01/aio/operations/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_09_01/aio/operations/__init__.py @@ -5,17 +5,23 @@ # 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 ._action_groups_operations import ActionGroupsOperations -from ._baselines_operations import BaselinesOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._action_groups_operations import ActionGroupsOperations # type: ignore +from ._baselines_operations import BaselinesOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ "ActionGroupsOperations", "BaselinesOperations", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_09_01/aio/operations/_action_groups_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_09_01/aio/operations/_action_groups_operations.py index ab1e0bae3655..0d6d4defa369 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_09_01/aio/operations/_action_groups_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_09_01/aio/operations/_action_groups_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload import urllib.parse @@ -19,15 +20,13 @@ 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 ...operations._action_groups_operations import ( build_create_or_update_request, build_delete_request, @@ -38,6 +37,10 @@ build_update_request, ) +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -60,6 +63,7 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @overload async def create_or_update( @@ -83,7 +87,6 @@ async def create_or_update( :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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_09_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -94,7 +97,7 @@ async def create_or_update( self, resource_group_name: str, action_group_name: str, - action_group: IO, + action_group: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -107,11 +110,10 @@ async def create_or_update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group: The action group to create or use for the update. Required. - :type action_group: IO + :type action_group: 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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_09_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -122,7 +124,7 @@ async def create_or_update( self, resource_group_name: str, action_group_name: str, - action_group: Union[_models.ActionGroupResource, IO], + action_group: Union[_models.ActionGroupResource, IO[bytes]], **kwargs: Any ) -> _models.ActionGroupResource: """Create a new action group or update an existing one. @@ -133,17 +135,13 @@ async def create_or_update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group: The action group to create or use for the update. Is either a - ActionGroupResource type or a IO type. Required. - :type action_group: ~azure.mgmt.monitor.v2018_09_01.models.ActionGroupResource 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 + ActionGroupResource type or a IO[bytes] type. Required. + :type action_group: ~azure.mgmt.monitor.v2018_09_01.models.ActionGroupResource or IO[bytes] :return: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_09_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -154,19 +152,19 @@ async def create_or_update( _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", "2018-09-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2018-09-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ActionGroupResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(action_group, (IO, bytes)): + if isinstance(action_group, (IOBase, bytes)): _content = action_group else: _json = self._serialize.body(action_group, "ActionGroupResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, action_group_name=action_group_name, subscription_id=self._config.subscription_id, @@ -174,16 +172,14 @@ async def create_or_update( 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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -193,21 +189,13 @@ async def create_or_update( 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("ActionGroupResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("ActionGroupResource", pipeline_response) + deserialized = self._deserialize("ActionGroupResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/actionGroups/{actionGroupName}" - } - @distributed_trace_async async def get(self, resource_group_name: str, action_group_name: str, **kwargs: Any) -> _models.ActionGroupResource: """Get an action group. @@ -217,12 +205,11 @@ async def get(self, resource_group_name: str, action_group_name: str, **kwargs: :type resource_group_name: str :param action_group_name: The name of the action group. Required. :type action_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_09_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -233,24 +220,22 @@ async def get(self, resource_group_name: str, action_group_name: str, **kwargs: _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2018-09-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2018-09-01")) cls: ClsType[_models.ActionGroupResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, action_group_name=action_group_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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -260,21 +245,15 @@ async def get(self, resource_group_name: str, action_group_name: str, **kwargs: error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ActionGroupResource", pipeline_response) + deserialized = self._deserialize("ActionGroupResource", 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.insights/actionGroups/{actionGroupName}" - } + return deserialized # type: ignore @distributed_trace_async - async def delete( # pylint: disable=inconsistent-return-statements - self, resource_group_name: str, action_group_name: str, **kwargs: Any - ) -> None: + async def delete(self, resource_group_name: str, action_group_name: str, **kwargs: Any) -> None: """Delete an action group. :param resource_group_name: The name of the resource group. The name is case insensitive. @@ -282,12 +261,11 @@ async def delete( # pylint: disable=inconsistent-return-statements :type resource_group_name: str :param action_group_name: The name of the action group. Required. :type action_group_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, @@ -298,24 +276,22 @@ async def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2018-09-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2018-09-01")) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, action_group_name=action_group_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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -326,11 +302,7 @@ async def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/actionGroups/{actionGroupName}" - } + return cls(pipeline_response, None, {}) # type: ignore @overload async def update( @@ -354,7 +326,6 @@ async def update( :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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_09_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -365,7 +336,7 @@ async def update( self, resource_group_name: str, action_group_name: str, - action_group_patch: IO, + action_group_patch: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -378,11 +349,10 @@ async def update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group_patch: Parameters supplied to the operation. Required. - :type action_group_patch: IO + :type action_group_patch: 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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_09_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -393,7 +363,7 @@ async def update( self, resource_group_name: str, action_group_name: str, - action_group_patch: Union[_models.ActionGroupPatchBody, IO], + action_group_patch: Union[_models.ActionGroupPatchBody, IO[bytes]], **kwargs: Any ) -> _models.ActionGroupResource: """Updates an existing action group's tags. To update other fields use the CreateOrUpdate method. @@ -404,17 +374,14 @@ async def update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group_patch: Parameters supplied to the operation. Is either a - ActionGroupPatchBody type or a IO type. Required. - :type action_group_patch: ~azure.mgmt.monitor.v2018_09_01.models.ActionGroupPatchBody 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 + ActionGroupPatchBody type or a IO[bytes] type. Required. + :type action_group_patch: ~azure.mgmt.monitor.v2018_09_01.models.ActionGroupPatchBody or + IO[bytes] :return: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_09_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -425,19 +392,19 @@ async def update( _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", "2018-09-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2018-09-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ActionGroupResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(action_group_patch, (IO, bytes)): + if isinstance(action_group_patch, (IOBase, bytes)): _content = action_group_patch else: _json = self._serialize.body(action_group_patch, "ActionGroupPatchBody") - request = build_update_request( + _request = build_update_request( resource_group_name=resource_group_name, action_group_name=action_group_name, subscription_id=self._config.subscription_id, @@ -445,16 +412,14 @@ async def update( 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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -464,22 +429,17 @@ async def update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ActionGroupResource", pipeline_response) + deserialized = self._deserialize("ActionGroupResource", 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.insights/actionGroups/{actionGroupName}" - } + return deserialized # type: ignore @distributed_trace def list_by_subscription_id(self, **kwargs: Any) -> AsyncIterable["_models.ActionGroupResource"]: """Get a list of all action groups in a subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ActionGroupResource or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.monitor.v2018_09_01.models.ActionGroupResource] @@ -488,10 +448,10 @@ def list_by_subscription_id(self, **kwargs: Any) -> AsyncIterable["_models.Actio _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2018-09-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2018-09-01")) cls: ClsType[_models.ActionGroupList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -502,15 +462,13 @@ def list_by_subscription_id(self, **kwargs: Any) -> AsyncIterable["_models.Actio def prepare_request(next_link=None): if not next_link: - request = build_list_by_subscription_id_request( + _request = build_list_by_subscription_id_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_subscription_id.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -521,14 +479,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("ActionGroupList", pipeline_response) @@ -538,11 +495,11 @@ async def extract_data(pipeline_response): return None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -555,10 +512,6 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_by_subscription_id.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/microsoft.insights/actionGroups" - } - @distributed_trace def list_by_resource_group( self, resource_group_name: str, **kwargs: Any @@ -568,7 +521,6 @@ def list_by_resource_group( :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ActionGroupResource or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.monitor.v2018_09_01.models.ActionGroupResource] @@ -577,10 +529,10 @@ def list_by_resource_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2018-09-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2018-09-01")) cls: ClsType[_models.ActionGroupList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -591,16 +543,14 @@ 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_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -611,14 +561,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("ActionGroupList", pipeline_response) @@ -628,11 +577,11 @@ async def extract_data(pipeline_response): return None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -645,12 +594,8 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/actionGroups" - } - @overload - async def enable_receiver( # pylint: disable=inconsistent-return-statements + async def enable_receiver( self, resource_group_name: str, action_group_name: str, @@ -672,18 +617,17 @@ async def enable_receiver( # pylint: disable=inconsistent-return-statements :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: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def enable_receiver( # pylint: disable=inconsistent-return-statements + async def enable_receiver( self, resource_group_name: str, action_group_name: str, - enable_request: IO, + enable_request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -697,22 +641,21 @@ async def enable_receiver( # pylint: disable=inconsistent-return-statements :param action_group_name: The name of the action group. Required. :type action_group_name: str :param enable_request: The receiver to re-enable. Required. - :type enable_request: IO + :type enable_request: 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: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async - async def enable_receiver( # pylint: disable=inconsistent-return-statements + async def enable_receiver( self, resource_group_name: str, action_group_name: str, - enable_request: Union[_models.EnableRequest, IO], + enable_request: Union[_models.EnableRequest, IO[bytes]], **kwargs: Any ) -> None: """Enable a receiver in an action group. This changes the receiver's status from Disabled to @@ -723,18 +666,14 @@ async def enable_receiver( # pylint: disable=inconsistent-return-statements :type resource_group_name: str :param action_group_name: The name of the action group. Required. :type action_group_name: str - :param enable_request: The receiver to re-enable. Is either a EnableRequest type or a IO type. - Required. - :type enable_request: ~azure.mgmt.monitor.v2018_09_01.models.EnableRequest 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 + :param enable_request: The receiver to re-enable. Is either a EnableRequest type or a IO[bytes] + type. Required. + :type enable_request: ~azure.mgmt.monitor.v2018_09_01.models.EnableRequest or IO[bytes] :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, @@ -745,19 +684,19 @@ async def enable_receiver( # pylint: disable=inconsistent-return-statements _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", "2018-09-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2018-09-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[None] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(enable_request, (IO, bytes)): + if isinstance(enable_request, (IOBase, bytes)): _content = enable_request else: _json = self._serialize.body(enable_request, "EnableRequest") - request = build_enable_receiver_request( + _request = build_enable_receiver_request( resource_group_name=resource_group_name, action_group_name=action_group_name, subscription_id=self._config.subscription_id, @@ -765,16 +704,14 @@ async def enable_receiver( # pylint: disable=inconsistent-return-statements content_type=content_type, json=_json, content=_content, - template_url=self.enable_receiver.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -785,8 +722,4 @@ async def enable_receiver( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - enable_receiver.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/actionGroups/{actionGroupName}/subscribe" - } + return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_09_01/aio/operations/_baselines_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_09_01/aio/operations/_baselines_operations.py index 5b11f1cba4f6..e2293afe2d71 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_09_01/aio/operations/_baselines_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_09_01/aio/operations/_baselines_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +6,7 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- import datetime +import sys from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar, Union import urllib.parse @@ -20,16 +20,18 @@ 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 ...operations._baselines_operations import build_list_request +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -52,6 +54,7 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list( @@ -95,17 +98,16 @@ def list( eq 'a1' and B eq 'b1' and C eq '*' or B = 'b2'** This is invalid because the logical or operator cannot separate two different metadata names. - Return all time series where A = a1, B = b1 and C = c1: **$filter=A eq 'a1' and B eq 'b1' and C eq 'c1'** - Return all time series - where A = a1 **$filter=A eq 'a1' and B eq '\ *' and C eq '*\ '**. Special case: When dimension - name or dimension value uses round brackets. Eg: When dimension name is **dim (test) 1** - Instead of using $filter= "dim (test) 1 eq '\ *' " use **$filter= "dim %2528test%2529 1 eq '*\ - ' "\ ** When dimension name is **\ dim (test) 3\ ** and dimension value is **\ dim3 (test) val\ - ** Instead of using $filter= "dim (test) 3 eq 'dim3 (test) val' " use **\ $filter= "dim - %2528test%2529 3 eq 'dim3 %2528test%2529 val' "**. Default value is None. + where A = a1 **$filter=A eq 'a1' and B eq '\\ *' and C eq '*\\ '**. Special case: When + dimension name or dimension value uses round brackets. Eg: When dimension name is **dim (test) + 1** Instead of using $filter= "dim (test) 1 eq '\\ *' " use **$filter= "dim %2528test%2529 1 eq + '*\\ ' "\\ ** When dimension name is **\\ dim (test) 3\\ ** and dimension value is **\\ dim3 + (test) val\\ ** Instead of using $filter= "dim (test) 3 eq 'dim3 (test) val' " use **\\ + $filter= "dim %2528test%2529 3 eq 'dim3 %2528test%2529 val' "**. Default value is None. :type filter: str :param result_type: Allows retrieving only metadata of the baseline. On data request all information is retrieved. Known values are: "Data" and "Metadata". Default value is None. :type result_type: str or ~azure.mgmt.monitor.v2018_09_01.models.ResultType - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either SingleMetricBaseline or the result of cls(response) :rtype: @@ -115,10 +117,10 @@ def list( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2018-09-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2018-09-01")) cls: ClsType[_models.MetricBaselinesResponse] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -129,7 +131,7 @@ def list( def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( resource_uri=resource_uri, metricnames=metricnames, metricnamespace=metricnamespace, @@ -140,12 +142,10 @@ def prepare_request(next_link=None): filter=filter, result_type=result_type, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -156,14 +156,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("MetricBaselinesResponse", pipeline_response) @@ -173,11 +172,11 @@ async def extract_data(pipeline_response): return None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -189,5 +188,3 @@ async def get_next(next_link=None): return pipeline_response return AsyncItemPaged(get_next, extract_data) - - list.metadata = {"url": "/{resourceUri}/providers/Microsoft.Insights/metricBaselines"} diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_09_01/models/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_09_01/models/__init__.py index b29f7c4a325e..edd2e80e1bf6 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_09_01/models/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_09_01/models/__init__.py @@ -5,35 +5,46 @@ # 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 ActionGroupList -from ._models_py3 import ActionGroupPatchBody -from ._models_py3 import ActionGroupResource -from ._models_py3 import ArmRoleReceiver -from ._models_py3 import AutomationRunbookReceiver -from ._models_py3 import AzureAppPushReceiver -from ._models_py3 import AzureFunctionReceiver -from ._models_py3 import BaselineMetadata -from ._models_py3 import EmailReceiver -from ._models_py3 import EnableRequest -from ._models_py3 import ErrorResponse -from ._models_py3 import ItsmReceiver -from ._models_py3 import LogicAppReceiver -from ._models_py3 import MetricBaselinesResponse -from ._models_py3 import MetricSingleDimension -from ._models_py3 import Resource -from ._models_py3 import SingleBaseline -from ._models_py3 import SingleMetricBaseline -from ._models_py3 import SmsReceiver -from ._models_py3 import TimeSeriesBaseline -from ._models_py3 import VoiceReceiver -from ._models_py3 import WebhookReceiver +from typing import TYPE_CHECKING -from ._monitor_management_client_enums import BaselineSensitivity -from ._monitor_management_client_enums import ReceiverStatus -from ._monitor_management_client_enums import ResultType +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models_py3 import ( # type: ignore + ActionGroupList, + ActionGroupPatchBody, + ActionGroupResource, + ArmRoleReceiver, + AutomationRunbookReceiver, + AzureAppPushReceiver, + AzureFunctionReceiver, + BaselineMetadata, + EmailReceiver, + EnableRequest, + ErrorResponse, + ItsmReceiver, + LogicAppReceiver, + MetricBaselinesResponse, + MetricSingleDimension, + Resource, + SingleBaseline, + SingleMetricBaseline, + SmsReceiver, + TimeSeriesBaseline, + VoiceReceiver, + WebhookReceiver, +) + +from ._monitor_management_client_enums import ( # type: ignore + BaselineSensitivity, + ReceiverStatus, + ResultType, +) from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ @@ -63,5 +74,5 @@ "ReceiverStatus", "ResultType", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_09_01/models/_models_py3.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_09_01/models/_models_py3.py index 2b3dbebf8638..ff7c62d0d85e 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_09_01/models/_models_py3.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_09_01/models/_models_py3.py @@ -1,5 +1,5 @@ -# coding=utf-8 # 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. @@ -13,7 +13,6 @@ from ... import _serialization if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from .. import models as _models @@ -82,7 +81,7 @@ class Resource(_serialization.Model): 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: Azure resource Id. :vartype id: str @@ -126,12 +125,12 @@ def __init__(self, *, location: str, tags: Optional[Dict[str, str]] = None, **kw self.tags = tags -class ActionGroupResource(Resource): # pylint: disable=too-many-instance-attributes +class ActionGroupResource(Resource): """An action group 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: Azure resource Id. :vartype id: str @@ -285,7 +284,7 @@ def __init__( class ArmRoleReceiver(_serialization.Model): """An arm role receiver. - 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 name of the arm role receiver. Names must be unique across all receivers within an action group. Required. @@ -320,7 +319,7 @@ def __init__(self, *, name: str, role_id: str, **kwargs: Any) -> None: class AutomationRunbookReceiver(_serialization.Model): """The Azure Automation Runbook notification receiver. - 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 automation_account_id: The Azure automation account Id which holds this runbook and authenticate to Azure resource. Required. @@ -391,7 +390,7 @@ def __init__( class AzureAppPushReceiver(_serialization.Model): """The Azure mobile App push notification receiver. - 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 name of the Azure mobile app push receiver. Names must be unique across all receivers within an action group. Required. @@ -426,7 +425,7 @@ def __init__(self, *, name: str, email_address: str, **kwargs: Any) -> None: class AzureFunctionReceiver(_serialization.Model): """An azure function receiver. - 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 name of the azure function receiver. Names must be unique across all receivers within an action group. Required. @@ -477,7 +476,7 @@ def __init__( class BaselineMetadata(_serialization.Model): """Represents a baseline metadata value. - 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: Name of the baseline metadata. Required. :vartype name: str @@ -512,7 +511,7 @@ class EmailReceiver(_serialization.Model): 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 name: The name of the email receiver. Names must be unique across all receivers within an action group. Required. @@ -553,7 +552,7 @@ def __init__(self, *, name: str, email_address: str, **kwargs: Any) -> None: class EnableRequest(_serialization.Model): """Describes a receiver that should be resubscribed. - 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 receiver_name: The name of the receiver to resubscribe. Required. :vartype receiver_name: str @@ -605,7 +604,7 @@ def __init__(self, *, code: Optional[str] = None, message: Optional[str] = None, class ItsmReceiver(_serialization.Model): """An Itsm receiver. - 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 name of the Itsm receiver. Names must be unique across all receivers within an action group. Required. @@ -619,7 +618,7 @@ class ItsmReceiver(_serialization.Model): CreateMultipleWorkItems option will be part of this blob as well. Required. :vartype ticket_configuration: str :ivar region: Region in which workspace resides. Supported - values:'centralindia','japaneast','southeastasia','australiasoutheast','uksouth','westcentralus','canadacentral','eastus','westeurope'. + values:'centralindia','japaneast','southeastasia','australiasoutheast','uksouth','westcentralus','canadacentral','eastus','westeurope'. # pylint: disable=line-too-long Required. :vartype region: str """ @@ -656,7 +655,7 @@ def __init__( CreateMultipleWorkItems option will be part of this blob as well. Required. :paramtype ticket_configuration: str :keyword region: Region in which workspace resides. Supported - values:'centralindia','japaneast','southeastasia','australiasoutheast','uksouth','westcentralus','canadacentral','eastus','westeurope'. + values:'centralindia','japaneast','southeastasia','australiasoutheast','uksouth','westcentralus','canadacentral','eastus','westeurope'. # pylint: disable=line-too-long Required. :paramtype region: str """ @@ -671,7 +670,7 @@ def __init__( class LogicAppReceiver(_serialization.Model): """A logic app receiver. - 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 name of the logic app receiver. Names must be unique across all receivers within an action group. Required. @@ -713,7 +712,7 @@ def __init__(self, *, name: str, resource_id: str, callback_url: str, **kwargs: class MetricBaselinesResponse(_serialization.Model): """A list of metric baselines. - 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 timespan: The timespan for which the data was retrieved. Its value consists of two datetimes concatenated, separated by '/'. This may be adjusted in the future and returned back @@ -774,7 +773,7 @@ def __init__( class MetricSingleDimension(_serialization.Model): """The metric dimension name and value. - 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: Name of the dimension. Required. :vartype name: str @@ -807,7 +806,7 @@ def __init__(self, *, name: str, value: str, **kwargs: Any) -> None: class SingleBaseline(_serialization.Model): """The baseline values for a single sensitivity value. - 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 sensitivity: the sensitivity of the baseline. Required. Known values are: "Low", "Medium", and "High". @@ -856,7 +855,7 @@ def __init__( class SingleMetricBaseline(_serialization.Model): """The baseline results of a single metric. - 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: The metric baseline Id. Required. :vartype id: str @@ -913,7 +912,7 @@ class SmsReceiver(_serialization.Model): 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 name: The name of the SMS receiver. Names must be unique across all receivers within an action group. Required. @@ -961,7 +960,7 @@ def __init__(self, *, name: str, country_code: str, phone_number: str, **kwargs: class TimeSeriesBaseline(_serialization.Model): """The baseline values for a single time series. - 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 aggregation: The aggregation type of the metric. Required. :vartype aggregation: str @@ -1022,7 +1021,7 @@ def __init__( class VoiceReceiver(_serialization.Model): """A voice receiver. - 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 name of the voice receiver. Names must be unique across all receivers within an action group. Required. @@ -1064,7 +1063,7 @@ def __init__(self, *, name: str, country_code: str, phone_number: str, **kwargs: class WebhookReceiver(_serialization.Model): """A webhook receiver. - 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 name of the webhook receiver. Names must be unique across all receivers within an action group. Required. diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_09_01/operations/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_09_01/operations/__init__.py index ea540c4b7b93..bc857528406a 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_09_01/operations/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_09_01/operations/__init__.py @@ -5,17 +5,23 @@ # 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 ._action_groups_operations import ActionGroupsOperations -from ._baselines_operations import BaselinesOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._action_groups_operations import ActionGroupsOperations # type: ignore +from ._baselines_operations import BaselinesOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ "ActionGroupsOperations", "BaselinesOperations", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_09_01/operations/_action_groups_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_09_01/operations/_action_groups_operations.py index 30b66925f7ef..0ec68cc1decd 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_09_01/operations/_action_groups_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_09_01/operations/_action_groups_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload import urllib.parse @@ -19,16 +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, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -59,7 +62,7 @@ def build_create_or_update_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -94,7 +97,7 @@ def build_get_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -127,7 +130,7 @@ def build_delete_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -161,7 +164,7 @@ def build_update_request( "actionGroupName": _SERIALIZER.url("action_group_name", action_group_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -187,7 +190,7 @@ def build_list_by_subscription_id_request(subscription_id: str, **kwargs: Any) - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -217,7 +220,7 @@ def build_list_by_resource_group_request(resource_group_name: str, subscription_ "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -251,7 +254,7 @@ def build_enable_receiver_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -282,6 +285,7 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @overload def create_or_update( @@ -305,7 +309,6 @@ def create_or_update( :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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_09_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -316,7 +319,7 @@ def create_or_update( self, resource_group_name: str, action_group_name: str, - action_group: IO, + action_group: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -329,11 +332,10 @@ def create_or_update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group: The action group to create or use for the update. Required. - :type action_group: IO + :type action_group: 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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_09_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -344,7 +346,7 @@ def create_or_update( self, resource_group_name: str, action_group_name: str, - action_group: Union[_models.ActionGroupResource, IO], + action_group: Union[_models.ActionGroupResource, IO[bytes]], **kwargs: Any ) -> _models.ActionGroupResource: """Create a new action group or update an existing one. @@ -355,17 +357,13 @@ def create_or_update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group: The action group to create or use for the update. Is either a - ActionGroupResource type or a IO type. Required. - :type action_group: ~azure.mgmt.monitor.v2018_09_01.models.ActionGroupResource 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 + ActionGroupResource type or a IO[bytes] type. Required. + :type action_group: ~azure.mgmt.monitor.v2018_09_01.models.ActionGroupResource or IO[bytes] :return: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_09_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -376,19 +374,19 @@ def create_or_update( _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", "2018-09-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2018-09-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ActionGroupResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(action_group, (IO, bytes)): + if isinstance(action_group, (IOBase, bytes)): _content = action_group else: _json = self._serialize.body(action_group, "ActionGroupResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, action_group_name=action_group_name, subscription_id=self._config.subscription_id, @@ -396,16 +394,14 @@ def create_or_update( 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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -415,21 +411,13 @@ def create_or_update( 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("ActionGroupResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("ActionGroupResource", pipeline_response) + deserialized = self._deserialize("ActionGroupResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/actionGroups/{actionGroupName}" - } - @distributed_trace def get(self, resource_group_name: str, action_group_name: str, **kwargs: Any) -> _models.ActionGroupResource: """Get an action group. @@ -439,12 +427,11 @@ def get(self, resource_group_name: str, action_group_name: str, **kwargs: Any) - :type resource_group_name: str :param action_group_name: The name of the action group. Required. :type action_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_09_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -455,24 +442,22 @@ def get(self, resource_group_name: str, action_group_name: str, **kwargs: Any) - _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2018-09-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2018-09-01")) cls: ClsType[_models.ActionGroupResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, action_group_name=action_group_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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -482,16 +467,12 @@ def get(self, resource_group_name: str, action_group_name: str, **kwargs: Any) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ActionGroupResource", pipeline_response) + deserialized = self._deserialize("ActionGroupResource", 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.insights/actionGroups/{actionGroupName}" - } + return deserialized # type: ignore @distributed_trace def delete( # pylint: disable=inconsistent-return-statements @@ -504,12 +485,11 @@ def delete( # pylint: disable=inconsistent-return-statements :type resource_group_name: str :param action_group_name: The name of the action group. Required. :type action_group_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, @@ -520,24 +500,22 @@ def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2018-09-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2018-09-01")) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, action_group_name=action_group_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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -548,11 +526,7 @@ def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/actionGroups/{actionGroupName}" - } + return cls(pipeline_response, None, {}) # type: ignore @overload def update( @@ -576,7 +550,6 @@ def update( :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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_09_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -587,7 +560,7 @@ def update( self, resource_group_name: str, action_group_name: str, - action_group_patch: IO, + action_group_patch: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -600,11 +573,10 @@ def update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group_patch: Parameters supplied to the operation. Required. - :type action_group_patch: IO + :type action_group_patch: 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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_09_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -615,7 +587,7 @@ def update( self, resource_group_name: str, action_group_name: str, - action_group_patch: Union[_models.ActionGroupPatchBody, IO], + action_group_patch: Union[_models.ActionGroupPatchBody, IO[bytes]], **kwargs: Any ) -> _models.ActionGroupResource: """Updates an existing action group's tags. To update other fields use the CreateOrUpdate method. @@ -626,17 +598,14 @@ def update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group_patch: Parameters supplied to the operation. Is either a - ActionGroupPatchBody type or a IO type. Required. - :type action_group_patch: ~azure.mgmt.monitor.v2018_09_01.models.ActionGroupPatchBody 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 + ActionGroupPatchBody type or a IO[bytes] type. Required. + :type action_group_patch: ~azure.mgmt.monitor.v2018_09_01.models.ActionGroupPatchBody or + IO[bytes] :return: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_09_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -647,19 +616,19 @@ def update( _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", "2018-09-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2018-09-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ActionGroupResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(action_group_patch, (IO, bytes)): + if isinstance(action_group_patch, (IOBase, bytes)): _content = action_group_patch else: _json = self._serialize.body(action_group_patch, "ActionGroupPatchBody") - request = build_update_request( + _request = build_update_request( resource_group_name=resource_group_name, action_group_name=action_group_name, subscription_id=self._config.subscription_id, @@ -667,16 +636,14 @@ def update( 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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -686,22 +653,17 @@ def update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ActionGroupResource", pipeline_response) + deserialized = self._deserialize("ActionGroupResource", 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.insights/actionGroups/{actionGroupName}" - } + return deserialized # type: ignore @distributed_trace def list_by_subscription_id(self, **kwargs: Any) -> Iterable["_models.ActionGroupResource"]: """Get a list of all action groups in a subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ActionGroupResource or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.monitor.v2018_09_01.models.ActionGroupResource] @@ -710,10 +672,10 @@ def list_by_subscription_id(self, **kwargs: Any) -> Iterable["_models.ActionGrou _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2018-09-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2018-09-01")) cls: ClsType[_models.ActionGroupList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -724,15 +686,13 @@ def list_by_subscription_id(self, **kwargs: Any) -> Iterable["_models.ActionGrou def prepare_request(next_link=None): if not next_link: - request = build_list_by_subscription_id_request( + _request = build_list_by_subscription_id_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_subscription_id.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -743,14 +703,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("ActionGroupList", pipeline_response) @@ -760,11 +719,11 @@ def extract_data(pipeline_response): return None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -777,10 +736,6 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_by_subscription_id.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/microsoft.insights/actionGroups" - } - @distributed_trace def list_by_resource_group( self, resource_group_name: str, **kwargs: Any @@ -790,7 +745,6 @@ def list_by_resource_group( :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ActionGroupResource or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.monitor.v2018_09_01.models.ActionGroupResource] @@ -799,10 +753,10 @@ def list_by_resource_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2018-09-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2018-09-01")) cls: ClsType[_models.ActionGroupList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -813,16 +767,14 @@ 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_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -833,14 +785,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("ActionGroupList", pipeline_response) @@ -850,11 +801,11 @@ def extract_data(pipeline_response): return None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -867,12 +818,8 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/actionGroups" - } - @overload - def enable_receiver( # pylint: disable=inconsistent-return-statements + def enable_receiver( self, resource_group_name: str, action_group_name: str, @@ -894,18 +841,17 @@ def enable_receiver( # pylint: disable=inconsistent-return-statements :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: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def enable_receiver( # pylint: disable=inconsistent-return-statements + def enable_receiver( self, resource_group_name: str, action_group_name: str, - enable_request: IO, + enable_request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -919,11 +865,10 @@ def enable_receiver( # pylint: disable=inconsistent-return-statements :param action_group_name: The name of the action group. Required. :type action_group_name: str :param enable_request: The receiver to re-enable. Required. - :type enable_request: IO + :type enable_request: 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: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -934,7 +879,7 @@ def enable_receiver( # pylint: disable=inconsistent-return-statements self, resource_group_name: str, action_group_name: str, - enable_request: Union[_models.EnableRequest, IO], + enable_request: Union[_models.EnableRequest, IO[bytes]], **kwargs: Any ) -> None: """Enable a receiver in an action group. This changes the receiver's status from Disabled to @@ -945,18 +890,14 @@ def enable_receiver( # pylint: disable=inconsistent-return-statements :type resource_group_name: str :param action_group_name: The name of the action group. Required. :type action_group_name: str - :param enable_request: The receiver to re-enable. Is either a EnableRequest type or a IO type. - Required. - :type enable_request: ~azure.mgmt.monitor.v2018_09_01.models.EnableRequest 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 + :param enable_request: The receiver to re-enable. Is either a EnableRequest type or a IO[bytes] + type. Required. + :type enable_request: ~azure.mgmt.monitor.v2018_09_01.models.EnableRequest or IO[bytes] :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, @@ -967,19 +908,19 @@ def enable_receiver( # pylint: disable=inconsistent-return-statements _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", "2018-09-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2018-09-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[None] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(enable_request, (IO, bytes)): + if isinstance(enable_request, (IOBase, bytes)): _content = enable_request else: _json = self._serialize.body(enable_request, "EnableRequest") - request = build_enable_receiver_request( + _request = build_enable_receiver_request( resource_group_name=resource_group_name, action_group_name=action_group_name, subscription_id=self._config.subscription_id, @@ -987,16 +928,14 @@ def enable_receiver( # pylint: disable=inconsistent-return-statements content_type=content_type, json=_json, content=_content, - template_url=self.enable_receiver.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1007,8 +946,4 @@ def enable_receiver( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - enable_receiver.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/actionGroups/{actionGroupName}/subscribe" - } + return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_09_01/operations/_baselines_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_09_01/operations/_baselines_operations.py index ab54bcbbc1ea..1a2fc3a32189 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_09_01/operations/_baselines_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_09_01/operations/_baselines_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +6,7 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- import datetime +import sys from typing import Any, Callable, Dict, Iterable, Optional, TypeVar, Union import urllib.parse @@ -20,16 +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, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -62,7 +64,7 @@ def build_list_request( "resourceUri": _SERIALIZER.url("resource_uri", resource_uri, "str", skip_quote=True), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters if metricnames is not None: @@ -107,6 +109,7 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list( @@ -150,17 +153,16 @@ def list( eq 'a1' and B eq 'b1' and C eq '*' or B = 'b2'** This is invalid because the logical or operator cannot separate two different metadata names. - Return all time series where A = a1, B = b1 and C = c1: **$filter=A eq 'a1' and B eq 'b1' and C eq 'c1'** - Return all time series - where A = a1 **$filter=A eq 'a1' and B eq '\ *' and C eq '*\ '**. Special case: When dimension - name or dimension value uses round brackets. Eg: When dimension name is **dim (test) 1** - Instead of using $filter= "dim (test) 1 eq '\ *' " use **$filter= "dim %2528test%2529 1 eq '*\ - ' "\ ** When dimension name is **\ dim (test) 3\ ** and dimension value is **\ dim3 (test) val\ - ** Instead of using $filter= "dim (test) 3 eq 'dim3 (test) val' " use **\ $filter= "dim - %2528test%2529 3 eq 'dim3 %2528test%2529 val' "**. Default value is None. + where A = a1 **$filter=A eq 'a1' and B eq '\\ *' and C eq '*\\ '**. Special case: When + dimension name or dimension value uses round brackets. Eg: When dimension name is **dim (test) + 1** Instead of using $filter= "dim (test) 1 eq '\\ *' " use **$filter= "dim %2528test%2529 1 eq + '*\\ ' "\\ ** When dimension name is **\\ dim (test) 3\\ ** and dimension value is **\\ dim3 + (test) val\\ ** Instead of using $filter= "dim (test) 3 eq 'dim3 (test) val' " use **\\ + $filter= "dim %2528test%2529 3 eq 'dim3 %2528test%2529 val' "**. Default value is None. :type filter: str :param result_type: Allows retrieving only metadata of the baseline. On data request all information is retrieved. Known values are: "Data" and "Metadata". Default value is None. :type result_type: str or ~azure.mgmt.monitor.v2018_09_01.models.ResultType - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either SingleMetricBaseline or the result of cls(response) :rtype: @@ -170,10 +172,10 @@ def list( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2018-09-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2018-09-01")) cls: ClsType[_models.MetricBaselinesResponse] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -184,7 +186,7 @@ def list( def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( resource_uri=resource_uri, metricnames=metricnames, metricnamespace=metricnamespace, @@ -195,12 +197,10 @@ def prepare_request(next_link=None): filter=filter, result_type=result_type, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -211,14 +211,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("MetricBaselinesResponse", pipeline_response) @@ -228,11 +227,11 @@ def extract_data(pipeline_response): return None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -244,5 +243,3 @@ def get_next(next_link=None): return pipeline_response return ItemPaged(get_next, extract_data) - - list.metadata = {"url": "/{resourceUri}/providers/Microsoft.Insights/metricBaselines"} diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_11_27_preview/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_11_27_preview/__init__.py index 2c7733bfd566..42cc62301757 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_11_27_preview/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_11_27_preview/__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 ._monitor_management_client import MonitorManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._monitor_management_client import MonitorManagementClient # type: ignore from ._version import VERSION __version__ = VERSION try: from ._patch import __all__ as _patch_all - from ._patch import * # 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__ = [ "MonitorManagementClient", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_11_27_preview/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_11_27_preview/_configuration.py index 14b202445968..89f7c2bb9861 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_11_27_preview/_configuration.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_11_27_preview/_configuration.py @@ -8,18 +8,16 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy from ._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MonitorManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class MonitorManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for MonitorManagementClient. Note that all parameters used to create this instance are saved as instance @@ -33,7 +31,6 @@ class MonitorManagementClientConfiguration(Configuration): # pylint: disable=to """ def __init__(self, credential: "TokenCredential", **kwargs: Any) -> None: - super(MonitorManagementClientConfiguration, self).__init__(**kwargs) api_version: str = kwargs.pop("api_version", "2018-11-27-preview") if credential is None: @@ -43,6 +40,7 @@ def __init__(self, credential: "TokenCredential", **kwargs: Any) -> None: self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-monitor/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -51,9 +49,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.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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_11_27_preview/_metadata.json b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_11_27_preview/_metadata.json index 5c87c2239967..513d1061c93d 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_11_27_preview/_metadata.json +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_11_27_preview/_metadata.json @@ -8,10 +8,10 @@ "host_value": "\"https://management.azure.com\"", "parameterized_host_template": null, "azure_arm": true, - "has_lro_operations": false, + "has_public_lro_operations": false, "client_side_validation": false, - "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"sdkcore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMAutoResourceProviderRegistrationPolicy\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}, \"stdlib\": {\"typing_extensions\": [\"Self\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"sdkcore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"AsyncARMAutoResourceProviderRegistrationPolicy\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}, \"stdlib\": {\"typing_extensions\": [\"Self\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "global_parameters": { "sync": { @@ -88,8 +88,8 @@ "credential_scopes": ["https://management.azure.com/.default"], "credential_call_sync": "ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", "credential_call_async": "AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", - "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "sync_imports": "{\"regular\": {\"sdkcore\": {\"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"regular\": {\"sdkcore\": {\"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "operation_groups": { "vm_insights": "VMInsightsOperations" diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_11_27_preview/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_11_27_preview/_monitor_management_client.py index 88d2d3d6ad3b..79be51695d8c 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_11_27_preview/_monitor_management_client.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_11_27_preview/_monitor_management_client.py @@ -8,9 +8,12 @@ from copy import deepcopy from typing import Any, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient +from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy from . import models as _models from .._serialization import Deserializer, Serializer @@ -18,11 +21,10 @@ from .operations import VMInsightsOperations if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MonitorManagementClient: # pylint: disable=client-accepts-api-version-keyword +class MonitorManagementClient: """Monitor Management Client. :ivar vm_insights: VMInsightsOperations operations @@ -40,15 +42,35 @@ def __init__( self, credential: "TokenCredential", base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: self._config = MonitorManagementClientConfiguration(credential=credential, **kwargs) - self._client: ARMPipelineClient = ARMPipelineClient(base_url=base_url, config=self._config, **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), + 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=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.vm_insights = VMInsightsOperations(self._client, self._config, self._serialize, self._deserialize) + self.vm_insights = VMInsightsOperations( + self._client, self._config, self._serialize, self._deserialize, "2018-11-27-preview" + ) - 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 @@ -68,12 +90,12 @@ 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) -> None: self._client.close() - def __enter__(self) -> "MonitorManagementClient": + def __enter__(self) -> Self: self._client.__enter__() return self diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_11_27_preview/_vendor.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_11_27_preview/_vendor.py deleted file mode 100644 index bd0df84f5319..000000000000 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_11_27_preview/_vendor.py +++ /dev/null @@ -1,30 +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 typing import List, cast - -from azure.core.pipeline.transport import HttpRequest - - -def _convert_request(request, files=None): - data = request.content if not files else None - request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) - if files: - request.set_formdata_body(files) - return request - - -def _format_url_section(template, **kwargs): - components = template.split("/") - while components: - try: - return template.format(**kwargs) - except KeyError as key: - # Need the cast, as for some reasons "split" is typed as list[str | Any] - formatted_components = cast(List[str], template.split("/")) - components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] - template = "/".join(components) diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_11_27_preview/_version.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_11_27_preview/_version.py index 394ee7c0c03c..e5754a47ce68 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_11_27_preview/_version.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_11_27_preview/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "6.0.2" +VERSION = "1.0.0b1" diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_11_27_preview/aio/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_11_27_preview/aio/__init__.py index 2c151bb41c19..3df30ff42149 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_11_27_preview/aio/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_11_27_preview/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 ._monitor_management_client import MonitorManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._monitor_management_client import MonitorManagementClient # type: ignore try: from ._patch import __all__ as _patch_all - from ._patch import * # 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__ = [ "MonitorManagementClient", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_11_27_preview/aio/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_11_27_preview/aio/_configuration.py index a36e7edf0602..914e6fca8c1a 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_11_27_preview/aio/_configuration.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_11_27_preview/aio/_configuration.py @@ -8,18 +8,16 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy from .._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MonitorManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class MonitorManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for MonitorManagementClient. Note that all parameters used to create this instance are saved as instance @@ -33,7 +31,6 @@ class MonitorManagementClientConfiguration(Configuration): # pylint: disable=to """ def __init__(self, credential: "AsyncTokenCredential", **kwargs: Any) -> None: - super(MonitorManagementClientConfiguration, self).__init__(**kwargs) api_version: str = kwargs.pop("api_version", "2018-11-27-preview") if credential is None: @@ -43,6 +40,7 @@ def __init__(self, credential: "AsyncTokenCredential", **kwargs: Any) -> None: self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-monitor/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -51,9 +49,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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_11_27_preview/aio/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_11_27_preview/aio/_monitor_management_client.py index 1b4d87006e7f..b629153d9971 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_11_27_preview/aio/_monitor_management_client.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_11_27_preview/aio/_monitor_management_client.py @@ -8,9 +8,12 @@ from copy import deepcopy from typing import Any, Awaitable, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient +from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy from .. import models as _models from ..._serialization import Deserializer, Serializer @@ -18,11 +21,10 @@ from .operations import VMInsightsOperations if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MonitorManagementClient: # pylint: disable=client-accepts-api-version-keyword +class MonitorManagementClient: """Monitor Management Client. :ivar vm_insights: VMInsightsOperations operations @@ -41,15 +43,37 @@ def __init__( self, credential: "AsyncTokenCredential", base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: self._config = MonitorManagementClientConfiguration(credential=credential, **kwargs) - self._client: AsyncARMPipelineClient = AsyncARMPipelineClient(base_url=base_url, config=self._config, **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=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.vm_insights = VMInsightsOperations(self._client, self._config, self._serialize, self._deserialize) + self.vm_insights = VMInsightsOperations( + self._client, self._config, self._serialize, self._deserialize, "2018-11-27-preview" + ) - 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 @@ -69,12 +93,12 @@ 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) -> "MonitorManagementClient": + async def __aenter__(self) -> Self: await self._client.__aenter__() return self diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_11_27_preview/aio/operations/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_11_27_preview/aio/operations/__init__.py index d1c0fc736fe2..a844cbb1eb3b 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_11_27_preview/aio/operations/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_11_27_preview/aio/operations/__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 ._vm_insights_operations import VMInsightsOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._vm_insights_operations import VMInsightsOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ "VMInsightsOperations", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_11_27_preview/aio/operations/_vm_insights_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_11_27_preview/aio/operations/_vm_insights_operations.py index 76e316d50cb4..8dc11b81539c 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_11_27_preview/aio/operations/_vm_insights_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_11_27_preview/aio/operations/_vm_insights_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,7 @@ # 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 ( @@ -17,16 +17,18 @@ 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_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._vm_insights_operations import build_get_onboarding_status_request +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -49,6 +51,7 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace_async async def get_onboarding_status(self, resource_uri: str, **kwargs: Any) -> _models.VMInsightsOnboardingStatus: @@ -57,12 +60,11 @@ async def get_onboarding_status(self, resource_uri: str, **kwargs: Any) -> _mode :param resource_uri: The fully qualified Azure Resource manager identifier of the resource, or scope, whose status to retrieve. Required. :type resource_uri: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: VMInsightsOnboardingStatus or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_11_27_preview.models.VMInsightsOnboardingStatus :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -73,22 +75,22 @@ async def get_onboarding_status(self, resource_uri: str, **kwargs: Any) -> _mode _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2018-11-27-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2018-11-27-preview") + ) cls: ClsType[_models.VMInsightsOnboardingStatus] = kwargs.pop("cls", None) - request = build_get_onboarding_status_request( + _request = build_get_onboarding_status_request( resource_uri=resource_uri, api_version=api_version, - template_url=self.get_onboarding_status.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -98,13 +100,9 @@ async def get_onboarding_status(self, resource_uri: str, **kwargs: Any) -> _mode error = self._deserialize.failsafe_deserialize(_models.ResponseWithError, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("VMInsightsOnboardingStatus", pipeline_response) + deserialized = self._deserialize("VMInsightsOnboardingStatus", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get_onboarding_status.metadata = { - "url": "/{resourceUri}/providers/Microsoft.Insights/vmInsightsOnboardingStatuses/default" - } + return deserialized # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_11_27_preview/models/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_11_27_preview/models/__init__.py index 1e469b651214..cbc000829137 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_11_27_preview/models/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_11_27_preview/models/__init__.py @@ -5,18 +5,29 @@ # 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 DataContainer -from ._models_py3 import Error -from ._models_py3 import ProxyResource -from ._models_py3 import ResponseWithError -from ._models_py3 import VMInsightsOnboardingStatus -from ._models_py3 import WorkspaceInfo +from typing import TYPE_CHECKING -from ._monitor_management_client_enums import DataStatus -from ._monitor_management_client_enums import OnboardingStatus +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models_py3 import ( # type: ignore + DataContainer, + Error, + ProxyResource, + ResponseWithError, + VMInsightsOnboardingStatus, + WorkspaceInfo, +) + +from ._monitor_management_client_enums import ( # type: ignore + DataStatus, + OnboardingStatus, +) from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ @@ -29,5 +40,5 @@ "DataStatus", "OnboardingStatus", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_11_27_preview/models/_models_py3.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_11_27_preview/models/_models_py3.py index e3eac8d03fea..758926d478be 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_11_27_preview/models/_models_py3.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_11_27_preview/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. @@ -12,14 +11,13 @@ from ... import _serialization if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from .. import models as _models class DataContainer(_serialization.Model): """Information about a container with data for a given resource. - 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 workspace: Log Analytics workspace information. Required. :vartype workspace: ~azure.mgmt.monitor.v2018_11_27_preview.models.WorkspaceInfo @@ -45,7 +43,7 @@ def __init__(self, *, workspace: "_models.WorkspaceInfo", **kwargs: Any) -> None class Error(_serialization.Model): """Error details. - 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 code: Error code identifying the specific error. Required. :vartype code: str @@ -110,7 +108,7 @@ def __init__(self, **kwargs: Any) -> None: class ResponseWithError(_serialization.Model): """An error response from the API. - 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 error: Error information. Required. :vartype error: ~azure.mgmt.monitor.v2018_11_27_preview.models.Error @@ -211,7 +209,7 @@ def __init__( class WorkspaceInfo(_serialization.Model): """Information about a Log Analytics Workspace. - 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: Azure Resource Manager identifier of the Log Analytics Workspace. Required. :vartype id: str diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_11_27_preview/operations/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_11_27_preview/operations/__init__.py index d1c0fc736fe2..a844cbb1eb3b 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_11_27_preview/operations/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_11_27_preview/operations/__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 ._vm_insights_operations import VMInsightsOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._vm_insights_operations import VMInsightsOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ "VMInsightsOperations", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_11_27_preview/operations/_vm_insights_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_11_27_preview/operations/_vm_insights_operations.py index acf14093a9bb..2a51fed97c67 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_11_27_preview/operations/_vm_insights_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_11_27_preview/operations/_vm_insights_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,7 @@ # 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 ( @@ -17,16 +17,18 @@ map_error, ) 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 +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -49,7 +51,7 @@ def build_get_onboarding_status_request(resource_uri: str, **kwargs: Any) -> Htt "resourceUri": _SERIALIZER.url("resource_uri", resource_uri, "str", skip_quote=True), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -78,6 +80,7 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def get_onboarding_status(self, resource_uri: str, **kwargs: Any) -> _models.VMInsightsOnboardingStatus: @@ -86,12 +89,11 @@ def get_onboarding_status(self, resource_uri: str, **kwargs: Any) -> _models.VMI :param resource_uri: The fully qualified Azure Resource manager identifier of the resource, or scope, whose status to retrieve. Required. :type resource_uri: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: VMInsightsOnboardingStatus or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2018_11_27_preview.models.VMInsightsOnboardingStatus :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -102,22 +104,22 @@ def get_onboarding_status(self, resource_uri: str, **kwargs: Any) -> _models.VMI _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2018-11-27-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2018-11-27-preview") + ) cls: ClsType[_models.VMInsightsOnboardingStatus] = kwargs.pop("cls", None) - request = build_get_onboarding_status_request( + _request = build_get_onboarding_status_request( resource_uri=resource_uri, api_version=api_version, - template_url=self.get_onboarding_status.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -127,13 +129,9 @@ def get_onboarding_status(self, resource_uri: str, **kwargs: Any) -> _models.VMI error = self._deserialize.failsafe_deserialize(_models.ResponseWithError, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("VMInsightsOnboardingStatus", pipeline_response) + deserialized = self._deserialize("VMInsightsOnboardingStatus", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get_onboarding_status.metadata = { - "url": "/{resourceUri}/providers/Microsoft.Insights/vmInsightsOnboardingStatuses/default" - } + return deserialized # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_03_01/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_03_01/__init__.py index 2c7733bfd566..42cc62301757 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_03_01/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_03_01/__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 ._monitor_management_client import MonitorManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._monitor_management_client import MonitorManagementClient # type: ignore from ._version import VERSION __version__ = VERSION try: from ._patch import __all__ as _patch_all - from ._patch import * # 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__ = [ "MonitorManagementClient", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_03_01/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_03_01/_configuration.py index 0e809d339236..5b278b169db5 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_03_01/_configuration.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_03_01/_configuration.py @@ -8,18 +8,16 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy from ._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MonitorManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class MonitorManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for MonitorManagementClient. Note that all parameters used to create this instance are saved as instance @@ -35,7 +33,6 @@ class MonitorManagementClientConfiguration(Configuration): # pylint: disable=to """ def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: - super(MonitorManagementClientConfiguration, self).__init__(**kwargs) api_version: str = kwargs.pop("api_version", "2019-03-01") if credential is None: @@ -48,6 +45,7 @@ def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-monitor/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -56,9 +54,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.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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_03_01/_metadata.json b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_03_01/_metadata.json index 59e413fdad82..a694c1404d78 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_03_01/_metadata.json +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_03_01/_metadata.json @@ -8,10 +8,10 @@ "host_value": "\"https://management.azure.com\"", "parameterized_host_template": null, "azure_arm": true, - "has_lro_operations": false, + "has_public_lro_operations": false, "client_side_validation": false, - "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"sdkcore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMAutoResourceProviderRegistrationPolicy\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}, \"stdlib\": {\"typing_extensions\": [\"Self\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"sdkcore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"AsyncARMAutoResourceProviderRegistrationPolicy\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}, \"stdlib\": {\"typing_extensions\": [\"Self\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "global_parameters": { "sync": { @@ -101,8 +101,8 @@ "credential_scopes": ["https://management.azure.com/.default"], "credential_call_sync": "ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", "credential_call_async": "AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", - "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "sync_imports": "{\"regular\": {\"sdkcore\": {\"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"regular\": {\"sdkcore\": {\"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "operation_groups": { "action_groups": "ActionGroupsOperations", diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_03_01/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_03_01/_monitor_management_client.py index f2e87fc4aa8f..ae49c37dc7a2 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_03_01/_monitor_management_client.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_03_01/_monitor_management_client.py @@ -8,9 +8,12 @@ from copy import deepcopy from typing import Any, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient +from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy from . import models as _models from .._serialization import Deserializer, Serializer @@ -18,11 +21,10 @@ from .operations import ActionGroupsOperations, BaselinesOperations if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MonitorManagementClient: # pylint: disable=client-accepts-api-version-keyword +class MonitorManagementClient: """Monitor Management Client. :ivar action_groups: ActionGroupsOperations operations @@ -50,16 +52,38 @@ def __init__( self._config = MonitorManagementClientConfiguration( credential=credential, subscription_id=subscription_id, **kwargs ) - self._client: ARMPipelineClient = ARMPipelineClient(base_url=base_url, config=self._config, **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), + 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=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.action_groups = ActionGroupsOperations(self._client, self._config, self._serialize, self._deserialize) - self.baselines = BaselinesOperations(self._client, self._config, self._serialize, self._deserialize) + self.action_groups = ActionGroupsOperations( + self._client, self._config, self._serialize, self._deserialize, "2019-03-01" + ) + self.baselines = BaselinesOperations( + self._client, self._config, self._serialize, self._deserialize, "2019-03-01" + ) - 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 @@ -79,12 +103,12 @@ 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) -> None: self._client.close() - def __enter__(self) -> "MonitorManagementClient": + def __enter__(self) -> Self: self._client.__enter__() return self diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_03_01/_vendor.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_03_01/_vendor.py deleted file mode 100644 index bd0df84f5319..000000000000 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_03_01/_vendor.py +++ /dev/null @@ -1,30 +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 typing import List, cast - -from azure.core.pipeline.transport import HttpRequest - - -def _convert_request(request, files=None): - data = request.content if not files else None - request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) - if files: - request.set_formdata_body(files) - return request - - -def _format_url_section(template, **kwargs): - components = template.split("/") - while components: - try: - return template.format(**kwargs) - except KeyError as key: - # Need the cast, as for some reasons "split" is typed as list[str | Any] - formatted_components = cast(List[str], template.split("/")) - components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] - template = "/".join(components) diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_03_01/_version.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_03_01/_version.py index 394ee7c0c03c..e5754a47ce68 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_03_01/_version.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_03_01/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "6.0.2" +VERSION = "1.0.0b1" diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_03_01/aio/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_03_01/aio/__init__.py index 2c151bb41c19..3df30ff42149 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_03_01/aio/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_03_01/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 ._monitor_management_client import MonitorManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._monitor_management_client import MonitorManagementClient # type: ignore try: from ._patch import __all__ as _patch_all - from ._patch import * # 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__ = [ "MonitorManagementClient", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_03_01/aio/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_03_01/aio/_configuration.py index 62614c9a0551..936ff51ca64f 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_03_01/aio/_configuration.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_03_01/aio/_configuration.py @@ -8,18 +8,16 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy from .._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MonitorManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class MonitorManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for MonitorManagementClient. Note that all parameters used to create this instance are saved as instance @@ -35,7 +33,6 @@ class MonitorManagementClientConfiguration(Configuration): # pylint: disable=to """ def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: - super(MonitorManagementClientConfiguration, self).__init__(**kwargs) api_version: str = kwargs.pop("api_version", "2019-03-01") if credential is None: @@ -48,6 +45,7 @@ def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **k self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-monitor/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -56,9 +54,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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_03_01/aio/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_03_01/aio/_monitor_management_client.py index 362ffeb00568..a7e6b652d90a 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_03_01/aio/_monitor_management_client.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_03_01/aio/_monitor_management_client.py @@ -8,9 +8,12 @@ from copy import deepcopy from typing import Any, Awaitable, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient +from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy from .. import models as _models from ..._serialization import Deserializer, Serializer @@ -18,11 +21,10 @@ from .operations import ActionGroupsOperations, BaselinesOperations if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MonitorManagementClient: # pylint: disable=client-accepts-api-version-keyword +class MonitorManagementClient: """Monitor Management Client. :ivar action_groups: ActionGroupsOperations operations @@ -50,16 +52,40 @@ def __init__( self._config = MonitorManagementClientConfiguration( credential=credential, subscription_id=subscription_id, **kwargs ) - self._client: AsyncARMPipelineClient = AsyncARMPipelineClient(base_url=base_url, config=self._config, **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=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.action_groups = ActionGroupsOperations(self._client, self._config, self._serialize, self._deserialize) - self.baselines = BaselinesOperations(self._client, self._config, self._serialize, self._deserialize) + self.action_groups = ActionGroupsOperations( + self._client, self._config, self._serialize, self._deserialize, "2019-03-01" + ) + self.baselines = BaselinesOperations( + self._client, self._config, self._serialize, self._deserialize, "2019-03-01" + ) - 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 @@ -79,12 +105,12 @@ 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) -> "MonitorManagementClient": + async def __aenter__(self) -> Self: await self._client.__aenter__() return self diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_03_01/aio/operations/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_03_01/aio/operations/__init__.py index ea540c4b7b93..bc857528406a 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_03_01/aio/operations/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_03_01/aio/operations/__init__.py @@ -5,17 +5,23 @@ # 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 ._action_groups_operations import ActionGroupsOperations -from ._baselines_operations import BaselinesOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._action_groups_operations import ActionGroupsOperations # type: ignore +from ._baselines_operations import BaselinesOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ "ActionGroupsOperations", "BaselinesOperations", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_03_01/aio/operations/_action_groups_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_03_01/aio/operations/_action_groups_operations.py index 6ae5cced3975..123c9f7a3b0d 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_03_01/aio/operations/_action_groups_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_03_01/aio/operations/_action_groups_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload import urllib.parse @@ -19,15 +20,13 @@ 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 ...operations._action_groups_operations import ( build_create_or_update_request, build_delete_request, @@ -38,6 +37,10 @@ build_update_request, ) +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -60,6 +63,7 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @overload async def create_or_update( @@ -83,7 +87,6 @@ async def create_or_update( :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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2019_03_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -94,7 +97,7 @@ async def create_or_update( self, resource_group_name: str, action_group_name: str, - action_group: IO, + action_group: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -107,11 +110,10 @@ async def create_or_update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group: The action group to create or use for the update. Required. - :type action_group: IO + :type action_group: 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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2019_03_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -122,7 +124,7 @@ async def create_or_update( self, resource_group_name: str, action_group_name: str, - action_group: Union[_models.ActionGroupResource, IO], + action_group: Union[_models.ActionGroupResource, IO[bytes]], **kwargs: Any ) -> _models.ActionGroupResource: """Create a new action group or update an existing one. @@ -133,17 +135,13 @@ async def create_or_update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group: The action group to create or use for the update. Is either a - ActionGroupResource type or a IO type. Required. - :type action_group: ~azure.mgmt.monitor.v2019_03_01.models.ActionGroupResource 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 + ActionGroupResource type or a IO[bytes] type. Required. + :type action_group: ~azure.mgmt.monitor.v2019_03_01.models.ActionGroupResource or IO[bytes] :return: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2019_03_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -154,19 +152,19 @@ async def create_or_update( _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", "2019-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2019-03-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ActionGroupResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(action_group, (IO, bytes)): + if isinstance(action_group, (IOBase, bytes)): _content = action_group else: _json = self._serialize.body(action_group, "ActionGroupResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, action_group_name=action_group_name, subscription_id=self._config.subscription_id, @@ -174,16 +172,14 @@ async def create_or_update( 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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -193,21 +189,13 @@ async def create_or_update( 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("ActionGroupResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("ActionGroupResource", pipeline_response) + deserialized = self._deserialize("ActionGroupResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/actionGroups/{actionGroupName}" - } - @distributed_trace_async async def get(self, resource_group_name: str, action_group_name: str, **kwargs: Any) -> _models.ActionGroupResource: """Get an action group. @@ -217,12 +205,11 @@ async def get(self, resource_group_name: str, action_group_name: str, **kwargs: :type resource_group_name: str :param action_group_name: The name of the action group. Required. :type action_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2019_03_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -233,24 +220,22 @@ async def get(self, resource_group_name: str, action_group_name: str, **kwargs: _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2019-03-01")) cls: ClsType[_models.ActionGroupResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, action_group_name=action_group_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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -260,21 +245,15 @@ async def get(self, resource_group_name: str, action_group_name: str, **kwargs: error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ActionGroupResource", pipeline_response) + deserialized = self._deserialize("ActionGroupResource", 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.insights/actionGroups/{actionGroupName}" - } + return deserialized # type: ignore @distributed_trace_async - async def delete( # pylint: disable=inconsistent-return-statements - self, resource_group_name: str, action_group_name: str, **kwargs: Any - ) -> None: + async def delete(self, resource_group_name: str, action_group_name: str, **kwargs: Any) -> None: """Delete an action group. :param resource_group_name: The name of the resource group. The name is case insensitive. @@ -282,12 +261,11 @@ async def delete( # pylint: disable=inconsistent-return-statements :type resource_group_name: str :param action_group_name: The name of the action group. Required. :type action_group_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, @@ -298,24 +276,22 @@ async def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2019-03-01")) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, action_group_name=action_group_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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -326,11 +302,7 @@ async def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/actionGroups/{actionGroupName}" - } + return cls(pipeline_response, None, {}) # type: ignore @overload async def update( @@ -354,7 +326,6 @@ async def update( :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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2019_03_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -365,7 +336,7 @@ async def update( self, resource_group_name: str, action_group_name: str, - action_group_patch: IO, + action_group_patch: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -378,11 +349,10 @@ async def update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group_patch: Parameters supplied to the operation. Required. - :type action_group_patch: IO + :type action_group_patch: 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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2019_03_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -393,7 +363,7 @@ async def update( self, resource_group_name: str, action_group_name: str, - action_group_patch: Union[_models.ActionGroupPatchBody, IO], + action_group_patch: Union[_models.ActionGroupPatchBody, IO[bytes]], **kwargs: Any ) -> _models.ActionGroupResource: """Updates an existing action group's tags. To update other fields use the CreateOrUpdate method. @@ -404,17 +374,14 @@ async def update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group_patch: Parameters supplied to the operation. Is either a - ActionGroupPatchBody type or a IO type. Required. - :type action_group_patch: ~azure.mgmt.monitor.v2019_03_01.models.ActionGroupPatchBody 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 + ActionGroupPatchBody type or a IO[bytes] type. Required. + :type action_group_patch: ~azure.mgmt.monitor.v2019_03_01.models.ActionGroupPatchBody or + IO[bytes] :return: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2019_03_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -425,19 +392,19 @@ async def update( _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", "2019-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2019-03-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ActionGroupResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(action_group_patch, (IO, bytes)): + if isinstance(action_group_patch, (IOBase, bytes)): _content = action_group_patch else: _json = self._serialize.body(action_group_patch, "ActionGroupPatchBody") - request = build_update_request( + _request = build_update_request( resource_group_name=resource_group_name, action_group_name=action_group_name, subscription_id=self._config.subscription_id, @@ -445,16 +412,14 @@ async def update( 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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -464,22 +429,17 @@ async def update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ActionGroupResource", pipeline_response) + deserialized = self._deserialize("ActionGroupResource", 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.insights/actionGroups/{actionGroupName}" - } + return deserialized # type: ignore @distributed_trace def list_by_subscription_id(self, **kwargs: Any) -> AsyncIterable["_models.ActionGroupResource"]: """Get a list of all action groups in a subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ActionGroupResource or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.monitor.v2019_03_01.models.ActionGroupResource] @@ -488,10 +448,10 @@ def list_by_subscription_id(self, **kwargs: Any) -> AsyncIterable["_models.Actio _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2019-03-01")) cls: ClsType[_models.ActionGroupList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -502,15 +462,13 @@ def list_by_subscription_id(self, **kwargs: Any) -> AsyncIterable["_models.Actio def prepare_request(next_link=None): if not next_link: - request = build_list_by_subscription_id_request( + _request = build_list_by_subscription_id_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_subscription_id.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -521,14 +479,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("ActionGroupList", pipeline_response) @@ -538,11 +495,11 @@ async def extract_data(pipeline_response): return None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -555,10 +512,6 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_by_subscription_id.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/microsoft.insights/actionGroups" - } - @distributed_trace def list_by_resource_group( self, resource_group_name: str, **kwargs: Any @@ -568,7 +521,6 @@ def list_by_resource_group( :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ActionGroupResource or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.monitor.v2019_03_01.models.ActionGroupResource] @@ -577,10 +529,10 @@ def list_by_resource_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2019-03-01")) cls: ClsType[_models.ActionGroupList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -591,16 +543,14 @@ 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_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -611,14 +561,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("ActionGroupList", pipeline_response) @@ -628,11 +577,11 @@ async def extract_data(pipeline_response): return None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -645,12 +594,8 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/actionGroups" - } - @overload - async def enable_receiver( # pylint: disable=inconsistent-return-statements + async def enable_receiver( self, resource_group_name: str, action_group_name: str, @@ -672,18 +617,17 @@ async def enable_receiver( # pylint: disable=inconsistent-return-statements :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: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def enable_receiver( # pylint: disable=inconsistent-return-statements + async def enable_receiver( self, resource_group_name: str, action_group_name: str, - enable_request: IO, + enable_request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -697,22 +641,21 @@ async def enable_receiver( # pylint: disable=inconsistent-return-statements :param action_group_name: The name of the action group. Required. :type action_group_name: str :param enable_request: The receiver to re-enable. Required. - :type enable_request: IO + :type enable_request: 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: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async - async def enable_receiver( # pylint: disable=inconsistent-return-statements + async def enable_receiver( self, resource_group_name: str, action_group_name: str, - enable_request: Union[_models.EnableRequest, IO], + enable_request: Union[_models.EnableRequest, IO[bytes]], **kwargs: Any ) -> None: """Enable a receiver in an action group. This changes the receiver's status from Disabled to @@ -723,18 +666,14 @@ async def enable_receiver( # pylint: disable=inconsistent-return-statements :type resource_group_name: str :param action_group_name: The name of the action group. Required. :type action_group_name: str - :param enable_request: The receiver to re-enable. Is either a EnableRequest type or a IO type. - Required. - :type enable_request: ~azure.mgmt.monitor.v2019_03_01.models.EnableRequest 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 + :param enable_request: The receiver to re-enable. Is either a EnableRequest type or a IO[bytes] + type. Required. + :type enable_request: ~azure.mgmt.monitor.v2019_03_01.models.EnableRequest or IO[bytes] :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, @@ -745,19 +684,19 @@ async def enable_receiver( # pylint: disable=inconsistent-return-statements _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", "2019-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2019-03-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[None] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(enable_request, (IO, bytes)): + if isinstance(enable_request, (IOBase, bytes)): _content = enable_request else: _json = self._serialize.body(enable_request, "EnableRequest") - request = build_enable_receiver_request( + _request = build_enable_receiver_request( resource_group_name=resource_group_name, action_group_name=action_group_name, subscription_id=self._config.subscription_id, @@ -765,16 +704,14 @@ async def enable_receiver( # pylint: disable=inconsistent-return-statements content_type=content_type, json=_json, content=_content, - template_url=self.enable_receiver.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -785,8 +722,4 @@ async def enable_receiver( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - enable_receiver.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/actionGroups/{actionGroupName}/subscribe" - } + return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_03_01/aio/operations/_baselines_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_03_01/aio/operations/_baselines_operations.py index abda0768b7b3..c42ee8aa6164 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_03_01/aio/operations/_baselines_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_03_01/aio/operations/_baselines_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +6,7 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- import datetime +import sys from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar, Union import urllib.parse @@ -20,16 +20,18 @@ 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 ...operations._baselines_operations import build_list_request +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -52,6 +54,7 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list( @@ -95,17 +98,16 @@ def list( eq 'a1' and B eq 'b1' and C eq '*' or B = 'b2'** This is invalid because the logical or operator cannot separate two different metadata names. - Return all time series where A = a1, B = b1 and C = c1: **$filter=A eq 'a1' and B eq 'b1' and C eq 'c1'** - Return all time series - where A = a1 **$filter=A eq 'a1' and B eq '\ *' and C eq '*\ '**. Special case: When dimension - name or dimension value uses round brackets. Eg: When dimension name is **dim (test) 1** - Instead of using $filter= "dim (test) 1 eq '\ *' " use **$filter= "dim %2528test%2529 1 eq '*\ - ' "\ ** When dimension name is **\ dim (test) 3\ ** and dimension value is **\ dim3 (test) val\ - ** Instead of using $filter= "dim (test) 3 eq 'dim3 (test) val' " use **\ $filter= "dim - %2528test%2529 3 eq 'dim3 %2528test%2529 val' "**. Default value is None. + where A = a1 **$filter=A eq 'a1' and B eq '\\ *' and C eq '*\\ '**. Special case: When + dimension name or dimension value uses round brackets. Eg: When dimension name is **dim (test) + 1** Instead of using $filter= "dim (test) 1 eq '\\ *' " use **$filter= "dim %2528test%2529 1 eq + '*\\ ' "\\ ** When dimension name is **\\ dim (test) 3\\ ** and dimension value is **\\ dim3 + (test) val\\ ** Instead of using $filter= "dim (test) 3 eq 'dim3 (test) val' " use **\\ + $filter= "dim %2528test%2529 3 eq 'dim3 %2528test%2529 val' "**. Default value is None. :type filter: str :param result_type: Allows retrieving only metadata of the baseline. On data request all information is retrieved. Known values are: "Data" and "Metadata". Default value is None. :type result_type: str or ~azure.mgmt.monitor.v2019_03_01.models.ResultType - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either SingleMetricBaseline or the result of cls(response) :rtype: @@ -115,10 +117,10 @@ def list( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2019-03-01")) cls: ClsType[_models.MetricBaselinesResponse] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -129,7 +131,7 @@ def list( def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( resource_uri=resource_uri, metricnames=metricnames, metricnamespace=metricnamespace, @@ -140,12 +142,10 @@ def prepare_request(next_link=None): filter=filter, result_type=result_type, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -156,14 +156,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("MetricBaselinesResponse", pipeline_response) @@ -173,11 +172,11 @@ async def extract_data(pipeline_response): return None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -189,5 +188,3 @@ async def get_next(next_link=None): return pipeline_response return AsyncItemPaged(get_next, extract_data) - - list.metadata = {"url": "/{resourceUri}/providers/Microsoft.Insights/metricBaselines"} diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_03_01/models/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_03_01/models/__init__.py index a5d67150b91c..661c58bc948c 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_03_01/models/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_03_01/models/__init__.py @@ -5,35 +5,46 @@ # 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 ActionGroupList -from ._models_py3 import ActionGroupPatchBody -from ._models_py3 import ActionGroupResource -from ._models_py3 import ArmRoleReceiver -from ._models_py3 import AutomationRunbookReceiver -from ._models_py3 import AzureAppPushReceiver -from ._models_py3 import AzureFunctionReceiver -from ._models_py3 import AzureResource -from ._models_py3 import BaselineMetadata -from ._models_py3 import EmailReceiver -from ._models_py3 import EnableRequest -from ._models_py3 import ErrorResponse -from ._models_py3 import ItsmReceiver -from ._models_py3 import LogicAppReceiver -from ._models_py3 import MetricBaselinesResponse -from ._models_py3 import MetricSingleDimension -from ._models_py3 import SingleBaseline -from ._models_py3 import SingleMetricBaseline -from ._models_py3 import SmsReceiver -from ._models_py3 import TimeSeriesBaseline -from ._models_py3 import VoiceReceiver -from ._models_py3 import WebhookReceiver +from typing import TYPE_CHECKING -from ._monitor_management_client_enums import BaselineSensitivity -from ._monitor_management_client_enums import ReceiverStatus -from ._monitor_management_client_enums import ResultType +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models_py3 import ( # type: ignore + ActionGroupList, + ActionGroupPatchBody, + ActionGroupResource, + ArmRoleReceiver, + AutomationRunbookReceiver, + AzureAppPushReceiver, + AzureFunctionReceiver, + AzureResource, + BaselineMetadata, + EmailReceiver, + EnableRequest, + ErrorResponse, + ItsmReceiver, + LogicAppReceiver, + MetricBaselinesResponse, + MetricSingleDimension, + SingleBaseline, + SingleMetricBaseline, + SmsReceiver, + TimeSeriesBaseline, + VoiceReceiver, + WebhookReceiver, +) + +from ._monitor_management_client_enums import ( # type: ignore + BaselineSensitivity, + ReceiverStatus, + ResultType, +) from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ @@ -63,5 +74,5 @@ "ReceiverStatus", "ResultType", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_03_01/models/_models_py3.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_03_01/models/_models_py3.py index 79e3bcc35e06..bdedf28577ed 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_03_01/models/_models_py3.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_03_01/models/_models_py3.py @@ -1,5 +1,5 @@ -# coding=utf-8 # 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. @@ -13,7 +13,6 @@ from ... import _serialization if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from .. import models as _models @@ -82,7 +81,7 @@ class AzureResource(_serialization.Model): 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: Azure resource Id. :vartype id: str @@ -126,12 +125,12 @@ def __init__(self, *, location: str, tags: Optional[Dict[str, str]] = None, **kw self.tags = tags -class ActionGroupResource(AzureResource): # pylint: disable=too-many-instance-attributes +class ActionGroupResource(AzureResource): """An action group 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: Azure resource Id. :vartype id: str @@ -285,7 +284,7 @@ def __init__( class ArmRoleReceiver(_serialization.Model): """An arm role receiver. - 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 name of the arm role receiver. Names must be unique across all receivers within an action group. Required. @@ -326,7 +325,7 @@ def __init__(self, *, name: str, role_id: str, use_common_alert_schema: bool = F class AutomationRunbookReceiver(_serialization.Model): """The Azure Automation Runbook notification receiver. - 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 automation_account_id: The Azure automation account Id which holds this runbook and authenticate to Azure resource. Required. @@ -404,7 +403,7 @@ def __init__( class AzureAppPushReceiver(_serialization.Model): """The Azure mobile App push notification receiver. - 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 name of the Azure mobile app push receiver. Names must be unique across all receivers within an action group. Required. @@ -439,7 +438,7 @@ def __init__(self, *, name: str, email_address: str, **kwargs: Any) -> None: class AzureFunctionReceiver(_serialization.Model): """An azure function receiver. - 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 name of the azure function receiver. Names must be unique across all receivers within an action group. Required. @@ -503,7 +502,7 @@ def __init__( class BaselineMetadata(_serialization.Model): """Represents a baseline metadata value. - 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: Name of the baseline metadata. Required. :vartype name: str @@ -538,7 +537,7 @@ class EmailReceiver(_serialization.Model): 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 name: The name of the email receiver. Names must be unique across all receivers within an action group. Required. @@ -585,7 +584,7 @@ def __init__(self, *, name: str, email_address: str, use_common_alert_schema: bo class EnableRequest(_serialization.Model): """Describes a receiver that should be resubscribed. - 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 receiver_name: The name of the receiver to resubscribe. Required. :vartype receiver_name: str @@ -637,7 +636,7 @@ def __init__(self, *, code: Optional[str] = None, message: Optional[str] = None, class ItsmReceiver(_serialization.Model): """An Itsm receiver. - 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 name of the Itsm receiver. Names must be unique across all receivers within an action group. Required. @@ -651,7 +650,7 @@ class ItsmReceiver(_serialization.Model): CreateMultipleWorkItems option will be part of this blob as well. Required. :vartype ticket_configuration: str :ivar region: Region in which workspace resides. Supported - values:'centralindia','japaneast','southeastasia','australiasoutheast','uksouth','westcentralus','canadacentral','eastus','westeurope'. + values:'centralindia','japaneast','southeastasia','australiasoutheast','uksouth','westcentralus','canadacentral','eastus','westeurope'. # pylint: disable=line-too-long Required. :vartype region: str """ @@ -688,7 +687,7 @@ def __init__( CreateMultipleWorkItems option will be part of this blob as well. Required. :paramtype ticket_configuration: str :keyword region: Region in which workspace resides. Supported - values:'centralindia','japaneast','southeastasia','australiasoutheast','uksouth','westcentralus','canadacentral','eastus','westeurope'. + values:'centralindia','japaneast','southeastasia','australiasoutheast','uksouth','westcentralus','canadacentral','eastus','westeurope'. # pylint: disable=line-too-long Required. :paramtype region: str """ @@ -703,7 +702,7 @@ def __init__( class LogicAppReceiver(_serialization.Model): """A logic app receiver. - 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 name of the logic app receiver. Names must be unique across all receivers within an action group. Required. @@ -773,7 +772,7 @@ def __init__(self, *, value: Optional[List["_models.SingleMetricBaseline"]] = No class MetricSingleDimension(_serialization.Model): """The metric dimension name and value. - 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: Name of the dimension. Required. :vartype name: str @@ -806,7 +805,7 @@ def __init__(self, *, name: str, value: str, **kwargs: Any) -> None: class SingleBaseline(_serialization.Model): """The baseline values for a single sensitivity value. - 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 sensitivity: the sensitivity of the baseline. Required. Known values are: "Low", "Medium", and "High". @@ -855,7 +854,7 @@ def __init__( class SingleMetricBaseline(_serialization.Model): """The baseline results of a single metric. - 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: The metric baseline Id. Required. :vartype id: str @@ -943,7 +942,7 @@ class SmsReceiver(_serialization.Model): 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 name: The name of the SMS receiver. Names must be unique across all receivers within an action group. Required. @@ -991,7 +990,7 @@ def __init__(self, *, name: str, country_code: str, phone_number: str, **kwargs: class TimeSeriesBaseline(_serialization.Model): """The baseline values for a single time series. - 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 aggregation: The aggregation type of the metric. Required. :vartype aggregation: str @@ -1052,7 +1051,7 @@ def __init__( class VoiceReceiver(_serialization.Model): """A voice receiver. - 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 name of the voice receiver. Names must be unique across all receivers within an action group. Required. @@ -1094,7 +1093,7 @@ def __init__(self, *, name: str, country_code: str, phone_number: str, **kwargs: class WebhookReceiver(_serialization.Model): """A webhook receiver. - 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 name of the webhook receiver. Names must be unique across all receivers within an action group. Required. diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_03_01/operations/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_03_01/operations/__init__.py index ea540c4b7b93..bc857528406a 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_03_01/operations/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_03_01/operations/__init__.py @@ -5,17 +5,23 @@ # 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 ._action_groups_operations import ActionGroupsOperations -from ._baselines_operations import BaselinesOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._action_groups_operations import ActionGroupsOperations # type: ignore +from ._baselines_operations import BaselinesOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ "ActionGroupsOperations", "BaselinesOperations", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_03_01/operations/_action_groups_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_03_01/operations/_action_groups_operations.py index 1d0be57f94be..ae743a28bc87 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_03_01/operations/_action_groups_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_03_01/operations/_action_groups_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload import urllib.parse @@ -19,16 +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, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -59,7 +62,7 @@ def build_create_or_update_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -94,7 +97,7 @@ def build_get_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -127,7 +130,7 @@ def build_delete_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -161,7 +164,7 @@ def build_update_request( "actionGroupName": _SERIALIZER.url("action_group_name", action_group_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -187,7 +190,7 @@ def build_list_by_subscription_id_request(subscription_id: str, **kwargs: Any) - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -217,7 +220,7 @@ def build_list_by_resource_group_request(resource_group_name: str, subscription_ "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -251,7 +254,7 @@ def build_enable_receiver_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -282,6 +285,7 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @overload def create_or_update( @@ -305,7 +309,6 @@ def create_or_update( :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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2019_03_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -316,7 +319,7 @@ def create_or_update( self, resource_group_name: str, action_group_name: str, - action_group: IO, + action_group: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -329,11 +332,10 @@ def create_or_update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group: The action group to create or use for the update. Required. - :type action_group: IO + :type action_group: 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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2019_03_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -344,7 +346,7 @@ def create_or_update( self, resource_group_name: str, action_group_name: str, - action_group: Union[_models.ActionGroupResource, IO], + action_group: Union[_models.ActionGroupResource, IO[bytes]], **kwargs: Any ) -> _models.ActionGroupResource: """Create a new action group or update an existing one. @@ -355,17 +357,13 @@ def create_or_update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group: The action group to create or use for the update. Is either a - ActionGroupResource type or a IO type. Required. - :type action_group: ~azure.mgmt.monitor.v2019_03_01.models.ActionGroupResource 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 + ActionGroupResource type or a IO[bytes] type. Required. + :type action_group: ~azure.mgmt.monitor.v2019_03_01.models.ActionGroupResource or IO[bytes] :return: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2019_03_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -376,19 +374,19 @@ def create_or_update( _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", "2019-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2019-03-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ActionGroupResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(action_group, (IO, bytes)): + if isinstance(action_group, (IOBase, bytes)): _content = action_group else: _json = self._serialize.body(action_group, "ActionGroupResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, action_group_name=action_group_name, subscription_id=self._config.subscription_id, @@ -396,16 +394,14 @@ def create_or_update( 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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -415,21 +411,13 @@ def create_or_update( 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("ActionGroupResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("ActionGroupResource", pipeline_response) + deserialized = self._deserialize("ActionGroupResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/actionGroups/{actionGroupName}" - } - @distributed_trace def get(self, resource_group_name: str, action_group_name: str, **kwargs: Any) -> _models.ActionGroupResource: """Get an action group. @@ -439,12 +427,11 @@ def get(self, resource_group_name: str, action_group_name: str, **kwargs: Any) - :type resource_group_name: str :param action_group_name: The name of the action group. Required. :type action_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2019_03_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -455,24 +442,22 @@ def get(self, resource_group_name: str, action_group_name: str, **kwargs: Any) - _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2019-03-01")) cls: ClsType[_models.ActionGroupResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, action_group_name=action_group_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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -482,16 +467,12 @@ def get(self, resource_group_name: str, action_group_name: str, **kwargs: Any) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ActionGroupResource", pipeline_response) + deserialized = self._deserialize("ActionGroupResource", 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.insights/actionGroups/{actionGroupName}" - } + return deserialized # type: ignore @distributed_trace def delete( # pylint: disable=inconsistent-return-statements @@ -504,12 +485,11 @@ def delete( # pylint: disable=inconsistent-return-statements :type resource_group_name: str :param action_group_name: The name of the action group. Required. :type action_group_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, @@ -520,24 +500,22 @@ def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2019-03-01")) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, action_group_name=action_group_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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -548,11 +526,7 @@ def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/actionGroups/{actionGroupName}" - } + return cls(pipeline_response, None, {}) # type: ignore @overload def update( @@ -576,7 +550,6 @@ def update( :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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2019_03_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -587,7 +560,7 @@ def update( self, resource_group_name: str, action_group_name: str, - action_group_patch: IO, + action_group_patch: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -600,11 +573,10 @@ def update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group_patch: Parameters supplied to the operation. Required. - :type action_group_patch: IO + :type action_group_patch: 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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2019_03_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -615,7 +587,7 @@ def update( self, resource_group_name: str, action_group_name: str, - action_group_patch: Union[_models.ActionGroupPatchBody, IO], + action_group_patch: Union[_models.ActionGroupPatchBody, IO[bytes]], **kwargs: Any ) -> _models.ActionGroupResource: """Updates an existing action group's tags. To update other fields use the CreateOrUpdate method. @@ -626,17 +598,14 @@ def update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group_patch: Parameters supplied to the operation. Is either a - ActionGroupPatchBody type or a IO type. Required. - :type action_group_patch: ~azure.mgmt.monitor.v2019_03_01.models.ActionGroupPatchBody 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 + ActionGroupPatchBody type or a IO[bytes] type. Required. + :type action_group_patch: ~azure.mgmt.monitor.v2019_03_01.models.ActionGroupPatchBody or + IO[bytes] :return: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2019_03_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -647,19 +616,19 @@ def update( _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", "2019-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2019-03-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ActionGroupResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(action_group_patch, (IO, bytes)): + if isinstance(action_group_patch, (IOBase, bytes)): _content = action_group_patch else: _json = self._serialize.body(action_group_patch, "ActionGroupPatchBody") - request = build_update_request( + _request = build_update_request( resource_group_name=resource_group_name, action_group_name=action_group_name, subscription_id=self._config.subscription_id, @@ -667,16 +636,14 @@ def update( 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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -686,22 +653,17 @@ def update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ActionGroupResource", pipeline_response) + deserialized = self._deserialize("ActionGroupResource", 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.insights/actionGroups/{actionGroupName}" - } + return deserialized # type: ignore @distributed_trace def list_by_subscription_id(self, **kwargs: Any) -> Iterable["_models.ActionGroupResource"]: """Get a list of all action groups in a subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ActionGroupResource or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.monitor.v2019_03_01.models.ActionGroupResource] @@ -710,10 +672,10 @@ def list_by_subscription_id(self, **kwargs: Any) -> Iterable["_models.ActionGrou _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2019-03-01")) cls: ClsType[_models.ActionGroupList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -724,15 +686,13 @@ def list_by_subscription_id(self, **kwargs: Any) -> Iterable["_models.ActionGrou def prepare_request(next_link=None): if not next_link: - request = build_list_by_subscription_id_request( + _request = build_list_by_subscription_id_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_subscription_id.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -743,14 +703,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("ActionGroupList", pipeline_response) @@ -760,11 +719,11 @@ def extract_data(pipeline_response): return None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -777,10 +736,6 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_by_subscription_id.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/microsoft.insights/actionGroups" - } - @distributed_trace def list_by_resource_group( self, resource_group_name: str, **kwargs: Any @@ -790,7 +745,6 @@ def list_by_resource_group( :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ActionGroupResource or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.monitor.v2019_03_01.models.ActionGroupResource] @@ -799,10 +753,10 @@ def list_by_resource_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2019-03-01")) cls: ClsType[_models.ActionGroupList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -813,16 +767,14 @@ 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_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -833,14 +785,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("ActionGroupList", pipeline_response) @@ -850,11 +801,11 @@ def extract_data(pipeline_response): return None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -867,12 +818,8 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/actionGroups" - } - @overload - def enable_receiver( # pylint: disable=inconsistent-return-statements + def enable_receiver( self, resource_group_name: str, action_group_name: str, @@ -894,18 +841,17 @@ def enable_receiver( # pylint: disable=inconsistent-return-statements :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: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def enable_receiver( # pylint: disable=inconsistent-return-statements + def enable_receiver( self, resource_group_name: str, action_group_name: str, - enable_request: IO, + enable_request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -919,11 +865,10 @@ def enable_receiver( # pylint: disable=inconsistent-return-statements :param action_group_name: The name of the action group. Required. :type action_group_name: str :param enable_request: The receiver to re-enable. Required. - :type enable_request: IO + :type enable_request: 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: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -934,7 +879,7 @@ def enable_receiver( # pylint: disable=inconsistent-return-statements self, resource_group_name: str, action_group_name: str, - enable_request: Union[_models.EnableRequest, IO], + enable_request: Union[_models.EnableRequest, IO[bytes]], **kwargs: Any ) -> None: """Enable a receiver in an action group. This changes the receiver's status from Disabled to @@ -945,18 +890,14 @@ def enable_receiver( # pylint: disable=inconsistent-return-statements :type resource_group_name: str :param action_group_name: The name of the action group. Required. :type action_group_name: str - :param enable_request: The receiver to re-enable. Is either a EnableRequest type or a IO type. - Required. - :type enable_request: ~azure.mgmt.monitor.v2019_03_01.models.EnableRequest 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 + :param enable_request: The receiver to re-enable. Is either a EnableRequest type or a IO[bytes] + type. Required. + :type enable_request: ~azure.mgmt.monitor.v2019_03_01.models.EnableRequest or IO[bytes] :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, @@ -967,19 +908,19 @@ def enable_receiver( # pylint: disable=inconsistent-return-statements _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", "2019-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2019-03-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[None] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(enable_request, (IO, bytes)): + if isinstance(enable_request, (IOBase, bytes)): _content = enable_request else: _json = self._serialize.body(enable_request, "EnableRequest") - request = build_enable_receiver_request( + _request = build_enable_receiver_request( resource_group_name=resource_group_name, action_group_name=action_group_name, subscription_id=self._config.subscription_id, @@ -987,16 +928,14 @@ def enable_receiver( # pylint: disable=inconsistent-return-statements content_type=content_type, json=_json, content=_content, - template_url=self.enable_receiver.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1007,8 +946,4 @@ def enable_receiver( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - enable_receiver.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/actionGroups/{actionGroupName}/subscribe" - } + return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_03_01/operations/_baselines_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_03_01/operations/_baselines_operations.py index 126e2ba6d2b0..408f1e221051 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_03_01/operations/_baselines_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_03_01/operations/_baselines_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +6,7 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- import datetime +import sys from typing import Any, Callable, Dict, Iterable, Optional, TypeVar, Union import urllib.parse @@ -20,16 +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, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -62,7 +64,7 @@ def build_list_request( "resourceUri": _SERIALIZER.url("resource_uri", resource_uri, "str", skip_quote=True), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters if metricnames is not None: @@ -107,6 +109,7 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list( @@ -150,17 +153,16 @@ def list( eq 'a1' and B eq 'b1' and C eq '*' or B = 'b2'** This is invalid because the logical or operator cannot separate two different metadata names. - Return all time series where A = a1, B = b1 and C = c1: **$filter=A eq 'a1' and B eq 'b1' and C eq 'c1'** - Return all time series - where A = a1 **$filter=A eq 'a1' and B eq '\ *' and C eq '*\ '**. Special case: When dimension - name or dimension value uses round brackets. Eg: When dimension name is **dim (test) 1** - Instead of using $filter= "dim (test) 1 eq '\ *' " use **$filter= "dim %2528test%2529 1 eq '*\ - ' "\ ** When dimension name is **\ dim (test) 3\ ** and dimension value is **\ dim3 (test) val\ - ** Instead of using $filter= "dim (test) 3 eq 'dim3 (test) val' " use **\ $filter= "dim - %2528test%2529 3 eq 'dim3 %2528test%2529 val' "**. Default value is None. + where A = a1 **$filter=A eq 'a1' and B eq '\\ *' and C eq '*\\ '**. Special case: When + dimension name or dimension value uses round brackets. Eg: When dimension name is **dim (test) + 1** Instead of using $filter= "dim (test) 1 eq '\\ *' " use **$filter= "dim %2528test%2529 1 eq + '*\\ ' "\\ ** When dimension name is **\\ dim (test) 3\\ ** and dimension value is **\\ dim3 + (test) val\\ ** Instead of using $filter= "dim (test) 3 eq 'dim3 (test) val' " use **\\ + $filter= "dim %2528test%2529 3 eq 'dim3 %2528test%2529 val' "**. Default value is None. :type filter: str :param result_type: Allows retrieving only metadata of the baseline. On data request all information is retrieved. Known values are: "Data" and "Metadata". Default value is None. :type result_type: str or ~azure.mgmt.monitor.v2019_03_01.models.ResultType - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either SingleMetricBaseline or the result of cls(response) :rtype: @@ -170,10 +172,10 @@ def list( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-03-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2019-03-01")) cls: ClsType[_models.MetricBaselinesResponse] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -184,7 +186,7 @@ def list( def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( resource_uri=resource_uri, metricnames=metricnames, metricnamespace=metricnamespace, @@ -195,12 +197,10 @@ def prepare_request(next_link=None): filter=filter, result_type=result_type, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -211,14 +211,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("MetricBaselinesResponse", pipeline_response) @@ -228,11 +227,11 @@ def extract_data(pipeline_response): return None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -244,5 +243,3 @@ def get_next(next_link=None): return pipeline_response return ItemPaged(get_next, extract_data) - - list.metadata = {"url": "/{resourceUri}/providers/Microsoft.Insights/metricBaselines"} diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_06_01/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_06_01/__init__.py index 2c7733bfd566..42cc62301757 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_06_01/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_06_01/__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 ._monitor_management_client import MonitorManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._monitor_management_client import MonitorManagementClient # type: ignore from ._version import VERSION __version__ = VERSION try: from ._patch import __all__ as _patch_all - from ._patch import * # 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__ = [ "MonitorManagementClient", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_06_01/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_06_01/_configuration.py index dc401fa09a71..d3793d4ff705 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_06_01/_configuration.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_06_01/_configuration.py @@ -8,18 +8,16 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy from ._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MonitorManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class MonitorManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for MonitorManagementClient. Note that all parameters used to create this instance are saved as instance @@ -35,7 +33,6 @@ class MonitorManagementClientConfiguration(Configuration): # pylint: disable=to """ def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: - super(MonitorManagementClientConfiguration, self).__init__(**kwargs) api_version: str = kwargs.pop("api_version", "2019-06-01") if credential is None: @@ -48,6 +45,7 @@ def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-monitor/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -56,9 +54,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.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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_06_01/_metadata.json b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_06_01/_metadata.json index 662a3ad580f2..fb7683baf45e 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_06_01/_metadata.json +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_06_01/_metadata.json @@ -8,10 +8,10 @@ "host_value": "\"https://management.azure.com\"", "parameterized_host_template": null, "azure_arm": true, - "has_lro_operations": false, + "has_public_lro_operations": false, "client_side_validation": false, - "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"sdkcore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMAutoResourceProviderRegistrationPolicy\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}, \"stdlib\": {\"typing_extensions\": [\"Self\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"sdkcore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"AsyncARMAutoResourceProviderRegistrationPolicy\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}, \"stdlib\": {\"typing_extensions\": [\"Self\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "global_parameters": { "sync": { @@ -101,8 +101,8 @@ "credential_scopes": ["https://management.azure.com/.default"], "credential_call_sync": "ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", "credential_call_async": "AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", - "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "sync_imports": "{\"regular\": {\"sdkcore\": {\"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"regular\": {\"sdkcore\": {\"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "operation_groups": { "action_groups": "ActionGroupsOperations" diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_06_01/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_06_01/_monitor_management_client.py index 5b40269f3683..ec04811a984a 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_06_01/_monitor_management_client.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_06_01/_monitor_management_client.py @@ -8,9 +8,12 @@ from copy import deepcopy from typing import Any, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient +from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy from . import models as _models from .._serialization import Deserializer, Serializer @@ -18,11 +21,10 @@ from .operations import ActionGroupsOperations if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MonitorManagementClient: # pylint: disable=client-accepts-api-version-keyword +class MonitorManagementClient: """Monitor Management Client. :ivar action_groups: ActionGroupsOperations operations @@ -48,15 +50,35 @@ def __init__( self._config = MonitorManagementClientConfiguration( credential=credential, subscription_id=subscription_id, **kwargs ) - self._client: ARMPipelineClient = ARMPipelineClient(base_url=base_url, config=self._config, **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), + 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=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.action_groups = ActionGroupsOperations(self._client, self._config, self._serialize, self._deserialize) + self.action_groups = ActionGroupsOperations( + self._client, self._config, self._serialize, self._deserialize, "2019-06-01" + ) - 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 @@ -76,12 +98,12 @@ 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) -> None: self._client.close() - def __enter__(self) -> "MonitorManagementClient": + def __enter__(self) -> Self: self._client.__enter__() return self diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_06_01/_vendor.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_06_01/_vendor.py deleted file mode 100644 index bd0df84f5319..000000000000 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_06_01/_vendor.py +++ /dev/null @@ -1,30 +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 typing import List, cast - -from azure.core.pipeline.transport import HttpRequest - - -def _convert_request(request, files=None): - data = request.content if not files else None - request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) - if files: - request.set_formdata_body(files) - return request - - -def _format_url_section(template, **kwargs): - components = template.split("/") - while components: - try: - return template.format(**kwargs) - except KeyError as key: - # Need the cast, as for some reasons "split" is typed as list[str | Any] - formatted_components = cast(List[str], template.split("/")) - components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] - template = "/".join(components) diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_06_01/_version.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_06_01/_version.py index 394ee7c0c03c..e5754a47ce68 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_06_01/_version.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_06_01/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "6.0.2" +VERSION = "1.0.0b1" diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_06_01/aio/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_06_01/aio/__init__.py index 2c151bb41c19..3df30ff42149 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_06_01/aio/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_06_01/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 ._monitor_management_client import MonitorManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._monitor_management_client import MonitorManagementClient # type: ignore try: from ._patch import __all__ as _patch_all - from ._patch import * # 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__ = [ "MonitorManagementClient", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_06_01/aio/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_06_01/aio/_configuration.py index 44ead2faf77d..b50f6c4e6770 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_06_01/aio/_configuration.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_06_01/aio/_configuration.py @@ -8,18 +8,16 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy from .._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MonitorManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class MonitorManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for MonitorManagementClient. Note that all parameters used to create this instance are saved as instance @@ -35,7 +33,6 @@ class MonitorManagementClientConfiguration(Configuration): # pylint: disable=to """ def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: - super(MonitorManagementClientConfiguration, self).__init__(**kwargs) api_version: str = kwargs.pop("api_version", "2019-06-01") if credential is None: @@ -48,6 +45,7 @@ def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **k self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-monitor/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -56,9 +54,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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_06_01/aio/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_06_01/aio/_monitor_management_client.py index 9b4f78b0ba81..952898d43009 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_06_01/aio/_monitor_management_client.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_06_01/aio/_monitor_management_client.py @@ -8,9 +8,12 @@ from copy import deepcopy from typing import Any, Awaitable, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient +from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy from .. import models as _models from ..._serialization import Deserializer, Serializer @@ -18,11 +21,10 @@ from .operations import ActionGroupsOperations if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MonitorManagementClient: # pylint: disable=client-accepts-api-version-keyword +class MonitorManagementClient: """Monitor Management Client. :ivar action_groups: ActionGroupsOperations operations @@ -48,15 +50,37 @@ def __init__( self._config = MonitorManagementClientConfiguration( credential=credential, subscription_id=subscription_id, **kwargs ) - self._client: AsyncARMPipelineClient = AsyncARMPipelineClient(base_url=base_url, config=self._config, **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=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.action_groups = ActionGroupsOperations(self._client, self._config, self._serialize, self._deserialize) + self.action_groups = ActionGroupsOperations( + self._client, self._config, self._serialize, self._deserialize, "2019-06-01" + ) - 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 @@ -76,12 +100,12 @@ 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) -> "MonitorManagementClient": + async def __aenter__(self) -> Self: await self._client.__aenter__() return self diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_06_01/aio/operations/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_06_01/aio/operations/__init__.py index 05f0527dc979..410e631e0472 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_06_01/aio/operations/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_06_01/aio/operations/__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 ._action_groups_operations import ActionGroupsOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._action_groups_operations import ActionGroupsOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ "ActionGroupsOperations", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_06_01/aio/operations/_action_groups_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_06_01/aio/operations/_action_groups_operations.py index b3f157b37ce1..ac64a14159f3 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_06_01/aio/operations/_action_groups_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_06_01/aio/operations/_action_groups_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload import urllib.parse @@ -19,15 +20,13 @@ 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 ...operations._action_groups_operations import ( build_create_or_update_request, build_delete_request, @@ -38,6 +37,10 @@ build_update_request, ) +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -60,6 +63,7 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @overload async def create_or_update( @@ -83,7 +87,6 @@ async def create_or_update( :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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2019_06_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -94,7 +97,7 @@ async def create_or_update( self, resource_group_name: str, action_group_name: str, - action_group: IO, + action_group: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -107,11 +110,10 @@ async def create_or_update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group: The action group to create or use for the update. Required. - :type action_group: IO + :type action_group: 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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2019_06_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -122,7 +124,7 @@ async def create_or_update( self, resource_group_name: str, action_group_name: str, - action_group: Union[_models.ActionGroupResource, IO], + action_group: Union[_models.ActionGroupResource, IO[bytes]], **kwargs: Any ) -> _models.ActionGroupResource: """Create a new action group or update an existing one. @@ -133,17 +135,13 @@ async def create_or_update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group: The action group to create or use for the update. Is either a - ActionGroupResource type or a IO type. Required. - :type action_group: ~azure.mgmt.monitor.v2019_06_01.models.ActionGroupResource 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 + ActionGroupResource type or a IO[bytes] type. Required. + :type action_group: ~azure.mgmt.monitor.v2019_06_01.models.ActionGroupResource or IO[bytes] :return: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2019_06_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -154,19 +152,19 @@ async def create_or_update( _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", "2019-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2019-06-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ActionGroupResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(action_group, (IO, bytes)): + if isinstance(action_group, (IOBase, bytes)): _content = action_group else: _json = self._serialize.body(action_group, "ActionGroupResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, action_group_name=action_group_name, subscription_id=self._config.subscription_id, @@ -174,16 +172,14 @@ async def create_or_update( 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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -193,21 +189,13 @@ async def create_or_update( 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("ActionGroupResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("ActionGroupResource", pipeline_response) + deserialized = self._deserialize("ActionGroupResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/actionGroups/{actionGroupName}" - } - @distributed_trace_async async def get(self, resource_group_name: str, action_group_name: str, **kwargs: Any) -> _models.ActionGroupResource: """Get an action group. @@ -217,12 +205,11 @@ async def get(self, resource_group_name: str, action_group_name: str, **kwargs: :type resource_group_name: str :param action_group_name: The name of the action group. Required. :type action_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2019_06_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -233,24 +220,22 @@ async def get(self, resource_group_name: str, action_group_name: str, **kwargs: _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2019-06-01")) cls: ClsType[_models.ActionGroupResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, action_group_name=action_group_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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -260,21 +245,15 @@ async def get(self, resource_group_name: str, action_group_name: str, **kwargs: error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ActionGroupResource", pipeline_response) + deserialized = self._deserialize("ActionGroupResource", 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.insights/actionGroups/{actionGroupName}" - } + return deserialized # type: ignore @distributed_trace_async - async def delete( # pylint: disable=inconsistent-return-statements - self, resource_group_name: str, action_group_name: str, **kwargs: Any - ) -> None: + async def delete(self, resource_group_name: str, action_group_name: str, **kwargs: Any) -> None: """Delete an action group. :param resource_group_name: The name of the resource group. The name is case insensitive. @@ -282,12 +261,11 @@ async def delete( # pylint: disable=inconsistent-return-statements :type resource_group_name: str :param action_group_name: The name of the action group. Required. :type action_group_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, @@ -298,24 +276,22 @@ async def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2019-06-01")) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, action_group_name=action_group_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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -326,11 +302,7 @@ async def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/actionGroups/{actionGroupName}" - } + return cls(pipeline_response, None, {}) # type: ignore @overload async def update( @@ -354,7 +326,6 @@ async def update( :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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2019_06_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -365,7 +336,7 @@ async def update( self, resource_group_name: str, action_group_name: str, - action_group_patch: IO, + action_group_patch: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -378,11 +349,10 @@ async def update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group_patch: Parameters supplied to the operation. Required. - :type action_group_patch: IO + :type action_group_patch: 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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2019_06_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -393,7 +363,7 @@ async def update( self, resource_group_name: str, action_group_name: str, - action_group_patch: Union[_models.ActionGroupPatchBody, IO], + action_group_patch: Union[_models.ActionGroupPatchBody, IO[bytes]], **kwargs: Any ) -> _models.ActionGroupResource: """Updates an existing action group's tags. To update other fields use the CreateOrUpdate method. @@ -404,17 +374,14 @@ async def update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group_patch: Parameters supplied to the operation. Is either a - ActionGroupPatchBody type or a IO type. Required. - :type action_group_patch: ~azure.mgmt.monitor.v2019_06_01.models.ActionGroupPatchBody 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 + ActionGroupPatchBody type or a IO[bytes] type. Required. + :type action_group_patch: ~azure.mgmt.monitor.v2019_06_01.models.ActionGroupPatchBody or + IO[bytes] :return: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2019_06_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -425,19 +392,19 @@ async def update( _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", "2019-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2019-06-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ActionGroupResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(action_group_patch, (IO, bytes)): + if isinstance(action_group_patch, (IOBase, bytes)): _content = action_group_patch else: _json = self._serialize.body(action_group_patch, "ActionGroupPatchBody") - request = build_update_request( + _request = build_update_request( resource_group_name=resource_group_name, action_group_name=action_group_name, subscription_id=self._config.subscription_id, @@ -445,16 +412,14 @@ async def update( 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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -464,22 +429,17 @@ async def update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ActionGroupResource", pipeline_response) + deserialized = self._deserialize("ActionGroupResource", 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.insights/actionGroups/{actionGroupName}" - } + return deserialized # type: ignore @distributed_trace def list_by_subscription_id(self, **kwargs: Any) -> AsyncIterable["_models.ActionGroupResource"]: """Get a list of all action groups in a subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ActionGroupResource or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.monitor.v2019_06_01.models.ActionGroupResource] @@ -488,10 +448,10 @@ def list_by_subscription_id(self, **kwargs: Any) -> AsyncIterable["_models.Actio _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2019-06-01")) cls: ClsType[_models.ActionGroupList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -502,15 +462,13 @@ def list_by_subscription_id(self, **kwargs: Any) -> AsyncIterable["_models.Actio def prepare_request(next_link=None): if not next_link: - request = build_list_by_subscription_id_request( + _request = build_list_by_subscription_id_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_subscription_id.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -521,14 +479,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("ActionGroupList", pipeline_response) @@ -538,11 +495,11 @@ async def extract_data(pipeline_response): return None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -555,10 +512,6 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_by_subscription_id.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/microsoft.insights/actionGroups" - } - @distributed_trace def list_by_resource_group( self, resource_group_name: str, **kwargs: Any @@ -568,7 +521,6 @@ def list_by_resource_group( :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ActionGroupResource or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.monitor.v2019_06_01.models.ActionGroupResource] @@ -577,10 +529,10 @@ def list_by_resource_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2019-06-01")) cls: ClsType[_models.ActionGroupList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -591,16 +543,14 @@ 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_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -611,14 +561,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("ActionGroupList", pipeline_response) @@ -628,11 +577,11 @@ async def extract_data(pipeline_response): return None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -645,12 +594,8 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/actionGroups" - } - @overload - async def enable_receiver( # pylint: disable=inconsistent-return-statements + async def enable_receiver( self, resource_group_name: str, action_group_name: str, @@ -672,18 +617,17 @@ async def enable_receiver( # pylint: disable=inconsistent-return-statements :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: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def enable_receiver( # pylint: disable=inconsistent-return-statements + async def enable_receiver( self, resource_group_name: str, action_group_name: str, - enable_request: IO, + enable_request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -697,22 +641,21 @@ async def enable_receiver( # pylint: disable=inconsistent-return-statements :param action_group_name: The name of the action group. Required. :type action_group_name: str :param enable_request: The receiver to re-enable. Required. - :type enable_request: IO + :type enable_request: 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: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async - async def enable_receiver( # pylint: disable=inconsistent-return-statements + async def enable_receiver( self, resource_group_name: str, action_group_name: str, - enable_request: Union[_models.EnableRequest, IO], + enable_request: Union[_models.EnableRequest, IO[bytes]], **kwargs: Any ) -> None: """Enable a receiver in an action group. This changes the receiver's status from Disabled to @@ -723,18 +666,14 @@ async def enable_receiver( # pylint: disable=inconsistent-return-statements :type resource_group_name: str :param action_group_name: The name of the action group. Required. :type action_group_name: str - :param enable_request: The receiver to re-enable. Is either a EnableRequest type or a IO type. - Required. - :type enable_request: ~azure.mgmt.monitor.v2019_06_01.models.EnableRequest 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 + :param enable_request: The receiver to re-enable. Is either a EnableRequest type or a IO[bytes] + type. Required. + :type enable_request: ~azure.mgmt.monitor.v2019_06_01.models.EnableRequest or IO[bytes] :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, @@ -745,19 +684,19 @@ async def enable_receiver( # pylint: disable=inconsistent-return-statements _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", "2019-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2019-06-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[None] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(enable_request, (IO, bytes)): + if isinstance(enable_request, (IOBase, bytes)): _content = enable_request else: _json = self._serialize.body(enable_request, "EnableRequest") - request = build_enable_receiver_request( + _request = build_enable_receiver_request( resource_group_name=resource_group_name, action_group_name=action_group_name, subscription_id=self._config.subscription_id, @@ -765,16 +704,14 @@ async def enable_receiver( # pylint: disable=inconsistent-return-statements content_type=content_type, json=_json, content=_content, - template_url=self.enable_receiver.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -785,8 +722,4 @@ async def enable_receiver( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - enable_receiver.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/actionGroups/{actionGroupName}/subscribe" - } + return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_06_01/models/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_06_01/models/__init__.py index 2755a8fd3548..2dbaf8484ab5 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_06_01/models/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_06_01/models/__init__.py @@ -5,27 +5,38 @@ # 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 ActionGroupList -from ._models_py3 import ActionGroupPatchBody -from ._models_py3 import ActionGroupResource -from ._models_py3 import ArmRoleReceiver -from ._models_py3 import AutomationRunbookReceiver -from ._models_py3 import AzureAppPushReceiver -from ._models_py3 import AzureFunctionReceiver -from ._models_py3 import AzureResource -from ._models_py3 import EmailReceiver -from ._models_py3 import EnableRequest -from ._models_py3 import ErrorResponse -from ._models_py3 import ItsmReceiver -from ._models_py3 import LogicAppReceiver -from ._models_py3 import SmsReceiver -from ._models_py3 import VoiceReceiver -from ._models_py3 import WebhookReceiver +from typing import TYPE_CHECKING -from ._monitor_management_client_enums import ReceiverStatus +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models_py3 import ( # type: ignore + ActionGroupList, + ActionGroupPatchBody, + ActionGroupResource, + ArmRoleReceiver, + AutomationRunbookReceiver, + AzureAppPushReceiver, + AzureFunctionReceiver, + AzureResource, + EmailReceiver, + EnableRequest, + ErrorResponse, + ItsmReceiver, + LogicAppReceiver, + SmsReceiver, + VoiceReceiver, + WebhookReceiver, +) + +from ._monitor_management_client_enums import ( # type: ignore + ReceiverStatus, +) from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ @@ -47,5 +58,5 @@ "WebhookReceiver", "ReceiverStatus", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_06_01/models/_models_py3.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_06_01/models/_models_py3.py index 2f5b964326a2..0276ddfa49cb 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_06_01/models/_models_py3.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_06_01/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. @@ -12,7 +11,6 @@ from ... import _serialization if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from .. import models as _models @@ -81,7 +79,7 @@ class AzureResource(_serialization.Model): 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: Azure resource Id. :vartype id: str @@ -125,12 +123,12 @@ def __init__(self, *, location: str, tags: Optional[Dict[str, str]] = None, **kw self.tags = tags -class ActionGroupResource(AzureResource): # pylint: disable=too-many-instance-attributes +class ActionGroupResource(AzureResource): """An action group 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: Azure resource Id. :vartype id: str @@ -284,7 +282,7 @@ def __init__( class ArmRoleReceiver(_serialization.Model): """An arm role receiver. - 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 name of the arm role receiver. Names must be unique across all receivers within an action group. Required. @@ -325,7 +323,7 @@ def __init__(self, *, name: str, role_id: str, use_common_alert_schema: bool = F class AutomationRunbookReceiver(_serialization.Model): """The Azure Automation Runbook notification receiver. - 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 automation_account_id: The Azure automation account Id which holds this runbook and authenticate to Azure resource. Required. @@ -403,7 +401,7 @@ def __init__( class AzureAppPushReceiver(_serialization.Model): """The Azure mobile App push notification receiver. - 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 name of the Azure mobile app push receiver. Names must be unique across all receivers within an action group. Required. @@ -438,7 +436,7 @@ def __init__(self, *, name: str, email_address: str, **kwargs: Any) -> None: class AzureFunctionReceiver(_serialization.Model): """An azure function receiver. - 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 name of the azure function receiver. Names must be unique across all receivers within an action group. Required. @@ -504,7 +502,7 @@ class EmailReceiver(_serialization.Model): 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 name: The name of the email receiver. Names must be unique across all receivers within an action group. Required. @@ -551,7 +549,7 @@ def __init__(self, *, name: str, email_address: str, use_common_alert_schema: bo class EnableRequest(_serialization.Model): """Describes a receiver that should be resubscribed. - 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 receiver_name: The name of the receiver to resubscribe. Required. :vartype receiver_name: str @@ -603,7 +601,7 @@ def __init__(self, *, code: Optional[str] = None, message: Optional[str] = None, class ItsmReceiver(_serialization.Model): """An Itsm receiver. - 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 name of the Itsm receiver. Names must be unique across all receivers within an action group. Required. @@ -617,7 +615,7 @@ class ItsmReceiver(_serialization.Model): CreateMultipleWorkItems option will be part of this blob as well. Required. :vartype ticket_configuration: str :ivar region: Region in which workspace resides. Supported - values:'centralindia','japaneast','southeastasia','australiasoutheast','uksouth','westcentralus','canadacentral','eastus','westeurope'. + values:'centralindia','japaneast','southeastasia','australiasoutheast','uksouth','westcentralus','canadacentral','eastus','westeurope'. # pylint: disable=line-too-long Required. :vartype region: str """ @@ -654,7 +652,7 @@ def __init__( CreateMultipleWorkItems option will be part of this blob as well. Required. :paramtype ticket_configuration: str :keyword region: Region in which workspace resides. Supported - values:'centralindia','japaneast','southeastasia','australiasoutheast','uksouth','westcentralus','canadacentral','eastus','westeurope'. + values:'centralindia','japaneast','southeastasia','australiasoutheast','uksouth','westcentralus','canadacentral','eastus','westeurope'. # pylint: disable=line-too-long Required. :paramtype region: str """ @@ -669,7 +667,7 @@ def __init__( class LogicAppReceiver(_serialization.Model): """A logic app receiver. - 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 name of the logic app receiver. Names must be unique across all receivers within an action group. Required. @@ -721,7 +719,7 @@ class SmsReceiver(_serialization.Model): 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 name: The name of the SMS receiver. Names must be unique across all receivers within an action group. Required. @@ -769,7 +767,7 @@ def __init__(self, *, name: str, country_code: str, phone_number: str, **kwargs: class VoiceReceiver(_serialization.Model): """A voice receiver. - 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 name of the voice receiver. Names must be unique across all receivers within an action group. Required. @@ -811,7 +809,7 @@ def __init__(self, *, name: str, country_code: str, phone_number: str, **kwargs: class WebhookReceiver(_serialization.Model): """A webhook receiver. - 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 name of the webhook receiver. Names must be unique across all receivers within an action group. Required. diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_06_01/operations/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_06_01/operations/__init__.py index 05f0527dc979..410e631e0472 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_06_01/operations/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_06_01/operations/__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 ._action_groups_operations import ActionGroupsOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._action_groups_operations import ActionGroupsOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ "ActionGroupsOperations", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_06_01/operations/_action_groups_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_06_01/operations/_action_groups_operations.py index 0fdbc97491bb..1f31b230f90b 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_06_01/operations/_action_groups_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_06_01/operations/_action_groups_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload import urllib.parse @@ -19,16 +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, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -59,7 +62,7 @@ def build_create_or_update_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -94,7 +97,7 @@ def build_get_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -127,7 +130,7 @@ def build_delete_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -161,7 +164,7 @@ def build_update_request( "actionGroupName": _SERIALIZER.url("action_group_name", action_group_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -187,7 +190,7 @@ def build_list_by_subscription_id_request(subscription_id: str, **kwargs: Any) - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -217,7 +220,7 @@ def build_list_by_resource_group_request(resource_group_name: str, subscription_ "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -251,7 +254,7 @@ def build_enable_receiver_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -282,6 +285,7 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @overload def create_or_update( @@ -305,7 +309,6 @@ def create_or_update( :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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2019_06_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -316,7 +319,7 @@ def create_or_update( self, resource_group_name: str, action_group_name: str, - action_group: IO, + action_group: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -329,11 +332,10 @@ def create_or_update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group: The action group to create or use for the update. Required. - :type action_group: IO + :type action_group: 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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2019_06_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -344,7 +346,7 @@ def create_or_update( self, resource_group_name: str, action_group_name: str, - action_group: Union[_models.ActionGroupResource, IO], + action_group: Union[_models.ActionGroupResource, IO[bytes]], **kwargs: Any ) -> _models.ActionGroupResource: """Create a new action group or update an existing one. @@ -355,17 +357,13 @@ def create_or_update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group: The action group to create or use for the update. Is either a - ActionGroupResource type or a IO type. Required. - :type action_group: ~azure.mgmt.monitor.v2019_06_01.models.ActionGroupResource 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 + ActionGroupResource type or a IO[bytes] type. Required. + :type action_group: ~azure.mgmt.monitor.v2019_06_01.models.ActionGroupResource or IO[bytes] :return: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2019_06_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -376,19 +374,19 @@ def create_or_update( _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", "2019-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2019-06-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ActionGroupResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(action_group, (IO, bytes)): + if isinstance(action_group, (IOBase, bytes)): _content = action_group else: _json = self._serialize.body(action_group, "ActionGroupResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, action_group_name=action_group_name, subscription_id=self._config.subscription_id, @@ -396,16 +394,14 @@ def create_or_update( 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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -415,21 +411,13 @@ def create_or_update( 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("ActionGroupResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("ActionGroupResource", pipeline_response) + deserialized = self._deserialize("ActionGroupResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/actionGroups/{actionGroupName}" - } - @distributed_trace def get(self, resource_group_name: str, action_group_name: str, **kwargs: Any) -> _models.ActionGroupResource: """Get an action group. @@ -439,12 +427,11 @@ def get(self, resource_group_name: str, action_group_name: str, **kwargs: Any) - :type resource_group_name: str :param action_group_name: The name of the action group. Required. :type action_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2019_06_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -455,24 +442,22 @@ def get(self, resource_group_name: str, action_group_name: str, **kwargs: Any) - _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2019-06-01")) cls: ClsType[_models.ActionGroupResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, action_group_name=action_group_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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -482,16 +467,12 @@ def get(self, resource_group_name: str, action_group_name: str, **kwargs: Any) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ActionGroupResource", pipeline_response) + deserialized = self._deserialize("ActionGroupResource", 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.insights/actionGroups/{actionGroupName}" - } + return deserialized # type: ignore @distributed_trace def delete( # pylint: disable=inconsistent-return-statements @@ -504,12 +485,11 @@ def delete( # pylint: disable=inconsistent-return-statements :type resource_group_name: str :param action_group_name: The name of the action group. Required. :type action_group_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, @@ -520,24 +500,22 @@ def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2019-06-01")) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, action_group_name=action_group_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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -548,11 +526,7 @@ def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/actionGroups/{actionGroupName}" - } + return cls(pipeline_response, None, {}) # type: ignore @overload def update( @@ -576,7 +550,6 @@ def update( :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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2019_06_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -587,7 +560,7 @@ def update( self, resource_group_name: str, action_group_name: str, - action_group_patch: IO, + action_group_patch: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -600,11 +573,10 @@ def update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group_patch: Parameters supplied to the operation. Required. - :type action_group_patch: IO + :type action_group_patch: 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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2019_06_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -615,7 +587,7 @@ def update( self, resource_group_name: str, action_group_name: str, - action_group_patch: Union[_models.ActionGroupPatchBody, IO], + action_group_patch: Union[_models.ActionGroupPatchBody, IO[bytes]], **kwargs: Any ) -> _models.ActionGroupResource: """Updates an existing action group's tags. To update other fields use the CreateOrUpdate method. @@ -626,17 +598,14 @@ def update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group_patch: Parameters supplied to the operation. Is either a - ActionGroupPatchBody type or a IO type. Required. - :type action_group_patch: ~azure.mgmt.monitor.v2019_06_01.models.ActionGroupPatchBody 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 + ActionGroupPatchBody type or a IO[bytes] type. Required. + :type action_group_patch: ~azure.mgmt.monitor.v2019_06_01.models.ActionGroupPatchBody or + IO[bytes] :return: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2019_06_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -647,19 +616,19 @@ def update( _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", "2019-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2019-06-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ActionGroupResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(action_group_patch, (IO, bytes)): + if isinstance(action_group_patch, (IOBase, bytes)): _content = action_group_patch else: _json = self._serialize.body(action_group_patch, "ActionGroupPatchBody") - request = build_update_request( + _request = build_update_request( resource_group_name=resource_group_name, action_group_name=action_group_name, subscription_id=self._config.subscription_id, @@ -667,16 +636,14 @@ def update( 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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -686,22 +653,17 @@ def update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ActionGroupResource", pipeline_response) + deserialized = self._deserialize("ActionGroupResource", 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.insights/actionGroups/{actionGroupName}" - } + return deserialized # type: ignore @distributed_trace def list_by_subscription_id(self, **kwargs: Any) -> Iterable["_models.ActionGroupResource"]: """Get a list of all action groups in a subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ActionGroupResource or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.monitor.v2019_06_01.models.ActionGroupResource] @@ -710,10 +672,10 @@ def list_by_subscription_id(self, **kwargs: Any) -> Iterable["_models.ActionGrou _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2019-06-01")) cls: ClsType[_models.ActionGroupList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -724,15 +686,13 @@ def list_by_subscription_id(self, **kwargs: Any) -> Iterable["_models.ActionGrou def prepare_request(next_link=None): if not next_link: - request = build_list_by_subscription_id_request( + _request = build_list_by_subscription_id_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_subscription_id.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -743,14 +703,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("ActionGroupList", pipeline_response) @@ -760,11 +719,11 @@ def extract_data(pipeline_response): return None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -777,10 +736,6 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_by_subscription_id.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/microsoft.insights/actionGroups" - } - @distributed_trace def list_by_resource_group( self, resource_group_name: str, **kwargs: Any @@ -790,7 +745,6 @@ def list_by_resource_group( :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ActionGroupResource or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.monitor.v2019_06_01.models.ActionGroupResource] @@ -799,10 +753,10 @@ def list_by_resource_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2019-06-01")) cls: ClsType[_models.ActionGroupList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -813,16 +767,14 @@ 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_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -833,14 +785,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("ActionGroupList", pipeline_response) @@ -850,11 +801,11 @@ def extract_data(pipeline_response): return None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -867,12 +818,8 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/actionGroups" - } - @overload - def enable_receiver( # pylint: disable=inconsistent-return-statements + def enable_receiver( self, resource_group_name: str, action_group_name: str, @@ -894,18 +841,17 @@ def enable_receiver( # pylint: disable=inconsistent-return-statements :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: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def enable_receiver( # pylint: disable=inconsistent-return-statements + def enable_receiver( self, resource_group_name: str, action_group_name: str, - enable_request: IO, + enable_request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -919,11 +865,10 @@ def enable_receiver( # pylint: disable=inconsistent-return-statements :param action_group_name: The name of the action group. Required. :type action_group_name: str :param enable_request: The receiver to re-enable. Required. - :type enable_request: IO + :type enable_request: 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: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -934,7 +879,7 @@ def enable_receiver( # pylint: disable=inconsistent-return-statements self, resource_group_name: str, action_group_name: str, - enable_request: Union[_models.EnableRequest, IO], + enable_request: Union[_models.EnableRequest, IO[bytes]], **kwargs: Any ) -> None: """Enable a receiver in an action group. This changes the receiver's status from Disabled to @@ -945,18 +890,14 @@ def enable_receiver( # pylint: disable=inconsistent-return-statements :type resource_group_name: str :param action_group_name: The name of the action group. Required. :type action_group_name: str - :param enable_request: The receiver to re-enable. Is either a EnableRequest type or a IO type. - Required. - :type enable_request: ~azure.mgmt.monitor.v2019_06_01.models.EnableRequest 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 + :param enable_request: The receiver to re-enable. Is either a EnableRequest type or a IO[bytes] + type. Required. + :type enable_request: ~azure.mgmt.monitor.v2019_06_01.models.EnableRequest or IO[bytes] :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, @@ -967,19 +908,19 @@ def enable_receiver( # pylint: disable=inconsistent-return-statements _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", "2019-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2019-06-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[None] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(enable_request, (IO, bytes)): + if isinstance(enable_request, (IOBase, bytes)): _content = enable_request else: _json = self._serialize.body(enable_request, "EnableRequest") - request = build_enable_receiver_request( + _request = build_enable_receiver_request( resource_group_name=resource_group_name, action_group_name=action_group_name, subscription_id=self._config.subscription_id, @@ -987,16 +928,14 @@ def enable_receiver( # pylint: disable=inconsistent-return-statements content_type=content_type, json=_json, content=_content, - template_url=self.enable_receiver.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1007,8 +946,4 @@ def enable_receiver( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - enable_receiver.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/actionGroups/{actionGroupName}/subscribe" - } + return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/__init__.py index 2c7733bfd566..42cc62301757 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/__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 ._monitor_management_client import MonitorManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._monitor_management_client import MonitorManagementClient # type: ignore from ._version import VERSION __version__ = VERSION try: from ._patch import __all__ as _patch_all - from ._patch import * # 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__ = [ "MonitorManagementClient", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/_configuration.py index 7b27cbdf9da5..e6f5fd6257d1 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/_configuration.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/_configuration.py @@ -8,18 +8,16 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy from ._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MonitorManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class MonitorManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for MonitorManagementClient. Note that all parameters used to create this instance are saved as instance @@ -35,7 +33,6 @@ class MonitorManagementClientConfiguration(Configuration): # pylint: disable=to """ def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: - super(MonitorManagementClientConfiguration, self).__init__(**kwargs) api_version: str = kwargs.pop("api_version", "2019-10-17-preview") if credential is None: @@ -48,6 +45,7 @@ def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-monitor/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -56,9 +54,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.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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/_metadata.json b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/_metadata.json index cd2778252553..41727632ad22 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/_metadata.json +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/_metadata.json @@ -8,10 +8,10 @@ "host_value": "\"https://management.azure.com\"", "parameterized_host_template": null, "azure_arm": true, - "has_lro_operations": true, + "has_public_lro_operations": true, "client_side_validation": false, - "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"sdkcore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMAutoResourceProviderRegistrationPolicy\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}, \"stdlib\": {\"typing_extensions\": [\"Self\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"sdkcore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"AsyncARMAutoResourceProviderRegistrationPolicy\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}, \"stdlib\": {\"typing_extensions\": [\"Self\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "global_parameters": { "sync": { @@ -101,8 +101,8 @@ "credential_scopes": ["https://management.azure.com/.default"], "credential_call_sync": "ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", "credential_call_async": "AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", - "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "sync_imports": "{\"regular\": {\"sdkcore\": {\"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"regular\": {\"sdkcore\": {\"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "operation_groups": { "private_link_scopes": "PrivateLinkScopesOperations", diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/_monitor_management_client.py index 93b667d3b1e3..27fe76576a3c 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/_monitor_management_client.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/_monitor_management_client.py @@ -8,9 +8,12 @@ from copy import deepcopy from typing import Any, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient +from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy from . import models as _models from .._serialization import Deserializer, Serializer @@ -24,11 +27,10 @@ ) if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MonitorManagementClient: # pylint: disable=client-accepts-api-version-keyword +class MonitorManagementClient: """Monitor Management Client. :ivar private_link_scopes: PrivateLinkScopesOperations operations @@ -69,29 +71,47 @@ def __init__( self._config = MonitorManagementClientConfiguration( credential=credential, subscription_id=subscription_id, **kwargs ) - self._client: ARMPipelineClient = ARMPipelineClient(base_url=base_url, config=self._config, **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), + 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=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.private_link_scopes = PrivateLinkScopesOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2019-10-17-preview" ) self.private_link_scope_operation_status = PrivateLinkScopeOperationStatusOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2019-10-17-preview" ) self.private_link_resources = PrivateLinkResourcesOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2019-10-17-preview" ) self.private_endpoint_connections = PrivateEndpointConnectionsOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2019-10-17-preview" ) self.private_link_scoped_resources = PrivateLinkScopedResourcesOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2019-10-17-preview" ) - 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 @@ -111,12 +131,12 @@ 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) -> None: self._client.close() - def __enter__(self) -> "MonitorManagementClient": + def __enter__(self) -> Self: self._client.__enter__() return self diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/_vendor.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/_vendor.py deleted file mode 100644 index bd0df84f5319..000000000000 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/_vendor.py +++ /dev/null @@ -1,30 +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 typing import List, cast - -from azure.core.pipeline.transport import HttpRequest - - -def _convert_request(request, files=None): - data = request.content if not files else None - request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) - if files: - request.set_formdata_body(files) - return request - - -def _format_url_section(template, **kwargs): - components = template.split("/") - while components: - try: - return template.format(**kwargs) - except KeyError as key: - # Need the cast, as for some reasons "split" is typed as list[str | Any] - formatted_components = cast(List[str], template.split("/")) - components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] - template = "/".join(components) diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/_version.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/_version.py index 394ee7c0c03c..e5754a47ce68 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/_version.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "6.0.2" +VERSION = "1.0.0b1" diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/aio/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/aio/__init__.py index 2c151bb41c19..3df30ff42149 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/aio/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/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 ._monitor_management_client import MonitorManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._monitor_management_client import MonitorManagementClient # type: ignore try: from ._patch import __all__ as _patch_all - from ._patch import * # 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__ = [ "MonitorManagementClient", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/aio/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/aio/_configuration.py index fd98a3ea043d..89f60cded8b8 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/aio/_configuration.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/aio/_configuration.py @@ -8,18 +8,16 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy from .._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MonitorManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class MonitorManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for MonitorManagementClient. Note that all parameters used to create this instance are saved as instance @@ -35,7 +33,6 @@ class MonitorManagementClientConfiguration(Configuration): # pylint: disable=to """ def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: - super(MonitorManagementClientConfiguration, self).__init__(**kwargs) api_version: str = kwargs.pop("api_version", "2019-10-17-preview") if credential is None: @@ -48,6 +45,7 @@ def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **k self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-monitor/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -56,9 +54,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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/aio/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/aio/_monitor_management_client.py index 22862094ca05..50f42dd7e062 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/aio/_monitor_management_client.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/aio/_monitor_management_client.py @@ -8,9 +8,12 @@ from copy import deepcopy from typing import Any, Awaitable, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient +from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy from .. import models as _models from ..._serialization import Deserializer, Serializer @@ -24,11 +27,10 @@ ) if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MonitorManagementClient: # pylint: disable=client-accepts-api-version-keyword +class MonitorManagementClient: """Monitor Management Client. :ivar private_link_scopes: PrivateLinkScopesOperations operations @@ -69,29 +71,49 @@ def __init__( self._config = MonitorManagementClientConfiguration( credential=credential, subscription_id=subscription_id, **kwargs ) - self._client: AsyncARMPipelineClient = AsyncARMPipelineClient(base_url=base_url, config=self._config, **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=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.private_link_scopes = PrivateLinkScopesOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2019-10-17-preview" ) self.private_link_scope_operation_status = PrivateLinkScopeOperationStatusOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2019-10-17-preview" ) self.private_link_resources = PrivateLinkResourcesOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2019-10-17-preview" ) self.private_endpoint_connections = PrivateEndpointConnectionsOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2019-10-17-preview" ) self.private_link_scoped_resources = PrivateLinkScopedResourcesOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2019-10-17-preview" ) - 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 @@ -111,12 +133,12 @@ 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) -> "MonitorManagementClient": + async def __aenter__(self) -> Self: await self._client.__aenter__() return self diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/aio/operations/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/aio/operations/__init__.py index 1f7c00746a8d..f529c5b732f2 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/aio/operations/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/aio/operations/__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 ._private_link_scopes_operations import PrivateLinkScopesOperations -from ._private_link_scope_operation_status_operations import PrivateLinkScopeOperationStatusOperations -from ._private_link_resources_operations import PrivateLinkResourcesOperations -from ._private_endpoint_connections_operations import PrivateEndpointConnectionsOperations -from ._private_link_scoped_resources_operations import PrivateLinkScopedResourcesOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._private_link_scopes_operations import PrivateLinkScopesOperations # type: ignore +from ._private_link_scope_operation_status_operations import PrivateLinkScopeOperationStatusOperations # type: ignore +from ._private_link_resources_operations import PrivateLinkResourcesOperations # type: ignore +from ._private_endpoint_connections_operations import PrivateEndpointConnectionsOperations # type: ignore +from ._private_link_scoped_resources_operations import PrivateLinkScopedResourcesOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ @@ -23,5 +29,5 @@ "PrivateEndpointConnectionsOperations", "PrivateLinkScopedResourcesOperations", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/aio/operations/_private_endpoint_connections_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/aio/operations/_private_endpoint_connections_operations.py index 4256bcd0373b..4914b8b73003 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/aio/operations/_private_endpoint_connections_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/aio/operations/_private_endpoint_connections_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,7 +5,9 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload +from io import IOBase +import sys +from typing import Any, AsyncIterable, AsyncIterator, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList @@ -16,12 +17,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 @@ -29,7 +31,6 @@ 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, @@ -37,6 +38,10 @@ build_list_by_private_link_scope_request, ) +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -59,6 +64,7 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace_async async def get( @@ -73,12 +79,11 @@ async def get( :type scope_name: str :param private_endpoint_connection_name: The name of the private endpoint connection. Required. :type private_endpoint_connection_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: PrivateEndpointConnection or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2019_10_17.models.PrivateEndpointConnection :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -89,25 +94,25 @@ async def get( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-10-17-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2019-10-17-preview") + ) cls: ClsType[_models.PrivateEndpointConnection] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, scope_name=scope_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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -116,26 +121,22 @@ async def get( map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) + deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response.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.Insights/privateLinkScopes/{scopeName}/privateEndpointConnections/{privateEndpointConnectionName}" - } + return deserialized # type: ignore async def _create_or_update_initial( self, resource_group_name: str, scope_name: str, private_endpoint_connection_name: str, - parameters: Union[_models.PrivateEndpointConnection, IO], + parameters: Union[_models.PrivateEndpointConnection, IO[bytes]], **kwargs: Any - ) -> Optional[_models.PrivateEndpointConnection]: - error_map = { + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -146,19 +147,21 @@ async def _create_or_update_initial( _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", "2019-10-17-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2019-10-17-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Optional[_models.PrivateEndpointConnection]] = kwargs.pop("cls", None) + cls: ClsType[AsyncIterator[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, "PrivateEndpointConnection") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, scope_name=scope_name, private_endpoint_connection_name=private_endpoint_connection_name, @@ -167,36 +170,33 @@ async def _create_or_update_initial( 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) + _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: + 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) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = None - if response.status_code == 200: - deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - _create_or_update_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/privateLinkScopes/{scopeName}/privateEndpointConnections/{privateEndpointConnectionName}" - } + return deserialized # type: ignore @overload async def begin_create_or_update( @@ -223,14 +223,6 @@ async def begin_create_or_update( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of AsyncLROPoller that returns either PrivateEndpointConnection or the result of cls(response) :rtype: @@ -244,7 +236,7 @@ async def begin_create_or_update( resource_group_name: str, scope_name: str, private_endpoint_connection_name: str, - parameters: IO, + parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -259,18 +251,10 @@ async def begin_create_or_update( :param private_endpoint_connection_name: The name of the private endpoint connection. Required. :type private_endpoint_connection_name: str :param parameters: Required. - :type parameters: IO + :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 PrivateEndpointConnection or the result of cls(response) :rtype: @@ -284,7 +268,7 @@ async def begin_create_or_update( resource_group_name: str, scope_name: str, private_endpoint_connection_name: str, - parameters: Union[_models.PrivateEndpointConnection, IO], + parameters: Union[_models.PrivateEndpointConnection, IO[bytes]], **kwargs: Any ) -> AsyncLROPoller[_models.PrivateEndpointConnection]: """Approve or reject a private endpoint connection with a given name. @@ -296,19 +280,8 @@ async def begin_create_or_update( :type scope_name: str :param private_endpoint_connection_name: The name of the private endpoint connection. Required. :type private_endpoint_connection_name: str - :param parameters: Is either a PrivateEndpointConnection type or a IO type. Required. - :type parameters: ~azure.mgmt.monitor.v2019_10_17.models.PrivateEndpointConnection or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. + :param parameters: Is either a PrivateEndpointConnection type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.monitor.v2019_10_17.models.PrivateEndpointConnection or IO[bytes] :return: An instance of AsyncLROPoller that returns either PrivateEndpointConnection or the result of cls(response) :rtype: @@ -318,7 +291,9 @@ async def begin_create_or_update( _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", "2019-10-17-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2019-10-17-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.PrivateEndpointConnection] = kwargs.pop("cls", None) polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) @@ -337,12 +312,13 @@ async def begin_create_or_update( 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("PrivateEndpointConnection", pipeline_response) + deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: @@ -352,22 +328,20 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return AsyncLROPoller.from_continuation_token( + return AsyncLROPoller[_models.PrivateEndpointConnection].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/privateLinkScopes/{scopeName}/privateEndpointConnections/{privateEndpointConnectionName}" - } + return AsyncLROPoller[_models.PrivateEndpointConnection]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) - async def _delete_initial( # pylint: disable=inconsistent-return-statements + async def _delete_initial( self, resource_group_name: str, scope_name: str, private_endpoint_connection_name: str, **kwargs: Any - ) -> None: - error_map = { + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -378,39 +352,44 @@ async def _delete_initial( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-10-17-preview")) - cls: ClsType[None] = kwargs.pop("cls", None) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2019-10-17-preview") + ) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, scope_name=scope_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) + _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _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) raise HttpResponseError(response=response, 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_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/privateLinkScopes/{scopeName}/privateEndpointConnections/{privateEndpointConnectionName}" - } + return deserialized # type: ignore @distributed_trace_async async def begin_delete( @@ -425,14 +404,6 @@ async def begin_delete( :type scope_name: str :param private_endpoint_connection_name: The name of the private endpoint connection. Required. :type private_endpoint_connection_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: @@ -440,13 +411,15 @@ async def begin_delete( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-10-17-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2019-10-17-preview") + ) cls: ClsType[None] = kwargs.pop("cls", None) polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: - raw_result = await self._delete_initial( # type: ignore + raw_result = await self._delete_initial( resource_group_name=resource_group_name, scope_name=scope_name, private_endpoint_connection_name=private_endpoint_connection_name, @@ -456,11 +429,12 @@ async def begin_delete( 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, {}) + return cls(pipeline_response, None, {}) # type: ignore if polling is True: polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) @@ -469,17 +443,13 @@ def get_long_running_output(pipeline_response): # pylint: disable=inconsistent- else: polling_method = polling if cont_token: - return AsyncLROPoller.from_continuation_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(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/privateLinkScopes/{scopeName}/privateEndpointConnections/{privateEndpointConnectionName}" - } + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore @distributed_trace def list_by_private_link_scope( @@ -492,7 +462,6 @@ def list_by_private_link_scope( :type resource_group_name: str :param scope_name: The name of the Azure Monitor PrivateLinkScope resource. Required. :type scope_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: @@ -502,10 +471,12 @@ def list_by_private_link_scope( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-10-17-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2019-10-17-preview") + ) cls: ClsType[_models.PrivateEndpointConnectionListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -516,17 +487,15 @@ def list_by_private_link_scope( def prepare_request(next_link=None): if not next_link: - request = build_list_by_private_link_scope_request( + _request = build_list_by_private_link_scope_request( resource_group_name=resource_group_name, scope_name=scope_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_private_link_scope.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -537,14 +506,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("PrivateEndpointConnectionListResult", pipeline_response) @@ -554,11 +522,11 @@ async def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -569,7 +537,3 @@ async def get_next(next_link=None): return pipeline_response return AsyncItemPaged(get_next, extract_data) - - list_by_private_link_scope.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/privateLinkScopes/{scopeName}/privateEndpointConnections" - } diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/aio/operations/_private_link_resources_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/aio/operations/_private_link_resources_operations.py index a36b124e5166..870429f6fd45 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/aio/operations/_private_link_resources_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/aio/operations/_private_link_resources_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,7 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar import urllib.parse @@ -19,17 +19,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.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_by_private_link_scope_request +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -52,6 +54,7 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list_by_private_link_scope( @@ -64,7 +67,6 @@ def list_by_private_link_scope( :type resource_group_name: str :param scope_name: The name of the Azure Monitor PrivateLinkScope resource. Required. :type scope_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either PrivateLinkResource or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.monitor.v2019_10_17.models.PrivateLinkResource] @@ -73,10 +75,12 @@ def list_by_private_link_scope( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-10-17-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2019-10-17-preview") + ) cls: ClsType[_models.PrivateLinkResourceListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -87,17 +91,15 @@ def list_by_private_link_scope( def prepare_request(next_link=None): if not next_link: - request = build_list_by_private_link_scope_request( + _request = build_list_by_private_link_scope_request( resource_group_name=resource_group_name, scope_name=scope_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_private_link_scope.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -108,14 +110,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("PrivateLinkResourceListResult", pipeline_response) @@ -125,11 +126,11 @@ async def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -141,10 +142,6 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_by_private_link_scope.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/privateLinkScopes/{scopeName}/privateLinkResources" - } - @distributed_trace_async async def get( self, resource_group_name: str, scope_name: str, group_name: str, **kwargs: Any @@ -158,12 +155,11 @@ async def get( :type scope_name: str :param group_name: The name of the private link resource. Required. :type group_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.monitor.v2019_10_17.models.PrivateLinkResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -174,25 +170,25 @@ async def get( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-10-17-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2019-10-17-preview") + ) cls: ClsType[_models.PrivateLinkResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, scope_name=scope_name, group_name=group_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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -201,13 +197,9 @@ async def get( map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize("PrivateLinkResource", pipeline_response) + deserialized = self._deserialize("PrivateLinkResource", pipeline_response.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.Insights/privateLinkScopes/{scopeName}/privateLinkResources/{groupName}" - } + return deserialized # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/aio/operations/_private_link_scope_operation_status_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/aio/operations/_private_link_scope_operation_status_operations.py index 670fdc09b418..fb45f2cf49f1 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/aio/operations/_private_link_scope_operation_status_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/aio/operations/_private_link_scope_operation_status_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,7 @@ # 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 ( @@ -17,21 +17,23 @@ 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_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_scope_operation_status_operations import build_get_request +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class PrivateLinkScopeOperationStatusOperations: +class PrivateLinkScopeOperationStatusOperations: # pylint: disable=name-too-long """ .. warning:: **DO NOT** instantiate this class directly. @@ -49,6 +51,7 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace_async async def get(self, async_operation_id: str, resource_group_name: str, **kwargs: Any) -> _models.OperationStatus: @@ -60,12 +63,11 @@ async def get(self, async_operation_id: str, resource_group_name: str, **kwargs: :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: OperationStatus or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2019_10_17.models.OperationStatus :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -76,24 +78,24 @@ async def get(self, async_operation_id: str, resource_group_name: str, **kwargs: _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-10-17-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2019-10-17-preview") + ) cls: ClsType[_models.OperationStatus] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( async_operation_id=async_operation_id, resource_group_name=resource_group_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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -102,13 +104,9 @@ async def get(self, async_operation_id: str, resource_group_name: str, **kwargs: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize("OperationStatus", pipeline_response) + deserialized = self._deserialize("OperationStatus", 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.insights/privateLinkScopeOperationStatuses/{asyncOperationId}" - } + return deserialized # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/aio/operations/_private_link_scoped_resources_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/aio/operations/_private_link_scoped_resources_operations.py index 66552cbfd75f..f7416f79502e 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/aio/operations/_private_link_scoped_resources_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/aio/operations/_private_link_scoped_resources_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,7 +5,9 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload +from io import IOBase +import sys +from typing import Any, AsyncIterable, AsyncIterator, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList @@ -16,12 +17,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 @@ -29,7 +31,6 @@ from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models -from ..._vendor import _convert_request from ...operations._private_link_scoped_resources_operations import ( build_create_or_update_request, build_delete_request, @@ -37,6 +38,10 @@ build_list_by_private_link_scope_request, ) +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -59,6 +64,7 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace_async async def get(self, resource_group_name: str, scope_name: str, name: str, **kwargs: Any) -> _models.ScopedResource: @@ -71,12 +77,11 @@ async def get(self, resource_group_name: str, scope_name: str, name: str, **kwar :type scope_name: str :param name: The name of the scoped resource object. Required. :type name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ScopedResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2019_10_17.models.ScopedResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -87,25 +92,25 @@ async def get(self, resource_group_name: str, scope_name: str, name: str, **kwar _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-10-17-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2019-10-17-preview") + ) cls: ClsType[_models.ScopedResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, scope_name=scope_name, name=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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -114,26 +119,22 @@ async def get(self, resource_group_name: str, scope_name: str, name: str, **kwar map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize("ScopedResource", pipeline_response) + deserialized = self._deserialize("ScopedResource", 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.Insights/privateLinkScopes/{scopeName}/scopedResources/{name}" - } + return deserialized # type: ignore async def _create_or_update_initial( self, resource_group_name: str, scope_name: str, name: str, - parameters: Union[_models.ScopedResource, IO], + parameters: Union[_models.ScopedResource, IO[bytes]], **kwargs: Any - ) -> Optional[_models.ScopedResource]: - error_map = { + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -144,19 +145,21 @@ async def _create_or_update_initial( _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", "2019-10-17-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2019-10-17-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Optional[_models.ScopedResource]] = kwargs.pop("cls", None) + cls: ClsType[AsyncIterator[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, "ScopedResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, scope_name=scope_name, name=name, @@ -165,39 +168,33 @@ async def _create_or_update_initial( 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) + _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 201, 202]: + 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) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = None - if response.status_code == 200: - deserialized = self._deserialize("ScopedResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("ScopedResource", 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 - - _create_or_update_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/privateLinkScopes/{scopeName}/scopedResources/{name}" - } + return deserialized # type: ignore @overload async def begin_create_or_update( @@ -224,14 +221,6 @@ async def begin_create_or_update( :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 ScopedResource or the result of cls(response) :rtype: @@ -245,7 +234,7 @@ async def begin_create_or_update( resource_group_name: str, scope_name: str, name: str, - parameters: IO, + parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -260,18 +249,10 @@ async def begin_create_or_update( :param name: The name of the scoped resource object. Required. :type name: str :param parameters: Required. - :type parameters: IO + :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 ScopedResource or the result of cls(response) :rtype: @@ -285,7 +266,7 @@ async def begin_create_or_update( resource_group_name: str, scope_name: str, name: str, - parameters: Union[_models.ScopedResource, IO], + parameters: Union[_models.ScopedResource, IO[bytes]], **kwargs: Any ) -> AsyncLROPoller[_models.ScopedResource]: """Approve or reject a private endpoint connection with a given name. @@ -297,19 +278,8 @@ async def begin_create_or_update( :type scope_name: str :param name: The name of the scoped resource object. Required. :type name: str - :param parameters: Is either a ScopedResource type or a IO type. Required. - :type parameters: ~azure.mgmt.monitor.v2019_10_17.models.ScopedResource 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. + :param parameters: Is either a ScopedResource type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.monitor.v2019_10_17.models.ScopedResource or IO[bytes] :return: An instance of AsyncLROPoller that returns either ScopedResource or the result of cls(response) :rtype: @@ -319,7 +289,9 @@ async def begin_create_or_update( _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", "2019-10-17-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2019-10-17-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ScopedResource] = kwargs.pop("cls", None) polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) @@ -338,12 +310,13 @@ async def begin_create_or_update( 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("ScopedResource", pipeline_response) + deserialized = self._deserialize("ScopedResource", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: @@ -353,22 +326,20 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return AsyncLROPoller.from_continuation_token( + return AsyncLROPoller[_models.ScopedResource].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/privateLinkScopes/{scopeName}/scopedResources/{name}" - } + return AsyncLROPoller[_models.ScopedResource]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) - async def _delete_initial( # pylint: disable=inconsistent-return-statements + async def _delete_initial( self, resource_group_name: str, scope_name: str, name: str, **kwargs: Any - ) -> None: - error_map = { + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -379,39 +350,44 @@ async def _delete_initial( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-10-17-preview")) - cls: ClsType[None] = kwargs.pop("cls", None) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2019-10-17-preview") + ) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, scope_name=scope_name, name=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) + _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _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) raise HttpResponseError(response=response, 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_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/privateLinkScopes/{scopeName}/scopedResources/{name}" - } + return deserialized # type: ignore @distributed_trace_async async def begin_delete( @@ -426,14 +402,6 @@ async def begin_delete( :type scope_name: str :param name: The name of the scoped resource object. Required. :type 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: @@ -441,13 +409,15 @@ async def begin_delete( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-10-17-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2019-10-17-preview") + ) cls: ClsType[None] = kwargs.pop("cls", None) polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: - raw_result = await self._delete_initial( # type: ignore + raw_result = await self._delete_initial( resource_group_name=resource_group_name, scope_name=scope_name, name=name, @@ -457,11 +427,12 @@ async def begin_delete( 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, {}) + return cls(pipeline_response, None, {}) # type: ignore if polling is True: polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) @@ -470,17 +441,13 @@ def get_long_running_output(pipeline_response): # pylint: disable=inconsistent- else: polling_method = polling if cont_token: - return AsyncLROPoller.from_continuation_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(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/privateLinkScopes/{scopeName}/scopedResources/{name}" - } + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore @distributed_trace def list_by_private_link_scope( @@ -493,7 +460,6 @@ def list_by_private_link_scope( :type resource_group_name: str :param scope_name: The name of the Azure Monitor PrivateLinkScope resource. Required. :type scope_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ScopedResource or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.monitor.v2019_10_17.models.ScopedResource] @@ -502,10 +468,12 @@ def list_by_private_link_scope( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-10-17-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2019-10-17-preview") + ) cls: ClsType[_models.ScopedResourceListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -516,17 +484,15 @@ def list_by_private_link_scope( def prepare_request(next_link=None): if not next_link: - request = build_list_by_private_link_scope_request( + _request = build_list_by_private_link_scope_request( resource_group_name=resource_group_name, scope_name=scope_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_private_link_scope.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -537,14 +503,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("ScopedResourceListResult", pipeline_response) @@ -554,11 +519,11 @@ async def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -569,7 +534,3 @@ async def get_next(next_link=None): return pipeline_response return AsyncItemPaged(get_next, extract_data) - - list_by_private_link_scope.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/privateLinkScopes/{scopeName}/scopedResources" - } diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/aio/operations/_private_link_scopes_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/aio/operations/_private_link_scopes_operations.py index 019d14d72b96..5179d973abda 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/aio/operations/_private_link_scopes_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/aio/operations/_private_link_scopes_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,7 +5,9 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload +from io import IOBase +import sys +from typing import Any, AsyncIterable, AsyncIterator, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList @@ -16,12 +17,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 @@ -29,7 +31,6 @@ from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models -from ..._vendor import _convert_request from ...operations._private_link_scopes_operations import ( build_create_or_update_request, build_delete_request, @@ -39,6 +40,10 @@ build_update_tags_request, ) +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -61,12 +66,12 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list(self, **kwargs: Any) -> AsyncIterable["_models.AzureMonitorPrivateLinkScope"]: """Gets a list of all Azure Monitor PrivateLinkScopes within a subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either AzureMonitorPrivateLinkScope or the result of cls(response) :rtype: @@ -76,10 +81,12 @@ def list(self, **kwargs: Any) -> AsyncIterable["_models.AzureMonitorPrivateLinkS _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-10-17-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2019-10-17-preview") + ) cls: ClsType[_models.AzureMonitorPrivateLinkScopeListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -90,15 +97,13 @@ def list(self, **kwargs: Any) -> AsyncIterable["_models.AzureMonitorPrivateLinkS def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _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) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -109,14 +114,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("AzureMonitorPrivateLinkScopeListResult", pipeline_response) @@ -126,11 +130,11 @@ async def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -142,8 +146,6 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/microsoft.insights/privateLinkScopes"} - @distributed_trace def list_by_resource_group( self, resource_group_name: str, **kwargs: Any @@ -153,7 +155,6 @@ def list_by_resource_group( :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either AzureMonitorPrivateLinkScope or the result of cls(response) :rtype: @@ -163,10 +164,12 @@ def list_by_resource_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-10-17-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2019-10-17-preview") + ) cls: ClsType[_models.AzureMonitorPrivateLinkScopeListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -177,16 +180,14 @@ 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_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -197,14 +198,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("AzureMonitorPrivateLinkScopeListResult", pipeline_response) @@ -214,11 +214,11 @@ async def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -230,14 +230,8 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/privateLinkScopes" - } - - async def _delete_initial( # pylint: disable=inconsistent-return-statements - self, resource_group_name: str, scope_name: str, **kwargs: Any - ) -> None: - error_map = { + async def _delete_initial(self, resource_group_name: str, scope_name: str, **kwargs: Any) -> AsyncIterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -248,38 +242,43 @@ async def _delete_initial( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-10-17-preview")) - cls: ClsType[None] = kwargs.pop("cls", None) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2019-10-17-preview") + ) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, scope_name=scope_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) + _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _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) raise HttpResponseError(response=response, 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_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/privateLinkScopes/{scopeName}" - } + return deserialized # type: ignore @distributed_trace_async async def begin_delete(self, resource_group_name: str, scope_name: str, **kwargs: Any) -> AsyncLROPoller[None]: @@ -290,14 +289,6 @@ async def begin_delete(self, resource_group_name: str, scope_name: str, **kwargs :type resource_group_name: str :param scope_name: The name of the Azure Monitor PrivateLinkScope resource. Required. :type scope_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: @@ -305,13 +296,15 @@ async def begin_delete(self, resource_group_name: str, scope_name: str, **kwargs _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-10-17-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2019-10-17-preview") + ) cls: ClsType[None] = kwargs.pop("cls", None) polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: - raw_result = await self._delete_initial( # type: ignore + raw_result = await self._delete_initial( resource_group_name=resource_group_name, scope_name=scope_name, api_version=api_version, @@ -320,11 +313,12 @@ async def begin_delete(self, resource_group_name: str, scope_name: str, **kwargs 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, {}) + return cls(pipeline_response, None, {}) # type: ignore if polling is True: polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) @@ -333,17 +327,13 @@ def get_long_running_output(pipeline_response): # pylint: disable=inconsistent- else: polling_method = polling if cont_token: - return AsyncLROPoller.from_continuation_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(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/privateLinkScopes/{scopeName}" - } + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore @distributed_trace_async async def get( @@ -356,12 +346,11 @@ async def get( :type resource_group_name: str :param scope_name: The name of the Azure Monitor PrivateLinkScope resource. Required. :type scope_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: AzureMonitorPrivateLinkScope or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2019_10_17.models.AzureMonitorPrivateLinkScope :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -372,24 +361,24 @@ async def get( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-10-17-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2019-10-17-preview") + ) cls: ClsType[_models.AzureMonitorPrivateLinkScope] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, scope_name=scope_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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -398,16 +387,12 @@ async def get( map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize("AzureMonitorPrivateLinkScope", pipeline_response) + deserialized = self._deserialize("AzureMonitorPrivateLinkScope", 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.insights/privateLinkScopes/{scopeName}" - } + return deserialized # type: ignore @overload async def create_or_update( @@ -434,7 +419,6 @@ async def create_or_update( :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: AzureMonitorPrivateLinkScope or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2019_10_17.models.AzureMonitorPrivateLinkScope :raises ~azure.core.exceptions.HttpResponseError: @@ -445,7 +429,7 @@ async def create_or_update( self, resource_group_name: str, scope_name: str, - azure_monitor_private_link_scope_payload: IO, + azure_monitor_private_link_scope_payload: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -460,11 +444,10 @@ async def create_or_update( :type scope_name: str :param azure_monitor_private_link_scope_payload: Properties that need to be specified to create or update a Azure Monitor PrivateLinkScope. Required. - :type azure_monitor_private_link_scope_payload: IO + :type azure_monitor_private_link_scope_payload: 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: AzureMonitorPrivateLinkScope or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2019_10_17.models.AzureMonitorPrivateLinkScope :raises ~azure.core.exceptions.HttpResponseError: @@ -475,7 +458,7 @@ async def create_or_update( self, resource_group_name: str, scope_name: str, - azure_monitor_private_link_scope_payload: Union[_models.AzureMonitorPrivateLinkScope, IO], + azure_monitor_private_link_scope_payload: Union[_models.AzureMonitorPrivateLinkScope, IO[bytes]], **kwargs: Any ) -> _models.AzureMonitorPrivateLinkScope: """Creates (or updates) a Azure Monitor PrivateLinkScope. Note: You cannot specify a different @@ -488,18 +471,14 @@ async def create_or_update( :type scope_name: str :param azure_monitor_private_link_scope_payload: Properties that need to be specified to create or update a Azure Monitor PrivateLinkScope. Is either a AzureMonitorPrivateLinkScope type or a - IO type. Required. + IO[bytes] type. Required. :type azure_monitor_private_link_scope_payload: - ~azure.mgmt.monitor.v2019_10_17.models.AzureMonitorPrivateLinkScope 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 + ~azure.mgmt.monitor.v2019_10_17.models.AzureMonitorPrivateLinkScope or IO[bytes] :return: AzureMonitorPrivateLinkScope or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2019_10_17.models.AzureMonitorPrivateLinkScope :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -510,19 +489,21 @@ async def create_or_update( _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", "2019-10-17-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2019-10-17-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.AzureMonitorPrivateLinkScope] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(azure_monitor_private_link_scope_payload, (IO, bytes)): + if isinstance(azure_monitor_private_link_scope_payload, (IOBase, bytes)): _content = azure_monitor_private_link_scope_payload else: _json = self._serialize.body(azure_monitor_private_link_scope_payload, "AzureMonitorPrivateLinkScope") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, scope_name=scope_name, subscription_id=self._config.subscription_id, @@ -530,16 +511,14 @@ async def create_or_update( 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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -548,21 +527,13 @@ async def create_or_update( map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - if response.status_code == 200: - deserialized = self._deserialize("AzureMonitorPrivateLinkScope", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("AzureMonitorPrivateLinkScope", pipeline_response) + deserialized = self._deserialize("AzureMonitorPrivateLinkScope", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/privateLinkScopes/{scopeName}" - } - @overload async def update_tags( self, @@ -587,7 +558,6 @@ async def update_tags( :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: AzureMonitorPrivateLinkScope or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2019_10_17.models.AzureMonitorPrivateLinkScope :raises ~azure.core.exceptions.HttpResponseError: @@ -598,7 +568,7 @@ async def update_tags( self, resource_group_name: str, scope_name: str, - private_link_scope_tags: IO, + private_link_scope_tags: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -613,11 +583,10 @@ async def update_tags( :type scope_name: str :param private_link_scope_tags: Updated tag information to set into the PrivateLinkScope instance. Required. - :type private_link_scope_tags: IO + :type private_link_scope_tags: 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: AzureMonitorPrivateLinkScope or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2019_10_17.models.AzureMonitorPrivateLinkScope :raises ~azure.core.exceptions.HttpResponseError: @@ -628,7 +597,7 @@ async def update_tags( self, resource_group_name: str, scope_name: str, - private_link_scope_tags: Union[_models.TagsResource, IO], + private_link_scope_tags: Union[_models.TagsResource, IO[bytes]], **kwargs: Any ) -> _models.AzureMonitorPrivateLinkScope: """Updates an existing PrivateLinkScope's tags. To update other fields use the CreateOrUpdate @@ -640,17 +609,13 @@ async def update_tags( :param scope_name: The name of the Azure Monitor PrivateLinkScope resource. Required. :type scope_name: str :param private_link_scope_tags: Updated tag information to set into the PrivateLinkScope - instance. Is either a TagsResource type or a IO type. Required. - :type private_link_scope_tags: ~azure.mgmt.monitor.v2019_10_17.models.TagsResource 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 + instance. Is either a TagsResource type or a IO[bytes] type. Required. + :type private_link_scope_tags: ~azure.mgmt.monitor.v2019_10_17.models.TagsResource or IO[bytes] :return: AzureMonitorPrivateLinkScope or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2019_10_17.models.AzureMonitorPrivateLinkScope :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -661,19 +626,21 @@ async def update_tags( _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", "2019-10-17-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2019-10-17-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.AzureMonitorPrivateLinkScope] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(private_link_scope_tags, (IO, bytes)): + if isinstance(private_link_scope_tags, (IOBase, bytes)): _content = private_link_scope_tags else: _json = self._serialize.body(private_link_scope_tags, "TagsResource") - request = build_update_tags_request( + _request = build_update_tags_request( resource_group_name=resource_group_name, scope_name=scope_name, subscription_id=self._config.subscription_id, @@ -681,16 +648,14 @@ async def update_tags( content_type=content_type, json=_json, content=_content, - template_url=self.update_tags.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -699,13 +664,9 @@ async def update_tags( map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize("AzureMonitorPrivateLinkScope", pipeline_response) + deserialized = self._deserialize("AzureMonitorPrivateLinkScope", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - update_tags.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/privateLinkScopes/{scopeName}" - } + return deserialized # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/models/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/models/__init__.py index 5947e1f13a83..a5ef8c7fe0ef 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/models/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/models/__init__.py @@ -5,26 +5,35 @@ # 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 AzureMonitorPrivateLinkScope -from ._models_py3 import AzureMonitorPrivateLinkScopeListResult -from ._models_py3 import ErrorAdditionalInfo -from ._models_py3 import ErrorResponse -from ._models_py3 import ErrorResponseCommon -from ._models_py3 import OperationStatus -from ._models_py3 import PrivateEndpointConnection -from ._models_py3 import PrivateEndpointConnectionListResult -from ._models_py3 import PrivateEndpointProperty -from ._models_py3 import PrivateLinkResource -from ._models_py3 import PrivateLinkResourceListResult -from ._models_py3 import PrivateLinkScopesResource -from ._models_py3 import PrivateLinkServiceConnectionStateProperty -from ._models_py3 import ProxyResource -from ._models_py3 import ScopedResource -from ._models_py3 import ScopedResourceListResult -from ._models_py3 import TagsResource +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models_py3 import ( # type: ignore + AzureMonitorPrivateLinkScope, + AzureMonitorPrivateLinkScopeListResult, + ErrorAdditionalInfo, + ErrorResponse, + ErrorResponseCommon, + OperationStatus, + PrivateEndpointConnection, + PrivateEndpointConnectionListResult, + PrivateEndpointProperty, + PrivateLinkResource, + PrivateLinkResourceListResult, + PrivateLinkScopesResource, + PrivateLinkServiceConnectionStateProperty, + ProxyResource, + ScopedResource, + ScopedResourceListResult, + TagsResource, +) from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ @@ -46,5 +55,5 @@ "ScopedResourceListResult", "TagsResource", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/models/_models_py3.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/models/_models_py3.py index 22eabfbd961c..2104edfc938a 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/models/_models_py3.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/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. @@ -13,7 +12,6 @@ from ... import _serialization if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from .. import models as _models @@ -22,7 +20,7 @@ class PrivateLinkScopesResource(_serialization.Model): 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: Azure resource Id. :vartype id: str @@ -71,7 +69,7 @@ class AzureMonitorPrivateLinkScope(PrivateLinkScopesResource): 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: Azure resource Id. :vartype id: str @@ -129,7 +127,7 @@ def __init__(self, *, location: str, tags: Optional[Dict[str, str]] = None, **kw class AzureMonitorPrivateLinkScopeListResult(_serialization.Model): """Describes the list of Azure Monitor PrivateLinkScope resources. - 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 value: List of Azure Monitor PrivateLinkScope definitions. Required. :vartype value: list[~azure.mgmt.monitor.v2019_10_17.models.AzureMonitorPrivateLinkScope] @@ -525,12 +523,12 @@ def __init__(self, **kwargs: Any) -> None: self.next_link = None -class PrivateLinkServiceConnectionStateProperty(_serialization.Model): +class PrivateLinkServiceConnectionStateProperty(_serialization.Model): # pylint: disable=name-too-long """State of the private endpoint connection. Variables are only populated by the server, and will be ignored when sending a request. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. :ivar status: The private link service connection status. Required. :vartype status: str diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/operations/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/operations/__init__.py index 1f7c00746a8d..f529c5b732f2 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/operations/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/operations/__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 ._private_link_scopes_operations import PrivateLinkScopesOperations -from ._private_link_scope_operation_status_operations import PrivateLinkScopeOperationStatusOperations -from ._private_link_resources_operations import PrivateLinkResourcesOperations -from ._private_endpoint_connections_operations import PrivateEndpointConnectionsOperations -from ._private_link_scoped_resources_operations import PrivateLinkScopedResourcesOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._private_link_scopes_operations import PrivateLinkScopesOperations # type: ignore +from ._private_link_scope_operation_status_operations import PrivateLinkScopeOperationStatusOperations # type: ignore +from ._private_link_resources_operations import PrivateLinkResourcesOperations # type: ignore +from ._private_endpoint_connections_operations import PrivateEndpointConnectionsOperations # type: ignore +from ._private_link_scoped_resources_operations import PrivateLinkScopedResourcesOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ @@ -23,5 +29,5 @@ "PrivateEndpointConnectionsOperations", "PrivateLinkScopedResourcesOperations", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/operations/_private_endpoint_connections_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/operations/_private_endpoint_connections_operations.py index 12f8057c1e29..43711be7bb1e 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/operations/_private_endpoint_connections_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/operations/_private_endpoint_connections_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,7 +5,9 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload +from io import IOBase +import sys +from typing import Any, Callable, Dict, IO, Iterable, Iterator, Optional, TypeVar, Union, cast, overload import urllib.parse from azure.core.exceptions import ( @@ -15,13 +16,14 @@ 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 @@ -29,8 +31,11 @@ from .. import models as _models from ..._serialization import Serializer -from .._vendor import _convert_request, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -67,7 +72,7 @@ def build_get_request( ), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -108,7 +113,7 @@ def build_create_or_update_request( ), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -147,7 +152,7 @@ def build_delete_request( ), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -177,7 +182,7 @@ def build_list_by_private_link_scope_request( "scopeName": _SERIALIZER.url("scope_name", scope_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -206,6 +211,7 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def get( @@ -220,12 +226,11 @@ def get( :type scope_name: str :param private_endpoint_connection_name: The name of the private endpoint connection. Required. :type private_endpoint_connection_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: PrivateEndpointConnection or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2019_10_17.models.PrivateEndpointConnection :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -236,25 +241,25 @@ def get( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-10-17-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2019-10-17-preview") + ) cls: ClsType[_models.PrivateEndpointConnection] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, scope_name=scope_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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -263,26 +268,22 @@ def get( map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) + deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response.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.Insights/privateLinkScopes/{scopeName}/privateEndpointConnections/{privateEndpointConnectionName}" - } + return deserialized # type: ignore def _create_or_update_initial( self, resource_group_name: str, scope_name: str, private_endpoint_connection_name: str, - parameters: Union[_models.PrivateEndpointConnection, IO], + parameters: Union[_models.PrivateEndpointConnection, IO[bytes]], **kwargs: Any - ) -> Optional[_models.PrivateEndpointConnection]: - error_map = { + ) -> Iterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -293,19 +294,21 @@ def _create_or_update_initial( _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", "2019-10-17-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2019-10-17-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Optional[_models.PrivateEndpointConnection]] = kwargs.pop("cls", 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, "PrivateEndpointConnection") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, scope_name=scope_name, private_endpoint_connection_name=private_endpoint_connection_name, @@ -314,36 +317,33 @@ def _create_or_update_initial( 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) + _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: + 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) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = None - if response.status_code == 200: - deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - _create_or_update_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/privateLinkScopes/{scopeName}/privateEndpointConnections/{privateEndpointConnectionName}" - } + return deserialized # type: ignore @overload def begin_create_or_update( @@ -370,14 +370,6 @@ def begin_create_or_update( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of LROPoller that returns either PrivateEndpointConnection or the result of cls(response) :rtype: @@ -391,7 +383,7 @@ def begin_create_or_update( resource_group_name: str, scope_name: str, private_endpoint_connection_name: str, - parameters: IO, + parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -406,18 +398,10 @@ def begin_create_or_update( :param private_endpoint_connection_name: The name of the private endpoint connection. Required. :type private_endpoint_connection_name: str :param parameters: Required. - :type parameters: IO + :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 PrivateEndpointConnection or the result of cls(response) :rtype: @@ -431,7 +415,7 @@ def begin_create_or_update( resource_group_name: str, scope_name: str, private_endpoint_connection_name: str, - parameters: Union[_models.PrivateEndpointConnection, IO], + parameters: Union[_models.PrivateEndpointConnection, IO[bytes]], **kwargs: Any ) -> LROPoller[_models.PrivateEndpointConnection]: """Approve or reject a private endpoint connection with a given name. @@ -443,19 +427,8 @@ def begin_create_or_update( :type scope_name: str :param private_endpoint_connection_name: The name of the private endpoint connection. Required. :type private_endpoint_connection_name: str - :param parameters: Is either a PrivateEndpointConnection type or a IO type. Required. - :type parameters: ~azure.mgmt.monitor.v2019_10_17.models.PrivateEndpointConnection or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. + :param parameters: Is either a PrivateEndpointConnection type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.monitor.v2019_10_17.models.PrivateEndpointConnection or IO[bytes] :return: An instance of LROPoller that returns either PrivateEndpointConnection or the result of cls(response) :rtype: @@ -465,7 +438,9 @@ def begin_create_or_update( _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", "2019-10-17-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2019-10-17-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.PrivateEndpointConnection] = kwargs.pop("cls", None) polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) @@ -484,12 +459,13 @@ def begin_create_or_update( 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("PrivateEndpointConnection", pipeline_response) + deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: @@ -499,22 +475,20 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return LROPoller.from_continuation_token( + return LROPoller[_models.PrivateEndpointConnection].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/privateLinkScopes/{scopeName}/privateEndpointConnections/{privateEndpointConnectionName}" - } + return LROPoller[_models.PrivateEndpointConnection]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) - def _delete_initial( # pylint: disable=inconsistent-return-statements + def _delete_initial( self, resource_group_name: str, scope_name: str, private_endpoint_connection_name: str, **kwargs: Any - ) -> None: - error_map = { + ) -> Iterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -525,39 +499,44 @@ def _delete_initial( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-10-17-preview")) - cls: ClsType[None] = kwargs.pop("cls", None) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2019-10-17-preview") + ) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, scope_name=scope_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) + _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response 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) raise HttpResponseError(response=response, 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_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/privateLinkScopes/{scopeName}/privateEndpointConnections/{privateEndpointConnectionName}" - } + return deserialized # type: ignore @distributed_trace def begin_delete( @@ -572,14 +551,6 @@ def begin_delete( :type scope_name: str :param private_endpoint_connection_name: The name of the private endpoint connection. Required. :type private_endpoint_connection_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: @@ -587,13 +558,15 @@ def begin_delete( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-10-17-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2019-10-17-preview") + ) cls: ClsType[None] = kwargs.pop("cls", None) polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: - raw_result = self._delete_initial( # type: ignore + raw_result = self._delete_initial( resource_group_name=resource_group_name, scope_name=scope_name, private_endpoint_connection_name=private_endpoint_connection_name, @@ -603,11 +576,12 @@ def begin_delete( params=_params, **kwargs ) + 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, {}) + return cls(pipeline_response, None, {}) # type: ignore if polling is True: polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) @@ -616,17 +590,13 @@ def get_long_running_output(pipeline_response): # pylint: disable=inconsistent- else: polling_method = polling if cont_token: - return LROPoller.from_continuation_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(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/privateLinkScopes/{scopeName}/privateEndpointConnections/{privateEndpointConnectionName}" - } + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore @distributed_trace def list_by_private_link_scope( @@ -639,7 +609,6 @@ def list_by_private_link_scope( :type resource_group_name: str :param scope_name: The name of the Azure Monitor PrivateLinkScope resource. Required. :type scope_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: @@ -649,10 +618,12 @@ def list_by_private_link_scope( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-10-17-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2019-10-17-preview") + ) cls: ClsType[_models.PrivateEndpointConnectionListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -663,17 +634,15 @@ def list_by_private_link_scope( def prepare_request(next_link=None): if not next_link: - request = build_list_by_private_link_scope_request( + _request = build_list_by_private_link_scope_request( resource_group_name=resource_group_name, scope_name=scope_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_private_link_scope.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -684,14 +653,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("PrivateEndpointConnectionListResult", pipeline_response) @@ -701,11 +669,11 @@ def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -716,7 +684,3 @@ def get_next(next_link=None): return pipeline_response return ItemPaged(get_next, extract_data) - - list_by_private_link_scope.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/privateLinkScopes/{scopeName}/privateEndpointConnections" - } diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/operations/_private_link_resources_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/operations/_private_link_resources_operations.py index 9c81b625304a..ec7f1874ab4b 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/operations/_private_link_resources_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/operations/_private_link_resources_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,7 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, Callable, Dict, Iterable, Optional, TypeVar import urllib.parse @@ -19,16 +19,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, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -58,7 +60,7 @@ def build_list_by_private_link_scope_request( "scopeName": _SERIALIZER.url("scope_name", scope_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -92,7 +94,7 @@ def build_get_request( "groupName": _SERIALIZER.url("group_name", group_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -121,6 +123,7 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list_by_private_link_scope( @@ -133,7 +136,6 @@ def list_by_private_link_scope( :type resource_group_name: str :param scope_name: The name of the Azure Monitor PrivateLinkScope resource. Required. :type scope_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either PrivateLinkResource or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.monitor.v2019_10_17.models.PrivateLinkResource] @@ -142,10 +144,12 @@ def list_by_private_link_scope( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-10-17-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2019-10-17-preview") + ) cls: ClsType[_models.PrivateLinkResourceListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -156,17 +160,15 @@ def list_by_private_link_scope( def prepare_request(next_link=None): if not next_link: - request = build_list_by_private_link_scope_request( + _request = build_list_by_private_link_scope_request( resource_group_name=resource_group_name, scope_name=scope_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_private_link_scope.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -177,14 +179,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("PrivateLinkResourceListResult", pipeline_response) @@ -194,11 +195,11 @@ def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -210,10 +211,6 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_by_private_link_scope.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/privateLinkScopes/{scopeName}/privateLinkResources" - } - @distributed_trace def get( self, resource_group_name: str, scope_name: str, group_name: str, **kwargs: Any @@ -227,12 +224,11 @@ def get( :type scope_name: str :param group_name: The name of the private link resource. Required. :type group_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.monitor.v2019_10_17.models.PrivateLinkResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -243,25 +239,25 @@ def get( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-10-17-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2019-10-17-preview") + ) cls: ClsType[_models.PrivateLinkResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, scope_name=scope_name, group_name=group_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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -270,13 +266,9 @@ def get( map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize("PrivateLinkResource", pipeline_response) + deserialized = self._deserialize("PrivateLinkResource", pipeline_response.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.Insights/privateLinkScopes/{scopeName}/privateLinkResources/{groupName}" - } + return deserialized # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/operations/_private_link_scope_operation_status_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/operations/_private_link_scope_operation_status_operations.py index 55cc021cddeb..ffb3d3399ba8 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/operations/_private_link_scope_operation_status_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/operations/_private_link_scope_operation_status_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,7 @@ # 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 ( @@ -17,16 +17,18 @@ map_error, ) 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 +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -56,7 +58,7 @@ def build_get_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -67,7 +69,7 @@ def build_get_request( return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -class PrivateLinkScopeOperationStatusOperations: +class PrivateLinkScopeOperationStatusOperations: # pylint: disable=name-too-long """ .. warning:: **DO NOT** instantiate this class directly. @@ -85,6 +87,7 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def get(self, async_operation_id: str, resource_group_name: str, **kwargs: Any) -> _models.OperationStatus: @@ -96,12 +99,11 @@ def get(self, async_operation_id: str, resource_group_name: str, **kwargs: Any) :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: OperationStatus or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2019_10_17.models.OperationStatus :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -112,24 +114,24 @@ def get(self, async_operation_id: str, resource_group_name: str, **kwargs: Any) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-10-17-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2019-10-17-preview") + ) cls: ClsType[_models.OperationStatus] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( async_operation_id=async_operation_id, resource_group_name=resource_group_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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -138,13 +140,9 @@ def get(self, async_operation_id: str, resource_group_name: str, **kwargs: Any) map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize("OperationStatus", pipeline_response) + deserialized = self._deserialize("OperationStatus", 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.insights/privateLinkScopeOperationStatuses/{asyncOperationId}" - } + return deserialized # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/operations/_private_link_scoped_resources_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/operations/_private_link_scoped_resources_operations.py index d7fbfff8d25d..0930fbfff5f2 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/operations/_private_link_scoped_resources_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/operations/_private_link_scoped_resources_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,7 +5,9 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload +from io import IOBase +import sys +from typing import Any, Callable, Dict, IO, Iterable, Iterator, Optional, TypeVar, Union, cast, overload import urllib.parse from azure.core.exceptions import ( @@ -15,13 +16,14 @@ 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 @@ -29,8 +31,11 @@ from .. import models as _models from ..._serialization import Serializer -from .._vendor import _convert_request, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -61,7 +66,7 @@ def build_get_request( "name": _SERIALIZER.url("name", name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -96,7 +101,7 @@ def build_create_or_update_request( "name": _SERIALIZER.url("name", name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -129,7 +134,7 @@ def build_delete_request( "name": _SERIALIZER.url("name", name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -159,7 +164,7 @@ def build_list_by_private_link_scope_request( "scopeName": _SERIALIZER.url("scope_name", scope_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -188,6 +193,7 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def get(self, resource_group_name: str, scope_name: str, name: str, **kwargs: Any) -> _models.ScopedResource: @@ -200,12 +206,11 @@ def get(self, resource_group_name: str, scope_name: str, name: str, **kwargs: An :type scope_name: str :param name: The name of the scoped resource object. Required. :type name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ScopedResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2019_10_17.models.ScopedResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -216,25 +221,25 @@ def get(self, resource_group_name: str, scope_name: str, name: str, **kwargs: An _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-10-17-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2019-10-17-preview") + ) cls: ClsType[_models.ScopedResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, scope_name=scope_name, name=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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -243,26 +248,22 @@ def get(self, resource_group_name: str, scope_name: str, name: str, **kwargs: An map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize("ScopedResource", pipeline_response) + deserialized = self._deserialize("ScopedResource", 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.Insights/privateLinkScopes/{scopeName}/scopedResources/{name}" - } + return deserialized # type: ignore def _create_or_update_initial( self, resource_group_name: str, scope_name: str, name: str, - parameters: Union[_models.ScopedResource, IO], + parameters: Union[_models.ScopedResource, IO[bytes]], **kwargs: Any - ) -> Optional[_models.ScopedResource]: - error_map = { + ) -> Iterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -273,19 +274,21 @@ def _create_or_update_initial( _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", "2019-10-17-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2019-10-17-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Optional[_models.ScopedResource]] = kwargs.pop("cls", 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, "ScopedResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, scope_name=scope_name, name=name, @@ -294,39 +297,33 @@ def _create_or_update_initial( 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) + _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 201, 202]: + 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) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = None - if response.status_code == 200: - deserialized = self._deserialize("ScopedResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("ScopedResource", 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 - - _create_or_update_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/privateLinkScopes/{scopeName}/scopedResources/{name}" - } + return deserialized # type: ignore @overload def begin_create_or_update( @@ -353,14 +350,6 @@ def begin_create_or_update( :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 ScopedResource or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.monitor.v2019_10_17.models.ScopedResource] @@ -373,7 +362,7 @@ def begin_create_or_update( resource_group_name: str, scope_name: str, name: str, - parameters: IO, + parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -388,18 +377,10 @@ def begin_create_or_update( :param name: The name of the scoped resource object. Required. :type name: str :param parameters: Required. - :type parameters: IO + :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 ScopedResource or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.monitor.v2019_10_17.models.ScopedResource] @@ -412,7 +393,7 @@ def begin_create_or_update( resource_group_name: str, scope_name: str, name: str, - parameters: Union[_models.ScopedResource, IO], + parameters: Union[_models.ScopedResource, IO[bytes]], **kwargs: Any ) -> LROPoller[_models.ScopedResource]: """Approve or reject a private endpoint connection with a given name. @@ -424,19 +405,8 @@ def begin_create_or_update( :type scope_name: str :param name: The name of the scoped resource object. Required. :type name: str - :param parameters: Is either a ScopedResource type or a IO type. Required. - :type parameters: ~azure.mgmt.monitor.v2019_10_17.models.ScopedResource 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. + :param parameters: Is either a ScopedResource type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.monitor.v2019_10_17.models.ScopedResource or IO[bytes] :return: An instance of LROPoller that returns either ScopedResource or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.monitor.v2019_10_17.models.ScopedResource] @@ -445,7 +415,9 @@ def begin_create_or_update( _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", "2019-10-17-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2019-10-17-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ScopedResource] = kwargs.pop("cls", None) polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) @@ -464,12 +436,13 @@ def begin_create_or_update( 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("ScopedResource", pipeline_response) + deserialized = self._deserialize("ScopedResource", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: @@ -479,22 +452,18 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return LROPoller.from_continuation_token( + return LROPoller[_models.ScopedResource].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/privateLinkScopes/{scopeName}/scopedResources/{name}" - } + return LROPoller[_models.ScopedResource]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) - def _delete_initial( # pylint: disable=inconsistent-return-statements - self, resource_group_name: str, scope_name: str, name: str, **kwargs: Any - ) -> None: - error_map = { + def _delete_initial(self, resource_group_name: str, scope_name: str, name: str, **kwargs: Any) -> Iterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -505,39 +474,44 @@ def _delete_initial( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-10-17-preview")) - cls: ClsType[None] = kwargs.pop("cls", None) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2019-10-17-preview") + ) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, scope_name=scope_name, name=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) + _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response 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) raise HttpResponseError(response=response, 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_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/privateLinkScopes/{scopeName}/scopedResources/{name}" - } + return deserialized # type: ignore @distributed_trace def begin_delete(self, resource_group_name: str, scope_name: str, name: str, **kwargs: Any) -> LROPoller[None]: @@ -550,14 +524,6 @@ def begin_delete(self, resource_group_name: str, scope_name: str, name: str, **k :type scope_name: str :param name: The name of the scoped resource object. Required. :type 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: @@ -565,13 +531,15 @@ def begin_delete(self, resource_group_name: str, scope_name: str, name: str, **k _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-10-17-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2019-10-17-preview") + ) cls: ClsType[None] = kwargs.pop("cls", None) polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: - raw_result = self._delete_initial( # type: ignore + raw_result = self._delete_initial( resource_group_name=resource_group_name, scope_name=scope_name, name=name, @@ -581,11 +549,12 @@ def begin_delete(self, resource_group_name: str, scope_name: str, name: str, **k params=_params, **kwargs ) + 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, {}) + return cls(pipeline_response, None, {}) # type: ignore if polling is True: polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) @@ -594,17 +563,13 @@ def get_long_running_output(pipeline_response): # pylint: disable=inconsistent- else: polling_method = polling if cont_token: - return LROPoller.from_continuation_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(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/privateLinkScopes/{scopeName}/scopedResources/{name}" - } + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore @distributed_trace def list_by_private_link_scope( @@ -617,7 +582,6 @@ def list_by_private_link_scope( :type resource_group_name: str :param scope_name: The name of the Azure Monitor PrivateLinkScope resource. Required. :type scope_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ScopedResource or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.monitor.v2019_10_17.models.ScopedResource] :raises ~azure.core.exceptions.HttpResponseError: @@ -625,10 +589,12 @@ def list_by_private_link_scope( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-10-17-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2019-10-17-preview") + ) cls: ClsType[_models.ScopedResourceListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -639,17 +605,15 @@ def list_by_private_link_scope( def prepare_request(next_link=None): if not next_link: - request = build_list_by_private_link_scope_request( + _request = build_list_by_private_link_scope_request( resource_group_name=resource_group_name, scope_name=scope_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_private_link_scope.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -660,14 +624,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("ScopedResourceListResult", pipeline_response) @@ -677,11 +640,11 @@ def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -692,7 +655,3 @@ def get_next(next_link=None): return pipeline_response return ItemPaged(get_next, extract_data) - - list_by_private_link_scope.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/privateLinkScopes/{scopeName}/scopedResources" - } diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/operations/_private_link_scopes_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/operations/_private_link_scopes_operations.py index 9a177d0cc9ca..84ca0b0b2f34 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/operations/_private_link_scopes_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_10_17/operations/_private_link_scopes_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,7 +5,9 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload +from io import IOBase +import sys +from typing import Any, Callable, Dict, IO, Iterable, Iterator, Optional, TypeVar, Union, cast, overload import urllib.parse from azure.core.exceptions import ( @@ -15,13 +16,14 @@ 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 @@ -29,8 +31,11 @@ from .. import models as _models from ..._serialization import Serializer -from .._vendor import _convert_request, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -51,7 +56,7 @@ def build_list_request(subscription_id: str, **kwargs: Any) -> HttpRequest: "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -81,7 +86,7 @@ def build_list_by_resource_group_request(resource_group_name: str, subscription_ "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -109,7 +114,7 @@ def build_delete_request(resource_group_name: str, scope_name: str, subscription "scopeName": _SERIALIZER.url("scope_name", scope_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -137,7 +142,7 @@ def build_get_request(resource_group_name: str, scope_name: str, subscription_id "scopeName": _SERIALIZER.url("scope_name", scope_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -171,7 +176,7 @@ def build_create_or_update_request( "scopeName": _SERIALIZER.url("scope_name", scope_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -207,7 +212,7 @@ def build_update_tags_request( "scopeName": _SERIALIZER.url("scope_name", scope_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -238,12 +243,12 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list(self, **kwargs: Any) -> Iterable["_models.AzureMonitorPrivateLinkScope"]: """Gets a list of all Azure Monitor PrivateLinkScopes within a subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either AzureMonitorPrivateLinkScope or the result of cls(response) :rtype: @@ -253,10 +258,12 @@ def list(self, **kwargs: Any) -> Iterable["_models.AzureMonitorPrivateLinkScope" _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-10-17-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2019-10-17-preview") + ) cls: ClsType[_models.AzureMonitorPrivateLinkScopeListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -267,15 +274,13 @@ def list(self, **kwargs: Any) -> Iterable["_models.AzureMonitorPrivateLinkScope" def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _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) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -286,14 +291,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("AzureMonitorPrivateLinkScopeListResult", pipeline_response) @@ -303,11 +307,11 @@ def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -319,8 +323,6 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/microsoft.insights/privateLinkScopes"} - @distributed_trace def list_by_resource_group( self, resource_group_name: str, **kwargs: Any @@ -330,7 +332,6 @@ def list_by_resource_group( :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either AzureMonitorPrivateLinkScope or the result of cls(response) :rtype: @@ -340,10 +341,12 @@ def list_by_resource_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-10-17-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2019-10-17-preview") + ) cls: ClsType[_models.AzureMonitorPrivateLinkScopeListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -354,16 +357,14 @@ 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_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -374,14 +375,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("AzureMonitorPrivateLinkScopeListResult", pipeline_response) @@ -391,11 +391,11 @@ def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -407,14 +407,8 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/privateLinkScopes" - } - - def _delete_initial( # pylint: disable=inconsistent-return-statements - self, resource_group_name: str, scope_name: str, **kwargs: Any - ) -> None: - error_map = { + def _delete_initial(self, resource_group_name: str, scope_name: str, **kwargs: Any) -> Iterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -425,38 +419,43 @@ def _delete_initial( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-10-17-preview")) - cls: ClsType[None] = kwargs.pop("cls", None) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2019-10-17-preview") + ) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, scope_name=scope_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) + _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response 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) raise HttpResponseError(response=response, 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_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/privateLinkScopes/{scopeName}" - } + return deserialized # type: ignore @distributed_trace def begin_delete(self, resource_group_name: str, scope_name: str, **kwargs: Any) -> LROPoller[None]: @@ -467,14 +466,6 @@ def begin_delete(self, resource_group_name: str, scope_name: str, **kwargs: Any) :type resource_group_name: str :param scope_name: The name of the Azure Monitor PrivateLinkScope resource. Required. :type scope_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: @@ -482,13 +473,15 @@ def begin_delete(self, resource_group_name: str, scope_name: str, **kwargs: Any) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-10-17-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2019-10-17-preview") + ) cls: ClsType[None] = kwargs.pop("cls", None) polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: - raw_result = self._delete_initial( # type: ignore + raw_result = self._delete_initial( resource_group_name=resource_group_name, scope_name=scope_name, api_version=api_version, @@ -497,11 +490,12 @@ def begin_delete(self, resource_group_name: str, scope_name: str, **kwargs: Any) params=_params, **kwargs ) + 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, {}) + return cls(pipeline_response, None, {}) # type: ignore if polling is True: polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) @@ -510,17 +504,13 @@ def get_long_running_output(pipeline_response): # pylint: disable=inconsistent- else: polling_method = polling if cont_token: - return LROPoller.from_continuation_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(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/privateLinkScopes/{scopeName}" - } + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore @distributed_trace def get(self, resource_group_name: str, scope_name: str, **kwargs: Any) -> _models.AzureMonitorPrivateLinkScope: @@ -531,12 +521,11 @@ def get(self, resource_group_name: str, scope_name: str, **kwargs: Any) -> _mode :type resource_group_name: str :param scope_name: The name of the Azure Monitor PrivateLinkScope resource. Required. :type scope_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: AzureMonitorPrivateLinkScope or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2019_10_17.models.AzureMonitorPrivateLinkScope :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -547,24 +536,24 @@ def get(self, resource_group_name: str, scope_name: str, **kwargs: Any) -> _mode _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-10-17-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2019-10-17-preview") + ) cls: ClsType[_models.AzureMonitorPrivateLinkScope] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, scope_name=scope_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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -573,16 +562,12 @@ def get(self, resource_group_name: str, scope_name: str, **kwargs: Any) -> _mode map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize("AzureMonitorPrivateLinkScope", pipeline_response) + deserialized = self._deserialize("AzureMonitorPrivateLinkScope", 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.insights/privateLinkScopes/{scopeName}" - } + return deserialized # type: ignore @overload def create_or_update( @@ -609,7 +594,6 @@ def create_or_update( :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: AzureMonitorPrivateLinkScope or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2019_10_17.models.AzureMonitorPrivateLinkScope :raises ~azure.core.exceptions.HttpResponseError: @@ -620,7 +604,7 @@ def create_or_update( self, resource_group_name: str, scope_name: str, - azure_monitor_private_link_scope_payload: IO, + azure_monitor_private_link_scope_payload: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -635,11 +619,10 @@ def create_or_update( :type scope_name: str :param azure_monitor_private_link_scope_payload: Properties that need to be specified to create or update a Azure Monitor PrivateLinkScope. Required. - :type azure_monitor_private_link_scope_payload: IO + :type azure_monitor_private_link_scope_payload: 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: AzureMonitorPrivateLinkScope or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2019_10_17.models.AzureMonitorPrivateLinkScope :raises ~azure.core.exceptions.HttpResponseError: @@ -650,7 +633,7 @@ def create_or_update( self, resource_group_name: str, scope_name: str, - azure_monitor_private_link_scope_payload: Union[_models.AzureMonitorPrivateLinkScope, IO], + azure_monitor_private_link_scope_payload: Union[_models.AzureMonitorPrivateLinkScope, IO[bytes]], **kwargs: Any ) -> _models.AzureMonitorPrivateLinkScope: """Creates (or updates) a Azure Monitor PrivateLinkScope. Note: You cannot specify a different @@ -663,18 +646,14 @@ def create_or_update( :type scope_name: str :param azure_monitor_private_link_scope_payload: Properties that need to be specified to create or update a Azure Monitor PrivateLinkScope. Is either a AzureMonitorPrivateLinkScope type or a - IO type. Required. + IO[bytes] type. Required. :type azure_monitor_private_link_scope_payload: - ~azure.mgmt.monitor.v2019_10_17.models.AzureMonitorPrivateLinkScope 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 + ~azure.mgmt.monitor.v2019_10_17.models.AzureMonitorPrivateLinkScope or IO[bytes] :return: AzureMonitorPrivateLinkScope or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2019_10_17.models.AzureMonitorPrivateLinkScope :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -685,19 +664,21 @@ def create_or_update( _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", "2019-10-17-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2019-10-17-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.AzureMonitorPrivateLinkScope] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(azure_monitor_private_link_scope_payload, (IO, bytes)): + if isinstance(azure_monitor_private_link_scope_payload, (IOBase, bytes)): _content = azure_monitor_private_link_scope_payload else: _json = self._serialize.body(azure_monitor_private_link_scope_payload, "AzureMonitorPrivateLinkScope") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, scope_name=scope_name, subscription_id=self._config.subscription_id, @@ -705,16 +686,14 @@ def create_or_update( 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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -723,21 +702,13 @@ def create_or_update( map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - if response.status_code == 200: - deserialized = self._deserialize("AzureMonitorPrivateLinkScope", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("AzureMonitorPrivateLinkScope", pipeline_response) + deserialized = self._deserialize("AzureMonitorPrivateLinkScope", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/privateLinkScopes/{scopeName}" - } - @overload def update_tags( self, @@ -762,7 +733,6 @@ def update_tags( :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: AzureMonitorPrivateLinkScope or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2019_10_17.models.AzureMonitorPrivateLinkScope :raises ~azure.core.exceptions.HttpResponseError: @@ -773,7 +743,7 @@ def update_tags( self, resource_group_name: str, scope_name: str, - private_link_scope_tags: IO, + private_link_scope_tags: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -788,11 +758,10 @@ def update_tags( :type scope_name: str :param private_link_scope_tags: Updated tag information to set into the PrivateLinkScope instance. Required. - :type private_link_scope_tags: IO + :type private_link_scope_tags: 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: AzureMonitorPrivateLinkScope or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2019_10_17.models.AzureMonitorPrivateLinkScope :raises ~azure.core.exceptions.HttpResponseError: @@ -803,7 +772,7 @@ def update_tags( self, resource_group_name: str, scope_name: str, - private_link_scope_tags: Union[_models.TagsResource, IO], + private_link_scope_tags: Union[_models.TagsResource, IO[bytes]], **kwargs: Any ) -> _models.AzureMonitorPrivateLinkScope: """Updates an existing PrivateLinkScope's tags. To update other fields use the CreateOrUpdate @@ -815,17 +784,13 @@ def update_tags( :param scope_name: The name of the Azure Monitor PrivateLinkScope resource. Required. :type scope_name: str :param private_link_scope_tags: Updated tag information to set into the PrivateLinkScope - instance. Is either a TagsResource type or a IO type. Required. - :type private_link_scope_tags: ~azure.mgmt.monitor.v2019_10_17.models.TagsResource 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 + instance. Is either a TagsResource type or a IO[bytes] type. Required. + :type private_link_scope_tags: ~azure.mgmt.monitor.v2019_10_17.models.TagsResource or IO[bytes] :return: AzureMonitorPrivateLinkScope or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2019_10_17.models.AzureMonitorPrivateLinkScope :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -836,19 +801,21 @@ def update_tags( _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", "2019-10-17-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2019-10-17-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.AzureMonitorPrivateLinkScope] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(private_link_scope_tags, (IO, bytes)): + if isinstance(private_link_scope_tags, (IOBase, bytes)): _content = private_link_scope_tags else: _json = self._serialize.body(private_link_scope_tags, "TagsResource") - request = build_update_tags_request( + _request = build_update_tags_request( resource_group_name=resource_group_name, scope_name=scope_name, subscription_id=self._config.subscription_id, @@ -856,16 +823,14 @@ def update_tags( content_type=content_type, json=_json, content=_content, - template_url=self.update_tags.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -874,13 +839,9 @@ def update_tags( map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize("AzureMonitorPrivateLinkScope", pipeline_response) + deserialized = self._deserialize("AzureMonitorPrivateLinkScope", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - update_tags.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/privateLinkScopes/{scopeName}" - } + return deserialized # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_11_01_preview/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_11_01_preview/__init__.py index 2c7733bfd566..42cc62301757 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_11_01_preview/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_11_01_preview/__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 ._monitor_management_client import MonitorManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._monitor_management_client import MonitorManagementClient # type: ignore from ._version import VERSION __version__ = VERSION try: from ._patch import __all__ as _patch_all - from ._patch import * # 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__ = [ "MonitorManagementClient", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_11_01_preview/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_11_01_preview/_configuration.py index 73d471345233..67574b077e1f 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_11_01_preview/_configuration.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_11_01_preview/_configuration.py @@ -8,18 +8,16 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy from ._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MonitorManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class MonitorManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for MonitorManagementClient. Note that all parameters used to create this instance are saved as instance @@ -35,7 +33,6 @@ class MonitorManagementClientConfiguration(Configuration): # pylint: disable=to """ def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: - super(MonitorManagementClientConfiguration, self).__init__(**kwargs) api_version: str = kwargs.pop("api_version", "2019-11-01-preview") if credential is None: @@ -48,6 +45,7 @@ def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-monitor/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -56,9 +54,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.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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_11_01_preview/_metadata.json b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_11_01_preview/_metadata.json index aa8b405524f5..7355a17b2f47 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_11_01_preview/_metadata.json +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_11_01_preview/_metadata.json @@ -8,10 +8,10 @@ "host_value": "\"https://management.azure.com\"", "parameterized_host_template": null, "azure_arm": true, - "has_lro_operations": false, + "has_public_lro_operations": false, "client_side_validation": false, - "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"sdkcore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMAutoResourceProviderRegistrationPolicy\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}, \"stdlib\": {\"typing_extensions\": [\"Self\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"sdkcore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"AsyncARMAutoResourceProviderRegistrationPolicy\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}, \"stdlib\": {\"typing_extensions\": [\"Self\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "global_parameters": { "sync": { @@ -101,8 +101,8 @@ "credential_scopes": ["https://management.azure.com/.default"], "credential_call_sync": "ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", "credential_call_async": "AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", - "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "sync_imports": "{\"regular\": {\"sdkcore\": {\"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"regular\": {\"sdkcore\": {\"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "operation_groups": { "data_collection_rule_associations": "DataCollectionRuleAssociationsOperations", diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_11_01_preview/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_11_01_preview/_monitor_management_client.py index 6f276c320222..3d27bcaa1df8 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_11_01_preview/_monitor_management_client.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_11_01_preview/_monitor_management_client.py @@ -8,9 +8,12 @@ from copy import deepcopy from typing import Any, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient +from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy from . import models as _models from .._serialization import Deserializer, Serializer @@ -18,11 +21,10 @@ from .operations import DataCollectionRuleAssociationsOperations, DataCollectionRulesOperations if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MonitorManagementClient: # pylint: disable=client-accepts-api-version-keyword +class MonitorManagementClient: """Monitor Management Client. :ivar data_collection_rule_associations: DataCollectionRuleAssociationsOperations operations @@ -52,20 +54,38 @@ def __init__( self._config = MonitorManagementClientConfiguration( credential=credential, subscription_id=subscription_id, **kwargs ) - self._client: ARMPipelineClient = ARMPipelineClient(base_url=base_url, config=self._config, **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), + 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=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.data_collection_rule_associations = DataCollectionRuleAssociationsOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2019-11-01-preview" ) self.data_collection_rules = DataCollectionRulesOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2019-11-01-preview" ) - 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 @@ -85,12 +105,12 @@ 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) -> None: self._client.close() - def __enter__(self) -> "MonitorManagementClient": + def __enter__(self) -> Self: self._client.__enter__() return self diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_11_01_preview/_vendor.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_11_01_preview/_vendor.py deleted file mode 100644 index bd0df84f5319..000000000000 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_11_01_preview/_vendor.py +++ /dev/null @@ -1,30 +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 typing import List, cast - -from azure.core.pipeline.transport import HttpRequest - - -def _convert_request(request, files=None): - data = request.content if not files else None - request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) - if files: - request.set_formdata_body(files) - return request - - -def _format_url_section(template, **kwargs): - components = template.split("/") - while components: - try: - return template.format(**kwargs) - except KeyError as key: - # Need the cast, as for some reasons "split" is typed as list[str | Any] - formatted_components = cast(List[str], template.split("/")) - components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] - template = "/".join(components) diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_11_01_preview/_version.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_11_01_preview/_version.py index 394ee7c0c03c..e5754a47ce68 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_11_01_preview/_version.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_11_01_preview/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "6.0.2" +VERSION = "1.0.0b1" diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_11_01_preview/aio/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_11_01_preview/aio/__init__.py index 2c151bb41c19..3df30ff42149 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_11_01_preview/aio/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_11_01_preview/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 ._monitor_management_client import MonitorManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._monitor_management_client import MonitorManagementClient # type: ignore try: from ._patch import __all__ as _patch_all - from ._patch import * # 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__ = [ "MonitorManagementClient", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_11_01_preview/aio/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_11_01_preview/aio/_configuration.py index ba7d63ed5b53..605d1f3fd7ea 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_11_01_preview/aio/_configuration.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_11_01_preview/aio/_configuration.py @@ -8,18 +8,16 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy from .._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MonitorManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class MonitorManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for MonitorManagementClient. Note that all parameters used to create this instance are saved as instance @@ -35,7 +33,6 @@ class MonitorManagementClientConfiguration(Configuration): # pylint: disable=to """ def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: - super(MonitorManagementClientConfiguration, self).__init__(**kwargs) api_version: str = kwargs.pop("api_version", "2019-11-01-preview") if credential is None: @@ -48,6 +45,7 @@ def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **k self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-monitor/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -56,9 +54,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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_11_01_preview/aio/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_11_01_preview/aio/_monitor_management_client.py index 78f9c865e6df..373618f4862a 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_11_01_preview/aio/_monitor_management_client.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_11_01_preview/aio/_monitor_management_client.py @@ -8,9 +8,12 @@ from copy import deepcopy from typing import Any, Awaitable, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient +from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy from .. import models as _models from ..._serialization import Deserializer, Serializer @@ -18,11 +21,10 @@ from .operations import DataCollectionRuleAssociationsOperations, DataCollectionRulesOperations if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MonitorManagementClient: # pylint: disable=client-accepts-api-version-keyword +class MonitorManagementClient: """Monitor Management Client. :ivar data_collection_rule_associations: DataCollectionRuleAssociationsOperations operations @@ -52,20 +54,40 @@ def __init__( self._config = MonitorManagementClientConfiguration( credential=credential, subscription_id=subscription_id, **kwargs ) - self._client: AsyncARMPipelineClient = AsyncARMPipelineClient(base_url=base_url, config=self._config, **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=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.data_collection_rule_associations = DataCollectionRuleAssociationsOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2019-11-01-preview" ) self.data_collection_rules = DataCollectionRulesOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2019-11-01-preview" ) - 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 @@ -85,12 +107,12 @@ 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) -> "MonitorManagementClient": + async def __aenter__(self) -> Self: await self._client.__aenter__() return self diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_11_01_preview/aio/operations/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_11_01_preview/aio/operations/__init__.py index cb4e5ea6755e..7d3453b77e78 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_11_01_preview/aio/operations/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_11_01_preview/aio/operations/__init__.py @@ -5,17 +5,23 @@ # 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 ._data_collection_rule_associations_operations import DataCollectionRuleAssociationsOperations -from ._data_collection_rules_operations import DataCollectionRulesOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._data_collection_rule_associations_operations import DataCollectionRuleAssociationsOperations # type: ignore +from ._data_collection_rules_operations import DataCollectionRulesOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ "DataCollectionRuleAssociationsOperations", "DataCollectionRulesOperations", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_11_01_preview/aio/operations/_data_collection_rule_associations_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_11_01_preview/aio/operations/_data_collection_rule_associations_operations.py index 45961e6de505..4ea44c17b7c3 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_11_01_preview/aio/operations/_data_collection_rule_associations_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_11_01_preview/aio/operations/_data_collection_rule_associations_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload import urllib.parse @@ -19,15 +20,13 @@ 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 ...operations._data_collection_rule_associations_operations import ( build_create_request, build_delete_request, @@ -36,6 +35,10 @@ build_list_by_rule_request, ) +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -58,18 +61,19 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list_by_resource( self, resource_uri: str, **kwargs: Any ) -> AsyncIterable["_models.DataCollectionRuleAssociationProxyOnlyResource"]: + # pylint: disable=line-too-long """Lists associations for the specified resource. Lists associations for the specified resource. :param resource_uri: The identifier of the resource. Required. :type resource_uri: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either DataCollectionRuleAssociationProxyOnlyResource or the result of cls(response) :rtype: @@ -79,10 +83,12 @@ def list_by_resource( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-11-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2019-11-01-preview") + ) cls: ClsType[_models.DataCollectionRuleAssociationProxyOnlyResourceListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -93,15 +99,13 @@ def list_by_resource( def prepare_request(next_link=None): if not next_link: - request = build_list_by_resource_request( + _request = build_list_by_resource_request( resource_uri=resource_uri, api_version=api_version, - template_url=self.list_by_resource.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -112,14 +116,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize( @@ -131,11 +134,11 @@ async def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -148,12 +151,11 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_by_resource.metadata = {"url": "/{resourceUri}/providers/Microsoft.Insights/dataCollectionRuleAssociations"} - @distributed_trace def list_by_rule( self, resource_group_name: str, data_collection_rule_name: str, **kwargs: Any ) -> AsyncIterable["_models.DataCollectionRuleAssociationProxyOnlyResource"]: + # pylint: disable=line-too-long """Lists associations for the specified data collection rule. Lists associations for the specified data collection rule. @@ -164,7 +166,6 @@ def list_by_rule( :param data_collection_rule_name: The name of the data collection rule. The name is case insensitive. Required. :type data_collection_rule_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either DataCollectionRuleAssociationProxyOnlyResource or the result of cls(response) :rtype: @@ -174,10 +175,12 @@ def list_by_rule( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-11-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2019-11-01-preview") + ) cls: ClsType[_models.DataCollectionRuleAssociationProxyOnlyResourceListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -188,17 +191,15 @@ def list_by_rule( def prepare_request(next_link=None): if not next_link: - request = build_list_by_rule_request( + _request = build_list_by_rule_request( resource_group_name=resource_group_name, data_collection_rule_name=data_collection_rule_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_rule.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -209,14 +210,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize( @@ -228,11 +228,11 @@ async def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -245,10 +245,6 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_by_rule.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionRules/{dataCollectionRuleName}/associations" - } - @distributed_trace_async async def get( self, resource_uri: str, association_name: str, **kwargs: Any @@ -261,13 +257,12 @@ async def get( :type resource_uri: str :param association_name: The name of the association. The name is case insensitive. Required. :type association_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: DataCollectionRuleAssociationProxyOnlyResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2019_11_01_preview.models.DataCollectionRuleAssociationProxyOnlyResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -278,23 +273,23 @@ async def get( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-11-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2019-11-01-preview") + ) cls: ClsType[_models.DataCollectionRuleAssociationProxyOnlyResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_uri=resource_uri, association_name=association_name, api_version=api_version, - template_url=self.get.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -304,16 +299,14 @@ async def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("DataCollectionRuleAssociationProxyOnlyResource", pipeline_response) + deserialized = self._deserialize( + "DataCollectionRuleAssociationProxyOnlyResource", pipeline_response.http_response + ) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get.metadata = { - "url": "/{resourceUri}/providers/Microsoft.Insights/dataCollectionRuleAssociations/{associationName}" - } + return deserialized # type: ignore @overload async def create( @@ -339,7 +332,6 @@ async def create( :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: DataCollectionRuleAssociationProxyOnlyResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2019_11_01_preview.models.DataCollectionRuleAssociationProxyOnlyResource @@ -351,7 +343,7 @@ async def create( self, resource_uri: str, association_name: str, - body: Optional[IO] = None, + body: Optional[IO[bytes]] = None, *, content_type: str = "application/json", **kwargs: Any @@ -365,11 +357,10 @@ async def create( :param association_name: The name of the association. The name is case insensitive. Required. :type association_name: str :param body: The payload. Default value is None. - :type body: IO + :type body: 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: DataCollectionRuleAssociationProxyOnlyResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2019_11_01_preview.models.DataCollectionRuleAssociationProxyOnlyResource @@ -381,7 +372,7 @@ async def create( self, resource_uri: str, association_name: str, - body: Optional[Union[_models.DataCollectionRuleAssociationProxyOnlyResource, IO]] = None, + body: Optional[Union[_models.DataCollectionRuleAssociationProxyOnlyResource, IO[bytes]]] = None, **kwargs: Any ) -> _models.DataCollectionRuleAssociationProxyOnlyResource: """Creates or updates an association. @@ -393,20 +384,16 @@ async def create( :param association_name: The name of the association. The name is case insensitive. Required. :type association_name: str :param body: The payload. Is either a DataCollectionRuleAssociationProxyOnlyResource type or a - IO type. Default value is None. + IO[bytes] type. Default value is None. :type body: ~azure.mgmt.monitor.v2019_11_01_preview.models.DataCollectionRuleAssociationProxyOnlyResource - 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 + or IO[bytes] :return: DataCollectionRuleAssociationProxyOnlyResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2019_11_01_preview.models.DataCollectionRuleAssociationProxyOnlyResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -417,14 +404,16 @@ async def create( _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", "2019-11-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2019-11-01-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.DataCollectionRuleAssociationProxyOnlyResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(body, (IO, bytes)): + if isinstance(body, (IOBase, bytes)): _content = body else: if body is not None: @@ -432,23 +421,21 @@ async def create( else: _json = None - request = build_create_request( + _request = build_create_request( resource_uri=resource_uri, association_name=association_name, api_version=api_version, content_type=content_type, json=_json, content=_content, - template_url=self.create.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -458,25 +445,17 @@ async def create( 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("DataCollectionRuleAssociationProxyOnlyResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("DataCollectionRuleAssociationProxyOnlyResource", pipeline_response) + deserialized = self._deserialize( + "DataCollectionRuleAssociationProxyOnlyResource", pipeline_response.http_response + ) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create.metadata = { - "url": "/{resourceUri}/providers/Microsoft.Insights/dataCollectionRuleAssociations/{associationName}" - } - @distributed_trace_async - async def delete( # pylint: disable=inconsistent-return-statements - self, resource_uri: str, association_name: str, **kwargs: Any - ) -> None: + async def delete(self, resource_uri: str, association_name: str, **kwargs: Any) -> None: """Deletes an association. Deletes an association. @@ -485,12 +464,11 @@ async def delete( # pylint: disable=inconsistent-return-statements :type resource_uri: str :param association_name: The name of the association. The name is case insensitive. Required. :type association_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, @@ -501,23 +479,23 @@ async def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-11-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2019-11-01-preview") + ) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_uri=resource_uri, association_name=association_name, api_version=api_version, - template_url=self.delete.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -528,8 +506,4 @@ async def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/{resourceUri}/providers/Microsoft.Insights/dataCollectionRuleAssociations/{associationName}" - } + return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_11_01_preview/aio/operations/_data_collection_rules_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_11_01_preview/aio/operations/_data_collection_rules_operations.py index ccb81f47d079..3553e84bbfd6 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_11_01_preview/aio/operations/_data_collection_rules_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_11_01_preview/aio/operations/_data_collection_rules_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload import urllib.parse @@ -19,15 +20,13 @@ 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 ...operations._data_collection_rules_operations import ( build_create_request, build_delete_request, @@ -37,6 +36,10 @@ build_update_request, ) +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -59,11 +62,13 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list_by_resource_group( self, resource_group_name: str, **kwargs: Any ) -> AsyncIterable["_models.DataCollectionRuleResource"]: + # pylint: disable=line-too-long """Lists all data collection rules in the specified resource group. Lists all data collection rules in the specified resource group. @@ -71,7 +76,6 @@ def list_by_resource_group( :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either DataCollectionRuleResource or the result of cls(response) :rtype: @@ -81,10 +85,12 @@ def list_by_resource_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-11-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2019-11-01-preview") + ) cls: ClsType[_models.DataCollectionRuleResourceListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -95,16 +101,14 @@ 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_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -115,14 +119,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("DataCollectionRuleResourceListResult", pipeline_response) @@ -132,11 +135,11 @@ async def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -149,17 +152,13 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionRules" - } - @distributed_trace def list_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.DataCollectionRuleResource"]: + # pylint: disable=line-too-long """Lists all data collection rules in the specified subscription. Lists all data collection rules in the specified subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either DataCollectionRuleResource or the result of cls(response) :rtype: @@ -169,10 +168,12 @@ def list_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.DataColl _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-11-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2019-11-01-preview") + ) cls: ClsType[_models.DataCollectionRuleResourceListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -183,15 +184,13 @@ def list_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.DataColl def prepare_request(next_link=None): if not next_link: - request = build_list_by_subscription_request( + _request = build_list_by_subscription_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_subscription.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -202,14 +201,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("DataCollectionRuleResourceListResult", pipeline_response) @@ -219,11 +217,11 @@ async def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -236,10 +234,6 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_by_subscription.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/dataCollectionRules" - } - @distributed_trace_async async def get( self, resource_group_name: str, data_collection_rule_name: str, **kwargs: Any @@ -254,12 +248,11 @@ async def get( :param data_collection_rule_name: The name of the data collection rule. The name is case insensitive. Required. :type data_collection_rule_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: DataCollectionRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2019_11_01_preview.models.DataCollectionRuleResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -270,24 +263,24 @@ async def get( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-11-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2019-11-01-preview") + ) cls: ClsType[_models.DataCollectionRuleResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, data_collection_rule_name=data_collection_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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -297,16 +290,12 @@ async def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("DataCollectionRuleResource", pipeline_response) + deserialized = self._deserialize("DataCollectionRuleResource", 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.Insights/dataCollectionRules/{dataCollectionRuleName}" - } + return deserialized # type: ignore @overload async def create( @@ -333,7 +322,6 @@ async def create( :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: DataCollectionRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2019_11_01_preview.models.DataCollectionRuleResource :raises ~azure.core.exceptions.HttpResponseError: @@ -344,7 +332,7 @@ async def create( self, resource_group_name: str, data_collection_rule_name: str, - body: Optional[IO] = None, + body: Optional[IO[bytes]] = None, *, content_type: str = "application/json", **kwargs: Any @@ -360,11 +348,10 @@ async def create( insensitive. Required. :type data_collection_rule_name: str :param body: The payload. Default value is None. - :type body: IO + :type body: 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: DataCollectionRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2019_11_01_preview.models.DataCollectionRuleResource :raises ~azure.core.exceptions.HttpResponseError: @@ -375,7 +362,7 @@ async def create( self, resource_group_name: str, data_collection_rule_name: str, - body: Optional[Union[_models.DataCollectionRuleResource, IO]] = None, + body: Optional[Union[_models.DataCollectionRuleResource, IO[bytes]]] = None, **kwargs: Any ) -> _models.DataCollectionRuleResource: """Creates or updates a data collection rule. @@ -388,18 +375,15 @@ async def create( :param data_collection_rule_name: The name of the data collection rule. The name is case insensitive. Required. :type data_collection_rule_name: str - :param body: The payload. Is either a DataCollectionRuleResource type or a IO type. Default - value is None. - :type body: ~azure.mgmt.monitor.v2019_11_01_preview.models.DataCollectionRuleResource or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + :param body: The payload. Is either a DataCollectionRuleResource type or a IO[bytes] type. Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response + :type body: ~azure.mgmt.monitor.v2019_11_01_preview.models.DataCollectionRuleResource or + IO[bytes] :return: DataCollectionRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2019_11_01_preview.models.DataCollectionRuleResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -410,14 +394,16 @@ async def create( _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", "2019-11-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2019-11-01-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.DataCollectionRuleResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(body, (IO, bytes)): + if isinstance(body, (IOBase, bytes)): _content = body else: if body is not None: @@ -425,7 +411,7 @@ async def create( else: _json = None - request = build_create_request( + _request = build_create_request( resource_group_name=resource_group_name, data_collection_rule_name=data_collection_rule_name, subscription_id=self._config.subscription_id, @@ -433,16 +419,14 @@ async def create( content_type=content_type, json=_json, content=_content, - template_url=self.create.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -452,21 +436,13 @@ async def create( 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("DataCollectionRuleResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("DataCollectionRuleResource", pipeline_response) + deserialized = self._deserialize("DataCollectionRuleResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionRules/{dataCollectionRuleName}" - } - @overload async def update( self, @@ -492,7 +468,6 @@ async def update( :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: DataCollectionRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2019_11_01_preview.models.DataCollectionRuleResource :raises ~azure.core.exceptions.HttpResponseError: @@ -503,7 +478,7 @@ async def update( self, resource_group_name: str, data_collection_rule_name: str, - body: Optional[IO] = None, + body: Optional[IO[bytes]] = None, *, content_type: str = "application/json", **kwargs: Any @@ -519,11 +494,10 @@ async def update( insensitive. Required. :type data_collection_rule_name: str :param body: The payload. Default value is None. - :type body: IO + :type body: 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: DataCollectionRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2019_11_01_preview.models.DataCollectionRuleResource :raises ~azure.core.exceptions.HttpResponseError: @@ -534,7 +508,7 @@ async def update( self, resource_group_name: str, data_collection_rule_name: str, - body: Optional[Union[_models.ResourceForUpdate, IO]] = None, + body: Optional[Union[_models.ResourceForUpdate, IO[bytes]]] = None, **kwargs: Any ) -> _models.DataCollectionRuleResource: """Updates part of a data collection rule. @@ -547,18 +521,14 @@ async def update( :param data_collection_rule_name: The name of the data collection rule. The name is case insensitive. Required. :type data_collection_rule_name: str - :param body: The payload. Is either a ResourceForUpdate type or a IO type. Default value is - None. - :type body: ~azure.mgmt.monitor.v2019_11_01_preview.models.ResourceForUpdate 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 + :param body: The payload. Is either a ResourceForUpdate type or a IO[bytes] type. Default value + is None. + :type body: ~azure.mgmt.monitor.v2019_11_01_preview.models.ResourceForUpdate or IO[bytes] :return: DataCollectionRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2019_11_01_preview.models.DataCollectionRuleResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -569,14 +539,16 @@ async def update( _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", "2019-11-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2019-11-01-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.DataCollectionRuleResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(body, (IO, bytes)): + if isinstance(body, (IOBase, bytes)): _content = body else: if body is not None: @@ -584,7 +556,7 @@ async def update( else: _json = None - request = build_update_request( + _request = build_update_request( resource_group_name=resource_group_name, data_collection_rule_name=data_collection_rule_name, subscription_id=self._config.subscription_id, @@ -592,16 +564,14 @@ async def update( 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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -611,21 +581,15 @@ async def update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("DataCollectionRuleResource", pipeline_response) + deserialized = self._deserialize("DataCollectionRuleResource", 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.Insights/dataCollectionRules/{dataCollectionRuleName}" - } + return deserialized # type: ignore @distributed_trace_async - async def delete( # pylint: disable=inconsistent-return-statements - self, resource_group_name: str, data_collection_rule_name: str, **kwargs: Any - ) -> None: + async def delete(self, resource_group_name: str, data_collection_rule_name: str, **kwargs: Any) -> None: """Deletes a data collection rule. Deletes a data collection rule. @@ -636,12 +600,11 @@ async def delete( # pylint: disable=inconsistent-return-statements :param data_collection_rule_name: The name of the data collection rule. The name is case insensitive. Required. :type data_collection_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, @@ -652,24 +615,24 @@ async def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-11-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2019-11-01-preview") + ) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, data_collection_rule_name=data_collection_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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -680,8 +643,4 @@ async def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionRules/{dataCollectionRuleName}" - } + return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_11_01_preview/models/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_11_01_preview/models/__init__.py index 20e7277139ff..d57c92420ec0 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_11_01_preview/models/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_11_01_preview/models/__init__.py @@ -5,44 +5,55 @@ # 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 AzureMonitorMetricsDestination -from ._models_py3 import DataCollectionRule -from ._models_py3 import DataCollectionRuleAssociation -from ._models_py3 import DataCollectionRuleAssociationProxyOnlyResource -from ._models_py3 import DataCollectionRuleAssociationProxyOnlyResourceListResult -from ._models_py3 import DataCollectionRuleAssociationProxyOnlyResourceProperties -from ._models_py3 import DataCollectionRuleDataSources -from ._models_py3 import DataCollectionRuleDestinations -from ._models_py3 import DataCollectionRuleResource -from ._models_py3 import DataCollectionRuleResourceListResult -from ._models_py3 import DataCollectionRuleResourceProperties -from ._models_py3 import DataFlow -from ._models_py3 import DataSourcesSpec -from ._models_py3 import DestinationsSpec -from ._models_py3 import DestinationsSpecAzureMonitorMetrics -from ._models_py3 import ErrorAdditionalInfo -from ._models_py3 import ErrorDetail -from ._models_py3 import ErrorResponse -from ._models_py3 import ExtensionDataSource -from ._models_py3 import LogAnalyticsDestination -from ._models_py3 import PerfCounterDataSource -from ._models_py3 import ResourceForUpdate -from ._models_py3 import SyslogDataSource -from ._models_py3 import WindowsEventLogDataSource +from typing import TYPE_CHECKING -from ._monitor_management_client_enums import KnownDataCollectionRuleAssociationProvisioningState -from ._monitor_management_client_enums import KnownDataCollectionRuleProvisioningState -from ._monitor_management_client_enums import KnownDataCollectionRuleResourceKind -from ._monitor_management_client_enums import KnownDataFlowStreams -from ._monitor_management_client_enums import KnownExtensionDataSourceStreams -from ._monitor_management_client_enums import KnownPerfCounterDataSourceStreams -from ._monitor_management_client_enums import KnownSyslogDataSourceFacilityNames -from ._monitor_management_client_enums import KnownSyslogDataSourceLogLevels -from ._monitor_management_client_enums import KnownSyslogDataSourceStreams -from ._monitor_management_client_enums import KnownWindowsEventLogDataSourceStreams +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models_py3 import ( # type: ignore + AzureMonitorMetricsDestination, + DataCollectionRule, + DataCollectionRuleAssociation, + DataCollectionRuleAssociationProxyOnlyResource, + DataCollectionRuleAssociationProxyOnlyResourceListResult, + DataCollectionRuleAssociationProxyOnlyResourceProperties, + DataCollectionRuleDataSources, + DataCollectionRuleDestinations, + DataCollectionRuleResource, + DataCollectionRuleResourceListResult, + DataCollectionRuleResourceProperties, + DataFlow, + DataSourcesSpec, + DestinationsSpec, + DestinationsSpecAzureMonitorMetrics, + ErrorAdditionalInfo, + ErrorDetail, + ErrorResponse, + ExtensionDataSource, + LogAnalyticsDestination, + PerfCounterDataSource, + ResourceForUpdate, + SyslogDataSource, + WindowsEventLogDataSource, +) + +from ._monitor_management_client_enums import ( # type: ignore + KnownDataCollectionRuleAssociationProvisioningState, + KnownDataCollectionRuleProvisioningState, + KnownDataCollectionRuleResourceKind, + KnownDataFlowStreams, + KnownExtensionDataSourceStreams, + KnownPerfCounterDataSourceStreams, + KnownSyslogDataSourceFacilityNames, + KnownSyslogDataSourceLogLevels, + KnownSyslogDataSourceStreams, + KnownWindowsEventLogDataSourceStreams, +) from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ @@ -81,5 +92,5 @@ "KnownSyslogDataSourceStreams", "KnownWindowsEventLogDataSourceStreams", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_11_01_preview/models/_models_py3.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_11_01_preview/models/_models_py3.py index 5ae69c566855..9054d4ea3848 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_11_01_preview/models/_models_py3.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_11_01_preview/models/_models_py3.py @@ -1,5 +1,5 @@ -# coding=utf-8 # 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. @@ -15,10 +15,9 @@ if sys.version_info >= (3, 9): from collections.abc import MutableMapping else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports + from typing import MutableMapping # type: ignore if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from .. import models as _models JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object @@ -160,7 +159,7 @@ def __init__( self.provisioning_state = None -class DataCollectionRuleAssociationProxyOnlyResource(_serialization.Model): +class DataCollectionRuleAssociationProxyOnlyResource(_serialization.Model): # pylint: disable=name-too-long """Definition of generic ARM proxy resource. Variables are only populated by the server, and will be ignored when sending a request. @@ -222,10 +221,10 @@ def __init__( self.provisioning_state = None -class DataCollectionRuleAssociationProxyOnlyResourceListResult(_serialization.Model): +class DataCollectionRuleAssociationProxyOnlyResourceListResult(_serialization.Model): # pylint: disable=name-too-long """A pageable list of resources. - 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 value: A list of resources. Required. :vartype value: @@ -262,7 +261,9 @@ def __init__( self.next_link = next_link -class DataCollectionRuleAssociationProxyOnlyResourceProperties(DataCollectionRuleAssociation): +class DataCollectionRuleAssociationProxyOnlyResourceProperties( + DataCollectionRuleAssociation +): # pylint: disable=name-too-long """Resource properties. Variables are only populated by the server, and will be ignored when sending a request. @@ -278,28 +279,6 @@ class DataCollectionRuleAssociationProxyOnlyResourceProperties(DataCollectionRul ~azure.mgmt.monitor.v2019_11_01_preview.models.KnownDataCollectionRuleAssociationProvisioningState """ - _validation = { - "provisioning_state": {"readonly": True}, - } - - _attribute_map = { - "description": {"key": "description", "type": "str"}, - "data_collection_rule_id": {"key": "dataCollectionRuleId", "type": "str"}, - "provisioning_state": {"key": "provisioningState", "type": "str"}, - } - - def __init__( - self, *, description: Optional[str] = None, data_collection_rule_id: Optional[str] = None, **kwargs: Any - ) -> None: - """ - :keyword description: Description of the association. - :paramtype description: str - :keyword data_collection_rule_id: The resource ID of the data collection rule that is to be - associated. - :paramtype data_collection_rule_id: str - """ - super().__init__(description=description, data_collection_rule_id=data_collection_rule_id, **kwargs) - class DataSourcesSpec(_serialization.Model): """Specification of data sources that will be collected. @@ -368,42 +347,6 @@ class DataCollectionRuleDataSources(DataSourcesSpec): :vartype extensions: list[~azure.mgmt.monitor.v2019_11_01_preview.models.ExtensionDataSource] """ - _attribute_map = { - "performance_counters": {"key": "performanceCounters", "type": "[PerfCounterDataSource]"}, - "windows_event_logs": {"key": "windowsEventLogs", "type": "[WindowsEventLogDataSource]"}, - "syslog": {"key": "syslog", "type": "[SyslogDataSource]"}, - "extensions": {"key": "extensions", "type": "[ExtensionDataSource]"}, - } - - def __init__( - self, - *, - performance_counters: Optional[List["_models.PerfCounterDataSource"]] = None, - windows_event_logs: Optional[List["_models.WindowsEventLogDataSource"]] = None, - syslog: Optional[List["_models.SyslogDataSource"]] = None, - extensions: Optional[List["_models.ExtensionDataSource"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword performance_counters: The list of performance counter data source configurations. - :paramtype performance_counters: - list[~azure.mgmt.monitor.v2019_11_01_preview.models.PerfCounterDataSource] - :keyword windows_event_logs: The list of Windows Event Log data source configurations. - :paramtype windows_event_logs: - list[~azure.mgmt.monitor.v2019_11_01_preview.models.WindowsEventLogDataSource] - :keyword syslog: The list of Syslog data source configurations. - :paramtype syslog: list[~azure.mgmt.monitor.v2019_11_01_preview.models.SyslogDataSource] - :keyword extensions: The list of Azure VM extension data source configurations. - :paramtype extensions: list[~azure.mgmt.monitor.v2019_11_01_preview.models.ExtensionDataSource] - """ - super().__init__( - performance_counters=performance_counters, - windows_event_logs=windows_event_logs, - syslog=syslog, - extensions=extensions, - **kwargs - ) - class DestinationsSpec(_serialization.Model): """Specification of destinations that can be used in data flows. @@ -452,35 +395,13 @@ class DataCollectionRuleDestinations(DestinationsSpec): ~azure.mgmt.monitor.v2019_11_01_preview.models.DestinationsSpecAzureMonitorMetrics """ - _attribute_map = { - "log_analytics": {"key": "logAnalytics", "type": "[LogAnalyticsDestination]"}, - "azure_monitor_metrics": {"key": "azureMonitorMetrics", "type": "DestinationsSpecAzureMonitorMetrics"}, - } - def __init__( - self, - *, - log_analytics: Optional[List["_models.LogAnalyticsDestination"]] = None, - azure_monitor_metrics: Optional["_models.DestinationsSpecAzureMonitorMetrics"] = None, - **kwargs: Any - ) -> None: - """ - :keyword log_analytics: List of Log Analytics destinations. - :paramtype log_analytics: - list[~azure.mgmt.monitor.v2019_11_01_preview.models.LogAnalyticsDestination] - :keyword azure_monitor_metrics: Azure Monitor Metrics destination. - :paramtype azure_monitor_metrics: - ~azure.mgmt.monitor.v2019_11_01_preview.models.DestinationsSpecAzureMonitorMetrics - """ - super().__init__(log_analytics=log_analytics, azure_monitor_metrics=azure_monitor_metrics, **kwargs) - - -class DataCollectionRuleResource(_serialization.Model): # pylint: disable=too-many-instance-attributes +class DataCollectionRuleResource(_serialization.Model): """Definition of ARM tracked top level 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 location: The geo-location where the resource lives. Required. :vartype location: str @@ -595,7 +516,7 @@ def __init__( class DataCollectionRuleResourceListResult(_serialization.Model): """A pageable list of resources. - 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 value: A list of resources. Required. :vartype value: list[~azure.mgmt.monitor.v2019_11_01_preview.models.DataCollectionRuleResource] @@ -652,51 +573,6 @@ class DataCollectionRuleResourceProperties(DataCollectionRule): ~azure.mgmt.monitor.v2019_11_01_preview.models.KnownDataCollectionRuleProvisioningState """ - _validation = { - "immutable_id": {"readonly": True}, - "provisioning_state": {"readonly": True}, - } - - _attribute_map = { - "description": {"key": "description", "type": "str"}, - "immutable_id": {"key": "immutableId", "type": "str"}, - "data_sources": {"key": "dataSources", "type": "DataCollectionRuleDataSources"}, - "destinations": {"key": "destinations", "type": "DataCollectionRuleDestinations"}, - "data_flows": {"key": "dataFlows", "type": "[DataFlow]"}, - "provisioning_state": {"key": "provisioningState", "type": "str"}, - } - - def __init__( - self, - *, - description: Optional[str] = None, - data_sources: Optional["_models.DataCollectionRuleDataSources"] = None, - destinations: Optional["_models.DataCollectionRuleDestinations"] = None, - data_flows: Optional[List["_models.DataFlow"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword description: Description of the data collection rule. - :paramtype description: str - :keyword data_sources: The specification of data sources. - This property is optional and can be omitted if the rule is meant to be used via direct calls - to the provisioned endpoint. - :paramtype data_sources: - ~azure.mgmt.monitor.v2019_11_01_preview.models.DataCollectionRuleDataSources - :keyword destinations: The specification of destinations. - :paramtype destinations: - ~azure.mgmt.monitor.v2019_11_01_preview.models.DataCollectionRuleDestinations - :keyword data_flows: The specification of data flows. - :paramtype data_flows: list[~azure.mgmt.monitor.v2019_11_01_preview.models.DataFlow] - """ - super().__init__( - description=description, - data_sources=data_sources, - destinations=destinations, - data_flows=data_flows, - **kwargs - ) - class DataFlow(_serialization.Model): """Definition of which streams are sent to which destinations. @@ -741,19 +617,6 @@ class DestinationsSpecAzureMonitorMetrics(AzureMonitorMetricsDestination): :vartype name: str """ - _attribute_map = { - "name": {"key": "name", "type": "str"}, - } - - def __init__(self, *, name: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword name: A friendly name for the destination. - This name should be unique across all destinations (regardless of type) within the data - collection rule. - :paramtype name: str - """ - super().__init__(name=name, **kwargs) - class ErrorAdditionalInfo(_serialization.Model): """The resource management error additional info. @@ -853,7 +716,7 @@ class ExtensionDataSource(_serialization.Model): the Azure Monitor Agent. Collected from either Windows and Linux machines, depending on which extension is defined. - 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 streams: List of streams that this data source will be sent to. A stream indicates what schema will be used for this data and usually what table in Log diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_11_01_preview/operations/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_11_01_preview/operations/__init__.py index cb4e5ea6755e..7d3453b77e78 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_11_01_preview/operations/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_11_01_preview/operations/__init__.py @@ -5,17 +5,23 @@ # 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 ._data_collection_rule_associations_operations import DataCollectionRuleAssociationsOperations -from ._data_collection_rules_operations import DataCollectionRulesOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._data_collection_rule_associations_operations import DataCollectionRuleAssociationsOperations # type: ignore +from ._data_collection_rules_operations import DataCollectionRulesOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ "DataCollectionRuleAssociationsOperations", "DataCollectionRulesOperations", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_11_01_preview/operations/_data_collection_rule_associations_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_11_01_preview/operations/_data_collection_rule_associations_operations.py index b0d7674bc0f2..24f8b9ffa6fe 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_11_01_preview/operations/_data_collection_rule_associations_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_11_01_preview/operations/_data_collection_rule_associations_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload import urllib.parse @@ -19,16 +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, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -49,7 +52,7 @@ def build_list_by_resource_request(resource_uri: str, **kwargs: Any) -> HttpRequ "resourceUri": _SERIALIZER.url("resource_uri", resource_uri, "str", skip_quote=True, min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -82,7 +85,7 @@ def build_list_by_rule_request( "dataCollectionRuleName": _SERIALIZER.url("data_collection_rule_name", data_collection_rule_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -109,7 +112,7 @@ def build_get_request(resource_uri: str, association_name: str, **kwargs: Any) - "associationName": _SERIALIZER.url("association_name", association_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -137,7 +140,7 @@ def build_create_request(resource_uri: str, association_name: str, **kwargs: Any "associationName": _SERIALIZER.url("association_name", association_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -166,7 +169,7 @@ def build_delete_request(resource_uri: str, association_name: str, **kwargs: Any "associationName": _SERIALIZER.url("association_name", association_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -195,18 +198,19 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list_by_resource( self, resource_uri: str, **kwargs: Any ) -> Iterable["_models.DataCollectionRuleAssociationProxyOnlyResource"]: + # pylint: disable=line-too-long """Lists associations for the specified resource. Lists associations for the specified resource. :param resource_uri: The identifier of the resource. Required. :type resource_uri: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either DataCollectionRuleAssociationProxyOnlyResource or the result of cls(response) :rtype: @@ -216,10 +220,12 @@ def list_by_resource( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-11-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2019-11-01-preview") + ) cls: ClsType[_models.DataCollectionRuleAssociationProxyOnlyResourceListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -230,15 +236,13 @@ def list_by_resource( def prepare_request(next_link=None): if not next_link: - request = build_list_by_resource_request( + _request = build_list_by_resource_request( resource_uri=resource_uri, api_version=api_version, - template_url=self.list_by_resource.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -249,14 +253,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize( @@ -268,11 +271,11 @@ def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -285,12 +288,11 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_by_resource.metadata = {"url": "/{resourceUri}/providers/Microsoft.Insights/dataCollectionRuleAssociations"} - @distributed_trace def list_by_rule( self, resource_group_name: str, data_collection_rule_name: str, **kwargs: Any ) -> Iterable["_models.DataCollectionRuleAssociationProxyOnlyResource"]: + # pylint: disable=line-too-long """Lists associations for the specified data collection rule. Lists associations for the specified data collection rule. @@ -301,7 +303,6 @@ def list_by_rule( :param data_collection_rule_name: The name of the data collection rule. The name is case insensitive. Required. :type data_collection_rule_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either DataCollectionRuleAssociationProxyOnlyResource or the result of cls(response) :rtype: @@ -311,10 +312,12 @@ def list_by_rule( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-11-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2019-11-01-preview") + ) cls: ClsType[_models.DataCollectionRuleAssociationProxyOnlyResourceListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -325,17 +328,15 @@ def list_by_rule( def prepare_request(next_link=None): if not next_link: - request = build_list_by_rule_request( + _request = build_list_by_rule_request( resource_group_name=resource_group_name, data_collection_rule_name=data_collection_rule_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_rule.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -346,14 +347,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize( @@ -365,11 +365,11 @@ def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -382,10 +382,6 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_by_rule.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionRules/{dataCollectionRuleName}/associations" - } - @distributed_trace def get( self, resource_uri: str, association_name: str, **kwargs: Any @@ -398,13 +394,12 @@ def get( :type resource_uri: str :param association_name: The name of the association. The name is case insensitive. Required. :type association_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: DataCollectionRuleAssociationProxyOnlyResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2019_11_01_preview.models.DataCollectionRuleAssociationProxyOnlyResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -415,23 +410,23 @@ def get( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-11-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2019-11-01-preview") + ) cls: ClsType[_models.DataCollectionRuleAssociationProxyOnlyResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_uri=resource_uri, association_name=association_name, api_version=api_version, - template_url=self.get.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -441,16 +436,14 @@ def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("DataCollectionRuleAssociationProxyOnlyResource", pipeline_response) + deserialized = self._deserialize( + "DataCollectionRuleAssociationProxyOnlyResource", pipeline_response.http_response + ) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get.metadata = { - "url": "/{resourceUri}/providers/Microsoft.Insights/dataCollectionRuleAssociations/{associationName}" - } + return deserialized # type: ignore @overload def create( @@ -476,7 +469,6 @@ def create( :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: DataCollectionRuleAssociationProxyOnlyResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2019_11_01_preview.models.DataCollectionRuleAssociationProxyOnlyResource @@ -488,7 +480,7 @@ def create( self, resource_uri: str, association_name: str, - body: Optional[IO] = None, + body: Optional[IO[bytes]] = None, *, content_type: str = "application/json", **kwargs: Any @@ -502,11 +494,10 @@ def create( :param association_name: The name of the association. The name is case insensitive. Required. :type association_name: str :param body: The payload. Default value is None. - :type body: IO + :type body: 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: DataCollectionRuleAssociationProxyOnlyResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2019_11_01_preview.models.DataCollectionRuleAssociationProxyOnlyResource @@ -518,7 +509,7 @@ def create( self, resource_uri: str, association_name: str, - body: Optional[Union[_models.DataCollectionRuleAssociationProxyOnlyResource, IO]] = None, + body: Optional[Union[_models.DataCollectionRuleAssociationProxyOnlyResource, IO[bytes]]] = None, **kwargs: Any ) -> _models.DataCollectionRuleAssociationProxyOnlyResource: """Creates or updates an association. @@ -530,20 +521,16 @@ def create( :param association_name: The name of the association. The name is case insensitive. Required. :type association_name: str :param body: The payload. Is either a DataCollectionRuleAssociationProxyOnlyResource type or a - IO type. Default value is None. + IO[bytes] type. Default value is None. :type body: ~azure.mgmt.monitor.v2019_11_01_preview.models.DataCollectionRuleAssociationProxyOnlyResource - 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 + or IO[bytes] :return: DataCollectionRuleAssociationProxyOnlyResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2019_11_01_preview.models.DataCollectionRuleAssociationProxyOnlyResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -554,14 +541,16 @@ def create( _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", "2019-11-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2019-11-01-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.DataCollectionRuleAssociationProxyOnlyResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(body, (IO, bytes)): + if isinstance(body, (IOBase, bytes)): _content = body else: if body is not None: @@ -569,23 +558,21 @@ def create( else: _json = None - request = build_create_request( + _request = build_create_request( resource_uri=resource_uri, association_name=association_name, api_version=api_version, content_type=content_type, json=_json, content=_content, - template_url=self.create.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -595,21 +582,15 @@ def create( 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("DataCollectionRuleAssociationProxyOnlyResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("DataCollectionRuleAssociationProxyOnlyResource", pipeline_response) + deserialized = self._deserialize( + "DataCollectionRuleAssociationProxyOnlyResource", pipeline_response.http_response + ) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create.metadata = { - "url": "/{resourceUri}/providers/Microsoft.Insights/dataCollectionRuleAssociations/{associationName}" - } - @distributed_trace def delete( # pylint: disable=inconsistent-return-statements self, resource_uri: str, association_name: str, **kwargs: Any @@ -622,12 +603,11 @@ def delete( # pylint: disable=inconsistent-return-statements :type resource_uri: str :param association_name: The name of the association. The name is case insensitive. Required. :type association_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, @@ -638,23 +618,23 @@ def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-11-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2019-11-01-preview") + ) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_uri=resource_uri, association_name=association_name, api_version=api_version, - template_url=self.delete.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -665,8 +645,4 @@ def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/{resourceUri}/providers/Microsoft.Insights/dataCollectionRuleAssociations/{associationName}" - } + return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_11_01_preview/operations/_data_collection_rules_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_11_01_preview/operations/_data_collection_rules_operations.py index 9ed552110b7c..7d893b6a1cab 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_11_01_preview/operations/_data_collection_rules_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2019_11_01_preview/operations/_data_collection_rules_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload import urllib.parse @@ -19,16 +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, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -55,7 +58,7 @@ def build_list_by_resource_group_request(resource_group_name: str, subscription_ ), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -81,7 +84,7 @@ def build_list_by_subscription_request(subscription_id: str, **kwargs: Any) -> H "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -114,7 +117,7 @@ def build_get_request( "dataCollectionRuleName": _SERIALIZER.url("data_collection_rule_name", data_collection_rule_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -148,7 +151,7 @@ def build_create_request( "dataCollectionRuleName": _SERIALIZER.url("data_collection_rule_name", data_collection_rule_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -184,7 +187,7 @@ def build_update_request( "dataCollectionRuleName": _SERIALIZER.url("data_collection_rule_name", data_collection_rule_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -219,7 +222,7 @@ def build_delete_request( "dataCollectionRuleName": _SERIALIZER.url("data_collection_rule_name", data_collection_rule_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -248,6 +251,7 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list_by_resource_group( @@ -260,7 +264,6 @@ def list_by_resource_group( :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either DataCollectionRuleResource or the result of cls(response) :rtype: @@ -270,10 +273,12 @@ def list_by_resource_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-11-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2019-11-01-preview") + ) cls: ClsType[_models.DataCollectionRuleResourceListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -284,16 +289,14 @@ 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_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -304,14 +307,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("DataCollectionRuleResourceListResult", pipeline_response) @@ -321,11 +323,11 @@ def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -338,17 +340,12 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionRules" - } - @distributed_trace def list_by_subscription(self, **kwargs: Any) -> Iterable["_models.DataCollectionRuleResource"]: """Lists all data collection rules in the specified subscription. Lists all data collection rules in the specified subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either DataCollectionRuleResource or the result of cls(response) :rtype: @@ -358,10 +355,12 @@ def list_by_subscription(self, **kwargs: Any) -> Iterable["_models.DataCollectio _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-11-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2019-11-01-preview") + ) cls: ClsType[_models.DataCollectionRuleResourceListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -372,15 +371,13 @@ def list_by_subscription(self, **kwargs: Any) -> Iterable["_models.DataCollectio def prepare_request(next_link=None): if not next_link: - request = build_list_by_subscription_request( + _request = build_list_by_subscription_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_subscription.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -391,14 +388,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("DataCollectionRuleResourceListResult", pipeline_response) @@ -408,11 +404,11 @@ def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -425,10 +421,6 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_by_subscription.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/dataCollectionRules" - } - @distributed_trace def get( self, resource_group_name: str, data_collection_rule_name: str, **kwargs: Any @@ -443,12 +435,11 @@ def get( :param data_collection_rule_name: The name of the data collection rule. The name is case insensitive. Required. :type data_collection_rule_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: DataCollectionRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2019_11_01_preview.models.DataCollectionRuleResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -459,24 +450,24 @@ def get( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-11-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2019-11-01-preview") + ) cls: ClsType[_models.DataCollectionRuleResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, data_collection_rule_name=data_collection_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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -486,16 +477,12 @@ def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("DataCollectionRuleResource", pipeline_response) + deserialized = self._deserialize("DataCollectionRuleResource", 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.Insights/dataCollectionRules/{dataCollectionRuleName}" - } + return deserialized # type: ignore @overload def create( @@ -522,7 +509,6 @@ def create( :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: DataCollectionRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2019_11_01_preview.models.DataCollectionRuleResource :raises ~azure.core.exceptions.HttpResponseError: @@ -533,7 +519,7 @@ def create( self, resource_group_name: str, data_collection_rule_name: str, - body: Optional[IO] = None, + body: Optional[IO[bytes]] = None, *, content_type: str = "application/json", **kwargs: Any @@ -549,11 +535,10 @@ def create( insensitive. Required. :type data_collection_rule_name: str :param body: The payload. Default value is None. - :type body: IO + :type body: 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: DataCollectionRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2019_11_01_preview.models.DataCollectionRuleResource :raises ~azure.core.exceptions.HttpResponseError: @@ -564,7 +549,7 @@ def create( self, resource_group_name: str, data_collection_rule_name: str, - body: Optional[Union[_models.DataCollectionRuleResource, IO]] = None, + body: Optional[Union[_models.DataCollectionRuleResource, IO[bytes]]] = None, **kwargs: Any ) -> _models.DataCollectionRuleResource: """Creates or updates a data collection rule. @@ -577,18 +562,15 @@ def create( :param data_collection_rule_name: The name of the data collection rule. The name is case insensitive. Required. :type data_collection_rule_name: str - :param body: The payload. Is either a DataCollectionRuleResource type or a IO type. Default - value is None. - :type body: ~azure.mgmt.monitor.v2019_11_01_preview.models.DataCollectionRuleResource or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + :param body: The payload. Is either a DataCollectionRuleResource type or a IO[bytes] type. Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response + :type body: ~azure.mgmt.monitor.v2019_11_01_preview.models.DataCollectionRuleResource or + IO[bytes] :return: DataCollectionRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2019_11_01_preview.models.DataCollectionRuleResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -599,14 +581,16 @@ def create( _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", "2019-11-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2019-11-01-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.DataCollectionRuleResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(body, (IO, bytes)): + if isinstance(body, (IOBase, bytes)): _content = body else: if body is not None: @@ -614,7 +598,7 @@ def create( else: _json = None - request = build_create_request( + _request = build_create_request( resource_group_name=resource_group_name, data_collection_rule_name=data_collection_rule_name, subscription_id=self._config.subscription_id, @@ -622,16 +606,14 @@ def create( content_type=content_type, json=_json, content=_content, - template_url=self.create.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -641,21 +623,13 @@ def create( 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("DataCollectionRuleResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("DataCollectionRuleResource", pipeline_response) + deserialized = self._deserialize("DataCollectionRuleResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionRules/{dataCollectionRuleName}" - } - @overload def update( self, @@ -681,7 +655,6 @@ def update( :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: DataCollectionRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2019_11_01_preview.models.DataCollectionRuleResource :raises ~azure.core.exceptions.HttpResponseError: @@ -692,7 +665,7 @@ def update( self, resource_group_name: str, data_collection_rule_name: str, - body: Optional[IO] = None, + body: Optional[IO[bytes]] = None, *, content_type: str = "application/json", **kwargs: Any @@ -708,11 +681,10 @@ def update( insensitive. Required. :type data_collection_rule_name: str :param body: The payload. Default value is None. - :type body: IO + :type body: 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: DataCollectionRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2019_11_01_preview.models.DataCollectionRuleResource :raises ~azure.core.exceptions.HttpResponseError: @@ -723,7 +695,7 @@ def update( self, resource_group_name: str, data_collection_rule_name: str, - body: Optional[Union[_models.ResourceForUpdate, IO]] = None, + body: Optional[Union[_models.ResourceForUpdate, IO[bytes]]] = None, **kwargs: Any ) -> _models.DataCollectionRuleResource: """Updates part of a data collection rule. @@ -736,18 +708,14 @@ def update( :param data_collection_rule_name: The name of the data collection rule. The name is case insensitive. Required. :type data_collection_rule_name: str - :param body: The payload. Is either a ResourceForUpdate type or a IO type. Default value is - None. - :type body: ~azure.mgmt.monitor.v2019_11_01_preview.models.ResourceForUpdate 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 + :param body: The payload. Is either a ResourceForUpdate type or a IO[bytes] type. Default value + is None. + :type body: ~azure.mgmt.monitor.v2019_11_01_preview.models.ResourceForUpdate or IO[bytes] :return: DataCollectionRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2019_11_01_preview.models.DataCollectionRuleResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -758,14 +726,16 @@ def update( _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", "2019-11-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2019-11-01-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.DataCollectionRuleResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(body, (IO, bytes)): + if isinstance(body, (IOBase, bytes)): _content = body else: if body is not None: @@ -773,7 +743,7 @@ def update( else: _json = None - request = build_update_request( + _request = build_update_request( resource_group_name=resource_group_name, data_collection_rule_name=data_collection_rule_name, subscription_id=self._config.subscription_id, @@ -781,16 +751,14 @@ def update( 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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -800,16 +768,12 @@ def update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("DataCollectionRuleResource", pipeline_response) + deserialized = self._deserialize("DataCollectionRuleResource", 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.Insights/dataCollectionRules/{dataCollectionRuleName}" - } + return deserialized # type: ignore @distributed_trace def delete( # pylint: disable=inconsistent-return-statements @@ -825,12 +789,11 @@ def delete( # pylint: disable=inconsistent-return-statements :param data_collection_rule_name: The name of the data collection rule. The name is case insensitive. Required. :type data_collection_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, @@ -841,24 +804,24 @@ def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-11-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2019-11-01-preview") + ) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, data_collection_rule_name=data_collection_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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -869,8 +832,4 @@ def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionRules/{dataCollectionRuleName}" - } + return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_01_01_preview/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_01_01_preview/__init__.py index 2c7733bfd566..42cc62301757 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_01_01_preview/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_01_01_preview/__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 ._monitor_management_client import MonitorManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._monitor_management_client import MonitorManagementClient # type: ignore from ._version import VERSION __version__ = VERSION try: from ._patch import __all__ as _patch_all - from ._patch import * # 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__ = [ "MonitorManagementClient", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_01_01_preview/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_01_01_preview/_configuration.py index a38a4e147869..fcb85acbfe8b 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_01_01_preview/_configuration.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_01_01_preview/_configuration.py @@ -8,18 +8,16 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy from ._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MonitorManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class MonitorManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for MonitorManagementClient. Note that all parameters used to create this instance are saved as instance @@ -33,7 +31,6 @@ class MonitorManagementClientConfiguration(Configuration): # pylint: disable=to """ def __init__(self, credential: "TokenCredential", **kwargs: Any) -> None: - super(MonitorManagementClientConfiguration, self).__init__(**kwargs) api_version: str = kwargs.pop("api_version", "2020-01-01-preview") if credential is None: @@ -43,6 +40,7 @@ def __init__(self, credential: "TokenCredential", **kwargs: Any) -> None: self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-monitor/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -51,9 +49,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.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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_01_01_preview/_metadata.json b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_01_01_preview/_metadata.json index 3c94faf452bf..21d79c565643 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_01_01_preview/_metadata.json +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_01_01_preview/_metadata.json @@ -8,10 +8,10 @@ "host_value": "\"https://management.azure.com\"", "parameterized_host_template": null, "azure_arm": true, - "has_lro_operations": false, + "has_public_lro_operations": false, "client_side_validation": false, - "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"sdkcore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMAutoResourceProviderRegistrationPolicy\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}, \"stdlib\": {\"typing_extensions\": [\"Self\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"sdkcore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"AsyncARMAutoResourceProviderRegistrationPolicy\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}, \"stdlib\": {\"typing_extensions\": [\"Self\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "global_parameters": { "sync": { @@ -88,8 +88,8 @@ "credential_scopes": ["https://management.azure.com/.default"], "credential_call_sync": "ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", "credential_call_async": "AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", - "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "sync_imports": "{\"regular\": {\"sdkcore\": {\"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"regular\": {\"sdkcore\": {\"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "operation_groups": { "management_group_diagnostic_settings": "ManagementGroupDiagnosticSettingsOperations" diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_01_01_preview/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_01_01_preview/_monitor_management_client.py index 8c60f2a9d091..4c91f339389b 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_01_01_preview/_monitor_management_client.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_01_01_preview/_monitor_management_client.py @@ -8,9 +8,12 @@ from copy import deepcopy from typing import Any, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient +from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy from . import models as _models from .._serialization import Deserializer, Serializer @@ -18,11 +21,10 @@ from .operations import ManagementGroupDiagnosticSettingsOperations if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MonitorManagementClient: # pylint: disable=client-accepts-api-version-keyword +class MonitorManagementClient: """Monitor Management Client. :ivar management_group_diagnostic_settings: ManagementGroupDiagnosticSettingsOperations @@ -42,17 +44,35 @@ def __init__( self, credential: "TokenCredential", base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: self._config = MonitorManagementClientConfiguration(credential=credential, **kwargs) - self._client: ARMPipelineClient = ARMPipelineClient(base_url=base_url, config=self._config, **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), + 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=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.management_group_diagnostic_settings = ManagementGroupDiagnosticSettingsOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2020-01-01-preview" ) - 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 @@ -72,12 +92,12 @@ 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) -> None: self._client.close() - def __enter__(self) -> "MonitorManagementClient": + def __enter__(self) -> Self: self._client.__enter__() return self diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_01_01_preview/_vendor.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_01_01_preview/_vendor.py deleted file mode 100644 index bd0df84f5319..000000000000 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_01_01_preview/_vendor.py +++ /dev/null @@ -1,30 +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 typing import List, cast - -from azure.core.pipeline.transport import HttpRequest - - -def _convert_request(request, files=None): - data = request.content if not files else None - request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) - if files: - request.set_formdata_body(files) - return request - - -def _format_url_section(template, **kwargs): - components = template.split("/") - while components: - try: - return template.format(**kwargs) - except KeyError as key: - # Need the cast, as for some reasons "split" is typed as list[str | Any] - formatted_components = cast(List[str], template.split("/")) - components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] - template = "/".join(components) diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_01_01_preview/_version.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_01_01_preview/_version.py index 394ee7c0c03c..e5754a47ce68 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_01_01_preview/_version.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_01_01_preview/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "6.0.2" +VERSION = "1.0.0b1" diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_01_01_preview/aio/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_01_01_preview/aio/__init__.py index 2c151bb41c19..3df30ff42149 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_01_01_preview/aio/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_01_01_preview/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 ._monitor_management_client import MonitorManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._monitor_management_client import MonitorManagementClient # type: ignore try: from ._patch import __all__ as _patch_all - from ._patch import * # 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__ = [ "MonitorManagementClient", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_01_01_preview/aio/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_01_01_preview/aio/_configuration.py index 3c41728a4113..5c330f95f616 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_01_01_preview/aio/_configuration.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_01_01_preview/aio/_configuration.py @@ -8,18 +8,16 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy from .._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MonitorManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class MonitorManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for MonitorManagementClient. Note that all parameters used to create this instance are saved as instance @@ -33,7 +31,6 @@ class MonitorManagementClientConfiguration(Configuration): # pylint: disable=to """ def __init__(self, credential: "AsyncTokenCredential", **kwargs: Any) -> None: - super(MonitorManagementClientConfiguration, self).__init__(**kwargs) api_version: str = kwargs.pop("api_version", "2020-01-01-preview") if credential is None: @@ -43,6 +40,7 @@ def __init__(self, credential: "AsyncTokenCredential", **kwargs: Any) -> None: self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-monitor/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -51,9 +49,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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_01_01_preview/aio/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_01_01_preview/aio/_monitor_management_client.py index 85b824d043e7..551b0b1a67e1 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_01_01_preview/aio/_monitor_management_client.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_01_01_preview/aio/_monitor_management_client.py @@ -8,9 +8,12 @@ from copy import deepcopy from typing import Any, Awaitable, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient +from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy from .. import models as _models from ..._serialization import Deserializer, Serializer @@ -18,11 +21,10 @@ from .operations import ManagementGroupDiagnosticSettingsOperations if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MonitorManagementClient: # pylint: disable=client-accepts-api-version-keyword +class MonitorManagementClient: """Monitor Management Client. :ivar management_group_diagnostic_settings: ManagementGroupDiagnosticSettingsOperations @@ -42,17 +44,37 @@ def __init__( self, credential: "AsyncTokenCredential", base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: self._config = MonitorManagementClientConfiguration(credential=credential, **kwargs) - self._client: AsyncARMPipelineClient = AsyncARMPipelineClient(base_url=base_url, config=self._config, **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=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.management_group_diagnostic_settings = ManagementGroupDiagnosticSettingsOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2020-01-01-preview" ) - 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 @@ -72,12 +94,12 @@ 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) -> "MonitorManagementClient": + async def __aenter__(self) -> Self: await self._client.__aenter__() return self diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_01_01_preview/aio/operations/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_01_01_preview/aio/operations/__init__.py index df848453257b..05e4534d6410 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_01_01_preview/aio/operations/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_01_01_preview/aio/operations/__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 ._management_group_diagnostic_settings_operations import ManagementGroupDiagnosticSettingsOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._management_group_diagnostic_settings_operations import ManagementGroupDiagnosticSettingsOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ "ManagementGroupDiagnosticSettingsOperations", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_01_01_preview/aio/operations/_management_group_diagnostic_settings_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_01_01_preview/aio/operations/_management_group_diagnostic_settings_operations.py index 1bdef69a47ed..5b9343e9e961 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_01_01_preview/aio/operations/_management_group_diagnostic_settings_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_01_01_preview/aio/operations/_management_group_diagnostic_settings_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload import urllib.parse @@ -19,15 +20,13 @@ 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 ...operations._management_group_diagnostic_settings_operations import ( build_create_or_update_request, build_delete_request, @@ -35,11 +34,15 @@ build_list_request, ) +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class ManagementGroupDiagnosticSettingsOperations: +class ManagementGroupDiagnosticSettingsOperations: # pylint: disable=name-too-long """ .. warning:: **DO NOT** instantiate this class directly. @@ -57,6 +60,7 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace_async async def get( @@ -68,13 +72,12 @@ async def get( :type management_group_id: str :param name: The name of the diagnostic setting. Required. :type name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ManagementGroupDiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2020_01_01_preview.models.ManagementGroupDiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -85,23 +88,23 @@ async def get( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-01-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2020-01-01-preview") + ) cls: ClsType[_models.ManagementGroupDiagnosticSettingsResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( management_group_id=management_group_id, name=name, api_version=api_version, - template_url=self.get.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -111,16 +114,12 @@ async def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ManagementGroupDiagnosticSettingsResource", pipeline_response) + deserialized = self._deserialize("ManagementGroupDiagnosticSettingsResource", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get.metadata = { - "url": "/providers/microsoft.management/managementGroups/{managementGroupId}/providers/microsoft.insights/diagnosticSettings/{name}" - } + return deserialized # type: ignore @overload async def create_or_update( @@ -144,7 +143,6 @@ async def create_or_update( :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: ManagementGroupDiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2020_01_01_preview.models.ManagementGroupDiagnosticSettingsResource @@ -156,7 +154,7 @@ async def create_or_update( self, management_group_id: str, name: str, - parameters: IO, + parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -168,11 +166,10 @@ async def create_or_update( :param name: The name of the diagnostic setting. Required. :type name: str :param parameters: Parameters supplied to the operation. Required. - :type parameters: IO + :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: ManagementGroupDiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2020_01_01_preview.models.ManagementGroupDiagnosticSettingsResource @@ -184,7 +181,7 @@ async def create_or_update( self, management_group_id: str, name: str, - parameters: Union[_models.ManagementGroupDiagnosticSettingsResource, IO], + parameters: Union[_models.ManagementGroupDiagnosticSettingsResource, IO[bytes]], **kwargs: Any ) -> _models.ManagementGroupDiagnosticSettingsResource: """Creates or updates management group diagnostic settings for the specified resource. @@ -194,19 +191,16 @@ async def create_or_update( :param name: The name of the diagnostic setting. Required. :type name: str :param parameters: Parameters supplied to the operation. Is either a - ManagementGroupDiagnosticSettingsResource type or a IO type. Required. + ManagementGroupDiagnosticSettingsResource type or a IO[bytes] type. Required. :type parameters: - ~azure.mgmt.monitor.v2020_01_01_preview.models.ManagementGroupDiagnosticSettingsResource 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 + ~azure.mgmt.monitor.v2020_01_01_preview.models.ManagementGroupDiagnosticSettingsResource or + IO[bytes] :return: ManagementGroupDiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2020_01_01_preview.models.ManagementGroupDiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -217,35 +211,35 @@ async def create_or_update( _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", "2020-01-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2020-01-01-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ManagementGroupDiagnosticSettingsResource] = 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, "ManagementGroupDiagnosticSettingsResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( management_group_id=management_group_id, name=name, 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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -255,33 +249,26 @@ async def create_or_update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ManagementGroupDiagnosticSettingsResource", pipeline_response) + deserialized = self._deserialize("ManagementGroupDiagnosticSettingsResource", 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": "/providers/microsoft.management/managementGroups/{managementGroupId}/providers/microsoft.insights/diagnosticSettings/{name}" - } + return deserialized # type: ignore @distributed_trace_async - async def delete( # pylint: disable=inconsistent-return-statements - self, management_group_id: str, name: str, **kwargs: Any - ) -> None: + async def delete(self, management_group_id: str, name: str, **kwargs: Any) -> None: """Deletes existing management group diagnostic settings for the specified resource. :param management_group_id: The management group id. Required. :type management_group_id: str :param name: The name of the diagnostic setting. Required. :type 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, @@ -292,23 +279,23 @@ async def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-01-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2020-01-01-preview") + ) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( management_group_id=management_group_id, name=name, api_version=api_version, - template_url=self.delete.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -319,21 +306,17 @@ async def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/providers/microsoft.management/managementGroups/{managementGroupId}/providers/microsoft.insights/diagnosticSettings/{name}" - } + return cls(pipeline_response, None, {}) # type: ignore @distributed_trace def list( self, management_group_id: str, **kwargs: Any ) -> AsyncIterable["_models.ManagementGroupDiagnosticSettingsResource"]: + # pylint: disable=line-too-long """Gets the active management group diagnostic settings list for the specified management group. :param management_group_id: The management group id. Required. :type management_group_id: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ManagementGroupDiagnosticSettingsResource or the result of cls(response) :rtype: @@ -343,10 +326,12 @@ def list( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-01-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2020-01-01-preview") + ) cls: ClsType[_models.ManagementGroupDiagnosticSettingsResourceCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -357,15 +342,13 @@ def list( def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( management_group_id=management_group_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) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -376,14 +359,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("ManagementGroupDiagnosticSettingsResourceCollection", pipeline_response) @@ -393,11 +375,11 @@ async def extract_data(pipeline_response): return None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -409,7 +391,3 @@ async def get_next(next_link=None): return pipeline_response return AsyncItemPaged(get_next, extract_data) - - list.metadata = { - "url": "/providers/microsoft.management/managementGroups/{managementGroupId}/providers/microsoft.insights/diagnosticSettings" - } diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_01_01_preview/models/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_01_01_preview/models/__init__.py index bb05df8b79ba..393c909594f3 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_01_01_preview/models/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_01_01_preview/models/__init__.py @@ -5,14 +5,23 @@ # 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 ErrorResponse -from ._models_py3 import ManagementGroupDiagnosticSettingsResource -from ._models_py3 import ManagementGroupDiagnosticSettingsResourceCollection -from ._models_py3 import ManagementGroupLogSettings -from ._models_py3 import ManagementGroupProxyOnlyResource +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models_py3 import ( # type: ignore + ErrorResponse, + ManagementGroupDiagnosticSettingsResource, + ManagementGroupDiagnosticSettingsResourceCollection, + ManagementGroupLogSettings, + ManagementGroupProxyOnlyResource, +) from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ @@ -22,5 +31,5 @@ "ManagementGroupLogSettings", "ManagementGroupProxyOnlyResource", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_01_01_preview/models/_models_py3.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_01_01_preview/models/_models_py3.py index d87ff2c9d569..f0791fb0a742 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_01_01_preview/models/_models_py3.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_01_01_preview/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. @@ -12,7 +11,6 @@ from ... import _serialization if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from .. import models as _models @@ -82,7 +80,7 @@ def __init__(self, *, location: Optional[str] = None, **kwargs: Any) -> None: self.location = location -class ManagementGroupDiagnosticSettingsResource(ManagementGroupProxyOnlyResource): +class ManagementGroupDiagnosticSettingsResource(ManagementGroupProxyOnlyResource): # pylint: disable=name-too-long """The management group diagnostic setting resource. Variables are only populated by the server, and will be ignored when sending a request. @@ -110,7 +108,7 @@ class ManagementGroupDiagnosticSettingsResource(ManagementGroupProxyOnlyResource :vartype logs: list[~azure.mgmt.monitor.v2020_01_01_preview.models.ManagementGroupLogSettings] :ivar workspace_id: The full ARM resource ID of the Log Analytics workspace to which you would like to send Diagnostic Logs. Example: - /subscriptions/4b9e8510-67ab-4e9a-95a9-e2f1e570ea9c/resourceGroups/insights-integration/providers/Microsoft.OperationalInsights/workspaces/viruela2. + /subscriptions/4b9e8510-67ab-4e9a-95a9-e2f1e570ea9c/resourceGroups/insights-integration/providers/Microsoft.OperationalInsights/workspaces/viruela2. # pylint: disable=line-too-long :vartype workspace_id: str """ @@ -164,7 +162,7 @@ def __init__( list[~azure.mgmt.monitor.v2020_01_01_preview.models.ManagementGroupLogSettings] :keyword workspace_id: The full ARM resource ID of the Log Analytics workspace to which you would like to send Diagnostic Logs. Example: - /subscriptions/4b9e8510-67ab-4e9a-95a9-e2f1e570ea9c/resourceGroups/insights-integration/providers/Microsoft.OperationalInsights/workspaces/viruela2. + /subscriptions/4b9e8510-67ab-4e9a-95a9-e2f1e570ea9c/resourceGroups/insights-integration/providers/Microsoft.OperationalInsights/workspaces/viruela2. # pylint: disable=line-too-long :paramtype workspace_id: str """ super().__init__(location=location, **kwargs) @@ -176,7 +174,7 @@ def __init__( self.workspace_id = workspace_id -class ManagementGroupDiagnosticSettingsResourceCollection(_serialization.Model): +class ManagementGroupDiagnosticSettingsResourceCollection(_serialization.Model): # pylint: disable=name-too-long """Represents a collection of management group diagnostic settings resources. :ivar value: The collection of management group diagnostic settings resources. @@ -203,7 +201,7 @@ def __init__( class ManagementGroupLogSettings(_serialization.Model): """Part of Management Group diagnostic setting. Specifies the settings for a particular log. - 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 category: Name of a Management Group Diagnostic Log category for a resource type this setting is applied to. Required. diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_01_01_preview/operations/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_01_01_preview/operations/__init__.py index df848453257b..05e4534d6410 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_01_01_preview/operations/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_01_01_preview/operations/__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 ._management_group_diagnostic_settings_operations import ManagementGroupDiagnosticSettingsOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._management_group_diagnostic_settings_operations import ManagementGroupDiagnosticSettingsOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ "ManagementGroupDiagnosticSettingsOperations", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_01_01_preview/operations/_management_group_diagnostic_settings_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_01_01_preview/operations/_management_group_diagnostic_settings_operations.py index eed4e536f9e6..80ae785e0ade 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_01_01_preview/operations/_management_group_diagnostic_settings_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_01_01_preview/operations/_management_group_diagnostic_settings_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload import urllib.parse @@ -19,16 +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, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -53,7 +56,7 @@ def build_get_request(management_group_id: str, name: str, **kwargs: Any) -> Htt "name": _SERIALIZER.url("name", name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -82,7 +85,7 @@ def build_create_or_update_request(management_group_id: str, name: str, **kwargs "name": _SERIALIZER.url("name", name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -112,7 +115,7 @@ def build_delete_request(management_group_id: str, name: str, **kwargs: Any) -> "name": _SERIALIZER.url("name", name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -139,7 +142,7 @@ def build_list_request(management_group_id: str, **kwargs: Any) -> HttpRequest: "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str", skip_quote=True), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -150,7 +153,7 @@ def build_list_request(management_group_id: str, **kwargs: Any) -> HttpRequest: return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -class ManagementGroupDiagnosticSettingsOperations: +class ManagementGroupDiagnosticSettingsOperations: # pylint: disable=name-too-long """ .. warning:: **DO NOT** instantiate this class directly. @@ -168,6 +171,7 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def get( @@ -179,13 +183,12 @@ def get( :type management_group_id: str :param name: The name of the diagnostic setting. Required. :type name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ManagementGroupDiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2020_01_01_preview.models.ManagementGroupDiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -196,23 +199,23 @@ def get( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-01-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2020-01-01-preview") + ) cls: ClsType[_models.ManagementGroupDiagnosticSettingsResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( management_group_id=management_group_id, name=name, api_version=api_version, - template_url=self.get.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -222,16 +225,12 @@ def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ManagementGroupDiagnosticSettingsResource", pipeline_response) + deserialized = self._deserialize("ManagementGroupDiagnosticSettingsResource", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get.metadata = { - "url": "/providers/microsoft.management/managementGroups/{managementGroupId}/providers/microsoft.insights/diagnosticSettings/{name}" - } + return deserialized # type: ignore @overload def create_or_update( @@ -255,7 +254,6 @@ def create_or_update( :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: ManagementGroupDiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2020_01_01_preview.models.ManagementGroupDiagnosticSettingsResource @@ -267,7 +265,7 @@ def create_or_update( self, management_group_id: str, name: str, - parameters: IO, + parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -279,11 +277,10 @@ def create_or_update( :param name: The name of the diagnostic setting. Required. :type name: str :param parameters: Parameters supplied to the operation. Required. - :type parameters: IO + :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: ManagementGroupDiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2020_01_01_preview.models.ManagementGroupDiagnosticSettingsResource @@ -295,7 +292,7 @@ def create_or_update( self, management_group_id: str, name: str, - parameters: Union[_models.ManagementGroupDiagnosticSettingsResource, IO], + parameters: Union[_models.ManagementGroupDiagnosticSettingsResource, IO[bytes]], **kwargs: Any ) -> _models.ManagementGroupDiagnosticSettingsResource: """Creates or updates management group diagnostic settings for the specified resource. @@ -305,19 +302,16 @@ def create_or_update( :param name: The name of the diagnostic setting. Required. :type name: str :param parameters: Parameters supplied to the operation. Is either a - ManagementGroupDiagnosticSettingsResource type or a IO type. Required. + ManagementGroupDiagnosticSettingsResource type or a IO[bytes] type. Required. :type parameters: - ~azure.mgmt.monitor.v2020_01_01_preview.models.ManagementGroupDiagnosticSettingsResource 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 + ~azure.mgmt.monitor.v2020_01_01_preview.models.ManagementGroupDiagnosticSettingsResource or + IO[bytes] :return: ManagementGroupDiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2020_01_01_preview.models.ManagementGroupDiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -328,35 +322,35 @@ def create_or_update( _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", "2020-01-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2020-01-01-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ManagementGroupDiagnosticSettingsResource] = 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, "ManagementGroupDiagnosticSettingsResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( management_group_id=management_group_id, name=name, 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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -366,16 +360,12 @@ def create_or_update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ManagementGroupDiagnosticSettingsResource", pipeline_response) + deserialized = self._deserialize("ManagementGroupDiagnosticSettingsResource", 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": "/providers/microsoft.management/managementGroups/{managementGroupId}/providers/microsoft.insights/diagnosticSettings/{name}" - } + return deserialized # type: ignore @distributed_trace def delete( # pylint: disable=inconsistent-return-statements @@ -387,12 +377,11 @@ def delete( # pylint: disable=inconsistent-return-statements :type management_group_id: str :param name: The name of the diagnostic setting. Required. :type 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, @@ -403,23 +392,23 @@ def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-01-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2020-01-01-preview") + ) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( management_group_id=management_group_id, name=name, api_version=api_version, - template_url=self.delete.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -430,21 +419,17 @@ def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/providers/microsoft.management/managementGroups/{managementGroupId}/providers/microsoft.insights/diagnosticSettings/{name}" - } + return cls(pipeline_response, None, {}) # type: ignore @distributed_trace def list( self, management_group_id: str, **kwargs: Any ) -> Iterable["_models.ManagementGroupDiagnosticSettingsResource"]: + # pylint: disable=line-too-long """Gets the active management group diagnostic settings list for the specified management group. :param management_group_id: The management group id. Required. :type management_group_id: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ManagementGroupDiagnosticSettingsResource or the result of cls(response) :rtype: @@ -454,10 +439,12 @@ def list( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-01-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2020-01-01-preview") + ) cls: ClsType[_models.ManagementGroupDiagnosticSettingsResourceCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -468,15 +455,13 @@ def list( def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( management_group_id=management_group_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) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -487,14 +472,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("ManagementGroupDiagnosticSettingsResourceCollection", pipeline_response) @@ -504,11 +488,11 @@ def extract_data(pipeline_response): return None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -520,7 +504,3 @@ def get_next(next_link=None): return pipeline_response return ItemPaged(get_next, extract_data) - - list.metadata = { - "url": "/providers/microsoft.management/managementGroups/{managementGroupId}/providers/microsoft.insights/diagnosticSettings" - } diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_05_01_preview/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_05_01_preview/__init__.py index 2c7733bfd566..42cc62301757 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_05_01_preview/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_05_01_preview/__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 ._monitor_management_client import MonitorManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._monitor_management_client import MonitorManagementClient # type: ignore from ._version import VERSION __version__ = VERSION try: from ._patch import __all__ as _patch_all - from ._patch import * # 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__ = [ "MonitorManagementClient", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_05_01_preview/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_05_01_preview/_configuration.py index fe6231bcf324..3941d0d6f328 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_05_01_preview/_configuration.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_05_01_preview/_configuration.py @@ -8,18 +8,16 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy from ._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MonitorManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class MonitorManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for MonitorManagementClient. Note that all parameters used to create this instance are saved as instance @@ -35,7 +33,6 @@ class MonitorManagementClientConfiguration(Configuration): # pylint: disable=to """ def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: - super(MonitorManagementClientConfiguration, self).__init__(**kwargs) api_version: str = kwargs.pop("api_version", "2020-05-01-preview") if credential is None: @@ -48,6 +45,7 @@ def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-monitor/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -56,9 +54,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.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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_05_01_preview/_metadata.json b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_05_01_preview/_metadata.json index 660ad49963d5..f78bb1b40275 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_05_01_preview/_metadata.json +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_05_01_preview/_metadata.json @@ -8,10 +8,10 @@ "host_value": "\"https://management.azure.com\"", "parameterized_host_template": null, "azure_arm": true, - "has_lro_operations": false, + "has_public_lro_operations": false, "client_side_validation": false, - "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"sdkcore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMAutoResourceProviderRegistrationPolicy\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}, \"stdlib\": {\"typing_extensions\": [\"Self\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"sdkcore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"AsyncARMAutoResourceProviderRegistrationPolicy\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}, \"stdlib\": {\"typing_extensions\": [\"Self\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "global_parameters": { "sync": { @@ -101,8 +101,8 @@ "credential_scopes": ["https://management.azure.com/.default"], "credential_call_sync": "ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", "credential_call_async": "AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", - "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "sync_imports": "{\"regular\": {\"sdkcore\": {\"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"regular\": {\"sdkcore\": {\"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "operation_groups": { "scheduled_query_rules": "ScheduledQueryRulesOperations" diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_05_01_preview/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_05_01_preview/_monitor_management_client.py index 820af6112cc5..46d4402a9a1a 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_05_01_preview/_monitor_management_client.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_05_01_preview/_monitor_management_client.py @@ -8,9 +8,12 @@ from copy import deepcopy from typing import Any, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient +from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy from . import models as _models from .._serialization import Deserializer, Serializer @@ -18,11 +21,10 @@ from .operations import ScheduledQueryRulesOperations if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MonitorManagementClient: # pylint: disable=client-accepts-api-version-keyword +class MonitorManagementClient: """Monitor Management Client. :ivar scheduled_query_rules: ScheduledQueryRulesOperations operations @@ -49,17 +51,35 @@ def __init__( self._config = MonitorManagementClientConfiguration( credential=credential, subscription_id=subscription_id, **kwargs ) - self._client: ARMPipelineClient = ARMPipelineClient(base_url=base_url, config=self._config, **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), + 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=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.scheduled_query_rules = ScheduledQueryRulesOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2020-05-01-preview" ) - 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 @@ -79,12 +99,12 @@ 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) -> None: self._client.close() - def __enter__(self) -> "MonitorManagementClient": + def __enter__(self) -> Self: self._client.__enter__() return self diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_05_01_preview/_vendor.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_05_01_preview/_vendor.py deleted file mode 100644 index bd0df84f5319..000000000000 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_05_01_preview/_vendor.py +++ /dev/null @@ -1,30 +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 typing import List, cast - -from azure.core.pipeline.transport import HttpRequest - - -def _convert_request(request, files=None): - data = request.content if not files else None - request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) - if files: - request.set_formdata_body(files) - return request - - -def _format_url_section(template, **kwargs): - components = template.split("/") - while components: - try: - return template.format(**kwargs) - except KeyError as key: - # Need the cast, as for some reasons "split" is typed as list[str | Any] - formatted_components = cast(List[str], template.split("/")) - components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] - template = "/".join(components) diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_05_01_preview/_version.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_05_01_preview/_version.py index 394ee7c0c03c..e5754a47ce68 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_05_01_preview/_version.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_05_01_preview/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "6.0.2" +VERSION = "1.0.0b1" diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_05_01_preview/aio/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_05_01_preview/aio/__init__.py index 2c151bb41c19..3df30ff42149 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_05_01_preview/aio/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_05_01_preview/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 ._monitor_management_client import MonitorManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._monitor_management_client import MonitorManagementClient # type: ignore try: from ._patch import __all__ as _patch_all - from ._patch import * # 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__ = [ "MonitorManagementClient", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_05_01_preview/aio/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_05_01_preview/aio/_configuration.py index 2f135477387f..6f3fe6a2f8ab 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_05_01_preview/aio/_configuration.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_05_01_preview/aio/_configuration.py @@ -8,18 +8,16 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy from .._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MonitorManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class MonitorManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for MonitorManagementClient. Note that all parameters used to create this instance are saved as instance @@ -35,7 +33,6 @@ class MonitorManagementClientConfiguration(Configuration): # pylint: disable=to """ def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: - super(MonitorManagementClientConfiguration, self).__init__(**kwargs) api_version: str = kwargs.pop("api_version", "2020-05-01-preview") if credential is None: @@ -48,6 +45,7 @@ def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **k self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-monitor/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -56,9 +54,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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_05_01_preview/aio/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_05_01_preview/aio/_monitor_management_client.py index 5332b493b426..e2e77dd5fd6c 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_05_01_preview/aio/_monitor_management_client.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_05_01_preview/aio/_monitor_management_client.py @@ -8,9 +8,12 @@ from copy import deepcopy from typing import Any, Awaitable, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient +from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy from .. import models as _models from ..._serialization import Deserializer, Serializer @@ -18,11 +21,10 @@ from .operations import ScheduledQueryRulesOperations if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MonitorManagementClient: # pylint: disable=client-accepts-api-version-keyword +class MonitorManagementClient: """Monitor Management Client. :ivar scheduled_query_rules: ScheduledQueryRulesOperations operations @@ -49,17 +51,37 @@ def __init__( self._config = MonitorManagementClientConfiguration( credential=credential, subscription_id=subscription_id, **kwargs ) - self._client: AsyncARMPipelineClient = AsyncARMPipelineClient(base_url=base_url, config=self._config, **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=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.scheduled_query_rules = ScheduledQueryRulesOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2020-05-01-preview" ) - 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 @@ -79,12 +101,12 @@ 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) -> "MonitorManagementClient": + async def __aenter__(self) -> Self: await self._client.__aenter__() return self diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_05_01_preview/aio/operations/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_05_01_preview/aio/operations/__init__.py index e010c281d4fc..795e91ef6843 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_05_01_preview/aio/operations/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_05_01_preview/aio/operations/__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 ._scheduled_query_rules_operations import ScheduledQueryRulesOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._scheduled_query_rules_operations import ScheduledQueryRulesOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ "ScheduledQueryRulesOperations", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_05_01_preview/aio/operations/_scheduled_query_rules_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_05_01_preview/aio/operations/_scheduled_query_rules_operations.py index 5983bcef6803..e9f3f0d0b000 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_05_01_preview/aio/operations/_scheduled_query_rules_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_05_01_preview/aio/operations/_scheduled_query_rules_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload import urllib.parse @@ -19,15 +20,13 @@ 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 ...operations._scheduled_query_rules_operations import ( build_create_or_update_request, build_delete_request, @@ -37,6 +36,10 @@ build_update_request, ) +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -59,12 +62,13 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.ScheduledQueryRuleResource"]: + # pylint: disable=line-too-long """Retrieve a scheduled query rule definitions in a subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ScheduledQueryRuleResource or the result of cls(response) :rtype: @@ -74,10 +78,12 @@ def list_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.Schedule _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2020-05-01-preview") + ) cls: ClsType[_models.ScheduledQueryRuleResourceCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -88,15 +94,13 @@ def list_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.Schedule def prepare_request(next_link=None): if not next_link: - request = build_list_by_subscription_request( + _request = build_list_by_subscription_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_subscription.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -107,14 +111,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("ScheduledQueryRuleResourceCollection", pipeline_response) @@ -124,11 +127,11 @@ async def extract_data(pipeline_response): return None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -141,20 +144,16 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_by_subscription.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/scheduledQueryRules" - } - @distributed_trace def list_by_resource_group( self, resource_group_name: str, **kwargs: Any ) -> AsyncIterable["_models.ScheduledQueryRuleResource"]: + # pylint: disable=line-too-long """Retrieve scheduled query rule definitions in a resource group. :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ScheduledQueryRuleResource or the result of cls(response) :rtype: @@ -164,10 +163,12 @@ def list_by_resource_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2020-05-01-preview") + ) cls: ClsType[_models.ScheduledQueryRuleResourceCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -178,16 +179,14 @@ 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_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -198,14 +197,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("ScheduledQueryRuleResourceCollection", pipeline_response) @@ -215,11 +213,11 @@ async def extract_data(pipeline_response): return None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -232,10 +230,6 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/scheduledQueryRules" - } - @distributed_trace_async async def get(self, resource_group_name: str, rule_name: str, **kwargs: Any) -> _models.ScheduledQueryRuleResource: """Retrieve an scheduled query rule definition. @@ -245,12 +239,11 @@ async def get(self, resource_group_name: str, rule_name: str, **kwargs: Any) -> :type resource_group_name: str :param rule_name: The name of the rule. Required. :type rule_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ScheduledQueryRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2020_05_01_preview.models.ScheduledQueryRuleResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -261,24 +254,24 @@ async def get(self, resource_group_name: str, rule_name: str, **kwargs: Any) -> _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2020-05-01-preview") + ) cls: ClsType[_models.ScheduledQueryRuleResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, rule_name=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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -288,16 +281,12 @@ async def get(self, resource_group_name: str, rule_name: str, **kwargs: Any) -> error = self._deserialize.failsafe_deserialize(_models.ErrorContract, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ScheduledQueryRuleResource", pipeline_response) + deserialized = self._deserialize("ScheduledQueryRuleResource", 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.Insights/scheduledQueryRules/{ruleName}" - } + return deserialized # type: ignore @overload async def create_or_update( @@ -321,7 +310,6 @@ async def create_or_update( :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: ScheduledQueryRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2020_05_01_preview.models.ScheduledQueryRuleResource :raises ~azure.core.exceptions.HttpResponseError: @@ -332,7 +320,7 @@ async def create_or_update( self, resource_group_name: str, rule_name: str, - parameters: IO, + parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -345,11 +333,10 @@ async def create_or_update( :param rule_name: The name of the rule. Required. :type rule_name: str :param parameters: The parameters of the rule to create or update. Required. - :type parameters: IO + :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: ScheduledQueryRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2020_05_01_preview.models.ScheduledQueryRuleResource :raises ~azure.core.exceptions.HttpResponseError: @@ -360,7 +347,7 @@ async def create_or_update( self, resource_group_name: str, rule_name: str, - parameters: Union[_models.ScheduledQueryRuleResource, IO], + parameters: Union[_models.ScheduledQueryRuleResource, IO[bytes]], **kwargs: Any ) -> _models.ScheduledQueryRuleResource: """Creates or updates a scheduled query rule. @@ -371,18 +358,14 @@ async def create_or_update( :param rule_name: The name of the rule. Required. :type rule_name: str :param parameters: The parameters of the rule to create or update. Is either a - ScheduledQueryRuleResource type or a IO type. Required. + ScheduledQueryRuleResource type or a IO[bytes] type. Required. :type parameters: ~azure.mgmt.monitor.v2020_05_01_preview.models.ScheduledQueryRuleResource 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 + IO[bytes] :return: ScheduledQueryRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2020_05_01_preview.models.ScheduledQueryRuleResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -393,19 +376,21 @@ async def create_or_update( _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", "2020-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2020-05-01-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ScheduledQueryRuleResource] = 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, "ScheduledQueryRuleResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, rule_name=rule_name, subscription_id=self._config.subscription_id, @@ -413,16 +398,14 @@ async def create_or_update( 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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -432,21 +415,13 @@ async def create_or_update( error = self._deserialize.failsafe_deserialize(_models.ErrorContract, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if response.status_code == 200: - deserialized = self._deserialize("ScheduledQueryRuleResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("ScheduledQueryRuleResource", pipeline_response) + deserialized = self._deserialize("ScheduledQueryRuleResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/scheduledQueryRules/{ruleName}" - } - @overload async def update( self, @@ -470,7 +445,6 @@ async def update( :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: ScheduledQueryRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2020_05_01_preview.models.ScheduledQueryRuleResource :raises ~azure.core.exceptions.HttpResponseError: @@ -481,7 +455,7 @@ async def update( self, resource_group_name: str, rule_name: str, - parameters: IO, + parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -494,11 +468,10 @@ async def update( :param rule_name: The name of the rule. Required. :type rule_name: str :param parameters: The parameters of the rule to update. Required. - :type parameters: IO + :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: ScheduledQueryRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2020_05_01_preview.models.ScheduledQueryRuleResource :raises ~azure.core.exceptions.HttpResponseError: @@ -509,7 +482,7 @@ async def update( self, resource_group_name: str, rule_name: str, - parameters: Union[_models.ScheduledQueryRuleResourcePatch, IO], + parameters: Union[_models.ScheduledQueryRuleResourcePatch, IO[bytes]], **kwargs: Any ) -> _models.ScheduledQueryRuleResource: """Update a scheduled query rule. @@ -520,18 +493,14 @@ async def update( :param rule_name: The name of the rule. Required. :type rule_name: str :param parameters: The parameters of the rule to update. Is either a - ScheduledQueryRuleResourcePatch type or a IO type. Required. + ScheduledQueryRuleResourcePatch type or a IO[bytes] type. Required. :type parameters: - ~azure.mgmt.monitor.v2020_05_01_preview.models.ScheduledQueryRuleResourcePatch 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 + ~azure.mgmt.monitor.v2020_05_01_preview.models.ScheduledQueryRuleResourcePatch or IO[bytes] :return: ScheduledQueryRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2020_05_01_preview.models.ScheduledQueryRuleResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -542,19 +511,21 @@ async def update( _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", "2020-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2020-05-01-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ScheduledQueryRuleResource] = 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, "ScheduledQueryRuleResourcePatch") - request = build_update_request( + _request = build_update_request( resource_group_name=resource_group_name, rule_name=rule_name, subscription_id=self._config.subscription_id, @@ -562,16 +533,14 @@ async def update( 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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -581,21 +550,15 @@ async def update( error = self._deserialize.failsafe_deserialize(_models.ErrorContract, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ScheduledQueryRuleResource", pipeline_response) + deserialized = self._deserialize("ScheduledQueryRuleResource", 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.Insights/scheduledQueryRules/{ruleName}" - } + return deserialized # type: ignore @distributed_trace_async - async def delete( # pylint: disable=inconsistent-return-statements - self, resource_group_name: str, rule_name: str, **kwargs: Any - ) -> None: + async def delete(self, resource_group_name: str, rule_name: str, **kwargs: Any) -> None: """Deletes a scheduled query rule. :param resource_group_name: The name of the resource group. The name is case insensitive. @@ -603,12 +566,11 @@ async def delete( # pylint: disable=inconsistent-return-statements :type resource_group_name: str :param rule_name: The name of the rule. Required. :type 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, @@ -619,24 +581,24 @@ async def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2020-05-01-preview") + ) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, rule_name=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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -647,8 +609,4 @@ async def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/scheduledQueryRules/{ruleName}" - } + return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_05_01_preview/models/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_05_01_preview/models/__init__.py index 808b00e8d2db..9016a2ef512d 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_05_01_preview/models/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_05_01_preview/models/__init__.py @@ -5,27 +5,38 @@ # 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 Action -from ._models_py3 import Condition -from ._models_py3 import ConditionFailingPeriods -from ._models_py3 import Dimension -from ._models_py3 import ErrorAdditionalInfo -from ._models_py3 import ErrorContract -from ._models_py3 import ErrorResponse -from ._models_py3 import Resource -from ._models_py3 import ScheduledQueryRuleCriteria -from ._models_py3 import ScheduledQueryRuleResource -from ._models_py3 import ScheduledQueryRuleResourceCollection -from ._models_py3 import ScheduledQueryRuleResourcePatch -from ._models_py3 import TrackedResource +from typing import TYPE_CHECKING -from ._monitor_management_client_enums import AlertSeverity -from ._monitor_management_client_enums import ConditionOperator -from ._monitor_management_client_enums import DimensionOperator -from ._monitor_management_client_enums import TimeAggregation +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models_py3 import ( # type: ignore + Action, + Condition, + ConditionFailingPeriods, + Dimension, + ErrorAdditionalInfo, + ErrorContract, + ErrorResponse, + Resource, + ScheduledQueryRuleCriteria, + ScheduledQueryRuleResource, + ScheduledQueryRuleResourceCollection, + ScheduledQueryRuleResourcePatch, + TrackedResource, +) + +from ._monitor_management_client_enums import ( # type: ignore + AlertSeverity, + ConditionOperator, + DimensionOperator, + TimeAggregation, +) from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ @@ -47,5 +58,5 @@ "DimensionOperator", "TimeAggregation", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_05_01_preview/models/_models_py3.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_05_01_preview/models/_models_py3.py index 637060da25af..1ad205db2c33 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_05_01_preview/models/_models_py3.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_05_01_preview/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. @@ -13,7 +12,6 @@ from ... import _serialization if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from .. import models as _models @@ -52,7 +50,7 @@ def __init__( class Condition(_serialization.Model): """A condition of the scheduled query rule. - 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 query: Log query alert. :vartype query: str @@ -181,7 +179,7 @@ def __init__( class Dimension(_serialization.Model): """Dimension splitting and filtering definition. - 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: Name of the dimension. Required. :vartype name: str @@ -321,7 +319,7 @@ class Resource(_serialization.Model): 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}. + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long :vartype id: str :ivar name: The name of the resource. :vartype name: str @@ -376,10 +374,10 @@ 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: Fully qualified resource ID for the resource. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long :vartype id: str :ivar name: The name of the resource. :vartype name: str @@ -419,15 +417,15 @@ def __init__(self, *, location: str, tags: Optional[Dict[str, str]] = None, **kw self.location = location -class ScheduledQueryRuleResource(TrackedResource): # pylint: disable=too-many-instance-attributes +class ScheduledQueryRuleResource(TrackedResource): """The scheduled query rule 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: Fully qualified resource ID for the resource. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long :vartype id: str :ivar name: The name of the resource. :vartype name: str @@ -620,7 +618,7 @@ def __init__(self, *, value: Optional[List["_models.ScheduledQueryRuleResource"] self.value = value -class ScheduledQueryRuleResourcePatch(_serialization.Model): # pylint: disable=too-many-instance-attributes +class ScheduledQueryRuleResourcePatch(_serialization.Model): """The scheduled query rule resource for patch operations. Variables are only populated by the server, and will be ignored when sending a request. diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_05_01_preview/operations/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_05_01_preview/operations/__init__.py index e010c281d4fc..795e91ef6843 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_05_01_preview/operations/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_05_01_preview/operations/__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 ._scheduled_query_rules_operations import ScheduledQueryRulesOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._scheduled_query_rules_operations import ScheduledQueryRulesOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ "ScheduledQueryRulesOperations", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_05_01_preview/operations/_scheduled_query_rules_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_05_01_preview/operations/_scheduled_query_rules_operations.py index d228d7b32971..36153aac8779 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_05_01_preview/operations/_scheduled_query_rules_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_05_01_preview/operations/_scheduled_query_rules_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload import urllib.parse @@ -19,16 +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, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -51,7 +54,7 @@ def build_list_by_subscription_request(subscription_id: str, **kwargs: Any) -> H "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -81,7 +84,7 @@ def build_list_by_resource_group_request(resource_group_name: str, subscription_ ), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -109,10 +112,10 @@ def build_get_request(resource_group_name: str, rule_name: str, subscription_id: "resourceGroupName": _SERIALIZER.url( "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 ), - "ruleName": _SERIALIZER.url("rule_name", rule_name, "str"), + "ruleName": _SERIALIZER.url("rule_name", rule_name, "str", pattern=r"^[^#<>%&:\?/{}*]{1,260}$"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -143,10 +146,10 @@ def build_create_or_update_request( "resourceGroupName": _SERIALIZER.url( "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 ), - "ruleName": _SERIALIZER.url("rule_name", rule_name, "str"), + "ruleName": _SERIALIZER.url("rule_name", rule_name, "str", pattern=r"^[^#<>%&:\?/{}*]{1,260}$"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -177,10 +180,10 @@ def build_update_request(resource_group_name: str, rule_name: str, subscription_ "resourceGroupName": _SERIALIZER.url( "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 ), - "ruleName": _SERIALIZER.url("rule_name", rule_name, "str"), + "ruleName": _SERIALIZER.url("rule_name", rule_name, "str", pattern=r"^[^#<>%&:\?/{}*]{1,260}$"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -210,10 +213,10 @@ def build_delete_request(resource_group_name: str, rule_name: str, subscription_ "resourceGroupName": _SERIALIZER.url( "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 ), - "ruleName": _SERIALIZER.url("rule_name", rule_name, "str"), + "ruleName": _SERIALIZER.url("rule_name", rule_name, "str", pattern=r"^[^#<>%&:\?/{}*]{1,260}$"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -242,12 +245,12 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list_by_subscription(self, **kwargs: Any) -> Iterable["_models.ScheduledQueryRuleResource"]: """Retrieve a scheduled query rule definitions in a subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ScheduledQueryRuleResource or the result of cls(response) :rtype: @@ -257,10 +260,12 @@ def list_by_subscription(self, **kwargs: Any) -> Iterable["_models.ScheduledQuer _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2020-05-01-preview") + ) cls: ClsType[_models.ScheduledQueryRuleResourceCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -271,15 +276,13 @@ def list_by_subscription(self, **kwargs: Any) -> Iterable["_models.ScheduledQuer def prepare_request(next_link=None): if not next_link: - request = build_list_by_subscription_request( + _request = build_list_by_subscription_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_subscription.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -290,14 +293,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("ScheduledQueryRuleResourceCollection", pipeline_response) @@ -307,11 +309,11 @@ def extract_data(pipeline_response): return None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -324,10 +326,6 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_by_subscription.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/scheduledQueryRules" - } - @distributed_trace def list_by_resource_group( self, resource_group_name: str, **kwargs: Any @@ -337,7 +335,6 @@ def list_by_resource_group( :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ScheduledQueryRuleResource or the result of cls(response) :rtype: @@ -347,10 +344,12 @@ def list_by_resource_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2020-05-01-preview") + ) cls: ClsType[_models.ScheduledQueryRuleResourceCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -361,16 +360,14 @@ 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_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -381,14 +378,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("ScheduledQueryRuleResourceCollection", pipeline_response) @@ -398,11 +394,11 @@ def extract_data(pipeline_response): return None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -415,10 +411,6 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/scheduledQueryRules" - } - @distributed_trace def get(self, resource_group_name: str, rule_name: str, **kwargs: Any) -> _models.ScheduledQueryRuleResource: """Retrieve an scheduled query rule definition. @@ -428,12 +420,11 @@ def get(self, resource_group_name: str, rule_name: str, **kwargs: Any) -> _model :type resource_group_name: str :param rule_name: The name of the rule. Required. :type rule_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ScheduledQueryRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2020_05_01_preview.models.ScheduledQueryRuleResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -444,24 +435,24 @@ def get(self, resource_group_name: str, rule_name: str, **kwargs: Any) -> _model _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2020-05-01-preview") + ) cls: ClsType[_models.ScheduledQueryRuleResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, rule_name=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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -471,16 +462,12 @@ def get(self, resource_group_name: str, rule_name: str, **kwargs: Any) -> _model error = self._deserialize.failsafe_deserialize(_models.ErrorContract, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ScheduledQueryRuleResource", pipeline_response) + deserialized = self._deserialize("ScheduledQueryRuleResource", 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.Insights/scheduledQueryRules/{ruleName}" - } + return deserialized # type: ignore @overload def create_or_update( @@ -504,7 +491,6 @@ def create_or_update( :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: ScheduledQueryRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2020_05_01_preview.models.ScheduledQueryRuleResource :raises ~azure.core.exceptions.HttpResponseError: @@ -515,7 +501,7 @@ def create_or_update( self, resource_group_name: str, rule_name: str, - parameters: IO, + parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -528,11 +514,10 @@ def create_or_update( :param rule_name: The name of the rule. Required. :type rule_name: str :param parameters: The parameters of the rule to create or update. Required. - :type parameters: IO + :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: ScheduledQueryRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2020_05_01_preview.models.ScheduledQueryRuleResource :raises ~azure.core.exceptions.HttpResponseError: @@ -543,7 +528,7 @@ def create_or_update( self, resource_group_name: str, rule_name: str, - parameters: Union[_models.ScheduledQueryRuleResource, IO], + parameters: Union[_models.ScheduledQueryRuleResource, IO[bytes]], **kwargs: Any ) -> _models.ScheduledQueryRuleResource: """Creates or updates a scheduled query rule. @@ -554,18 +539,14 @@ def create_or_update( :param rule_name: The name of the rule. Required. :type rule_name: str :param parameters: The parameters of the rule to create or update. Is either a - ScheduledQueryRuleResource type or a IO type. Required. + ScheduledQueryRuleResource type or a IO[bytes] type. Required. :type parameters: ~azure.mgmt.monitor.v2020_05_01_preview.models.ScheduledQueryRuleResource 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 + IO[bytes] :return: ScheduledQueryRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2020_05_01_preview.models.ScheduledQueryRuleResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -576,19 +557,21 @@ def create_or_update( _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", "2020-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2020-05-01-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ScheduledQueryRuleResource] = 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, "ScheduledQueryRuleResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, rule_name=rule_name, subscription_id=self._config.subscription_id, @@ -596,16 +579,14 @@ def create_or_update( 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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -615,21 +596,13 @@ def create_or_update( error = self._deserialize.failsafe_deserialize(_models.ErrorContract, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if response.status_code == 200: - deserialized = self._deserialize("ScheduledQueryRuleResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("ScheduledQueryRuleResource", pipeline_response) + deserialized = self._deserialize("ScheduledQueryRuleResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/scheduledQueryRules/{ruleName}" - } - @overload def update( self, @@ -653,7 +626,6 @@ def update( :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: ScheduledQueryRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2020_05_01_preview.models.ScheduledQueryRuleResource :raises ~azure.core.exceptions.HttpResponseError: @@ -664,7 +636,7 @@ def update( self, resource_group_name: str, rule_name: str, - parameters: IO, + parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -677,11 +649,10 @@ def update( :param rule_name: The name of the rule. Required. :type rule_name: str :param parameters: The parameters of the rule to update. Required. - :type parameters: IO + :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: ScheduledQueryRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2020_05_01_preview.models.ScheduledQueryRuleResource :raises ~azure.core.exceptions.HttpResponseError: @@ -692,7 +663,7 @@ def update( self, resource_group_name: str, rule_name: str, - parameters: Union[_models.ScheduledQueryRuleResourcePatch, IO], + parameters: Union[_models.ScheduledQueryRuleResourcePatch, IO[bytes]], **kwargs: Any ) -> _models.ScheduledQueryRuleResource: """Update a scheduled query rule. @@ -703,18 +674,14 @@ def update( :param rule_name: The name of the rule. Required. :type rule_name: str :param parameters: The parameters of the rule to update. Is either a - ScheduledQueryRuleResourcePatch type or a IO type. Required. + ScheduledQueryRuleResourcePatch type or a IO[bytes] type. Required. :type parameters: - ~azure.mgmt.monitor.v2020_05_01_preview.models.ScheduledQueryRuleResourcePatch 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 + ~azure.mgmt.monitor.v2020_05_01_preview.models.ScheduledQueryRuleResourcePatch or IO[bytes] :return: ScheduledQueryRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2020_05_01_preview.models.ScheduledQueryRuleResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -725,19 +692,21 @@ def update( _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", "2020-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2020-05-01-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ScheduledQueryRuleResource] = 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, "ScheduledQueryRuleResourcePatch") - request = build_update_request( + _request = build_update_request( resource_group_name=resource_group_name, rule_name=rule_name, subscription_id=self._config.subscription_id, @@ -745,16 +714,14 @@ def update( 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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -764,16 +731,12 @@ def update( error = self._deserialize.failsafe_deserialize(_models.ErrorContract, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ScheduledQueryRuleResource", pipeline_response) + deserialized = self._deserialize("ScheduledQueryRuleResource", 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.Insights/scheduledQueryRules/{ruleName}" - } + return deserialized # type: ignore @distributed_trace def delete( # pylint: disable=inconsistent-return-statements @@ -786,12 +749,11 @@ def delete( # pylint: disable=inconsistent-return-statements :type resource_group_name: str :param rule_name: The name of the rule. Required. :type 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, @@ -802,24 +764,24 @@ def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2020-05-01-preview") + ) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, rule_name=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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -830,8 +792,4 @@ def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/scheduledQueryRules/{ruleName}" - } + return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_10_01/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_10_01/__init__.py index 2c7733bfd566..42cc62301757 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_10_01/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_10_01/__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 ._monitor_management_client import MonitorManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._monitor_management_client import MonitorManagementClient # type: ignore from ._version import VERSION __version__ = VERSION try: from ._patch import __all__ as _patch_all - from ._patch import * # 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__ = [ "MonitorManagementClient", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_10_01/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_10_01/_configuration.py index fddd1844a56b..9e61ce4bc15e 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_10_01/_configuration.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_10_01/_configuration.py @@ -8,18 +8,16 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy from ._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MonitorManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class MonitorManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for MonitorManagementClient. Note that all parameters used to create this instance are saved as instance @@ -35,7 +33,6 @@ class MonitorManagementClientConfiguration(Configuration): # pylint: disable=to """ def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: - super(MonitorManagementClientConfiguration, self).__init__(**kwargs) api_version: str = kwargs.pop("api_version", "2020-10-01") if credential is None: @@ -48,6 +45,7 @@ def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-monitor/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -56,9 +54,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.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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_10_01/_metadata.json b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_10_01/_metadata.json index 8310acd4e00c..027486b16a61 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_10_01/_metadata.json +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_10_01/_metadata.json @@ -8,10 +8,10 @@ "host_value": "\"https://management.azure.com\"", "parameterized_host_template": null, "azure_arm": true, - "has_lro_operations": false, + "has_public_lro_operations": false, "client_side_validation": false, - "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"sdkcore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMAutoResourceProviderRegistrationPolicy\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}, \"stdlib\": {\"typing_extensions\": [\"Self\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"sdkcore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"AsyncARMAutoResourceProviderRegistrationPolicy\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}, \"stdlib\": {\"typing_extensions\": [\"Self\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "global_parameters": { "sync": { @@ -101,8 +101,8 @@ "credential_scopes": ["https://management.azure.com/.default"], "credential_call_sync": "ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", "credential_call_async": "AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", - "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "sync_imports": "{\"regular\": {\"sdkcore\": {\"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"regular\": {\"sdkcore\": {\"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "operation_groups": { "activity_log_alerts": "ActivityLogAlertsOperations" diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_10_01/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_10_01/_monitor_management_client.py index ee3137b48e31..e06e28c5d56c 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_10_01/_monitor_management_client.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_10_01/_monitor_management_client.py @@ -8,9 +8,12 @@ from copy import deepcopy from typing import Any, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient +from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy from . import models as _models from .._serialization import Deserializer, Serializer @@ -18,11 +21,10 @@ from .operations import ActivityLogAlertsOperations if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MonitorManagementClient: # pylint: disable=client-accepts-api-version-keyword +class MonitorManagementClient: """Monitor Management Client. :ivar activity_log_alerts: ActivityLogAlertsOperations operations @@ -49,17 +51,35 @@ def __init__( self._config = MonitorManagementClientConfiguration( credential=credential, subscription_id=subscription_id, **kwargs ) - self._client: ARMPipelineClient = ARMPipelineClient(base_url=base_url, config=self._config, **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), + 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=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.activity_log_alerts = ActivityLogAlertsOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2020-10-01" ) - 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 @@ -79,12 +99,12 @@ 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) -> None: self._client.close() - def __enter__(self) -> "MonitorManagementClient": + def __enter__(self) -> Self: self._client.__enter__() return self diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_10_01/_vendor.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_10_01/_vendor.py deleted file mode 100644 index bd0df84f5319..000000000000 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_10_01/_vendor.py +++ /dev/null @@ -1,30 +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 typing import List, cast - -from azure.core.pipeline.transport import HttpRequest - - -def _convert_request(request, files=None): - data = request.content if not files else None - request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) - if files: - request.set_formdata_body(files) - return request - - -def _format_url_section(template, **kwargs): - components = template.split("/") - while components: - try: - return template.format(**kwargs) - except KeyError as key: - # Need the cast, as for some reasons "split" is typed as list[str | Any] - formatted_components = cast(List[str], template.split("/")) - components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] - template = "/".join(components) diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_10_01/_version.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_10_01/_version.py index 394ee7c0c03c..e5754a47ce68 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_10_01/_version.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_10_01/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "6.0.2" +VERSION = "1.0.0b1" diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_10_01/aio/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_10_01/aio/__init__.py index 2c151bb41c19..3df30ff42149 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_10_01/aio/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_10_01/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 ._monitor_management_client import MonitorManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._monitor_management_client import MonitorManagementClient # type: ignore try: from ._patch import __all__ as _patch_all - from ._patch import * # 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__ = [ "MonitorManagementClient", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_10_01/aio/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_10_01/aio/_configuration.py index 42b631fd8594..d86df3652df7 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_10_01/aio/_configuration.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_10_01/aio/_configuration.py @@ -8,18 +8,16 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy from .._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MonitorManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class MonitorManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for MonitorManagementClient. Note that all parameters used to create this instance are saved as instance @@ -35,7 +33,6 @@ class MonitorManagementClientConfiguration(Configuration): # pylint: disable=to """ def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: - super(MonitorManagementClientConfiguration, self).__init__(**kwargs) api_version: str = kwargs.pop("api_version", "2020-10-01") if credential is None: @@ -48,6 +45,7 @@ def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **k self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-monitor/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -56,9 +54,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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_10_01/aio/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_10_01/aio/_monitor_management_client.py index a39bf9bd18be..4dd3f3981df1 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_10_01/aio/_monitor_management_client.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_10_01/aio/_monitor_management_client.py @@ -8,9 +8,12 @@ from copy import deepcopy from typing import Any, Awaitable, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient +from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy from .. import models as _models from ..._serialization import Deserializer, Serializer @@ -18,11 +21,10 @@ from .operations import ActivityLogAlertsOperations if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MonitorManagementClient: # pylint: disable=client-accepts-api-version-keyword +class MonitorManagementClient: """Monitor Management Client. :ivar activity_log_alerts: ActivityLogAlertsOperations operations @@ -49,17 +51,37 @@ def __init__( self._config = MonitorManagementClientConfiguration( credential=credential, subscription_id=subscription_id, **kwargs ) - self._client: AsyncARMPipelineClient = AsyncARMPipelineClient(base_url=base_url, config=self._config, **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=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.activity_log_alerts = ActivityLogAlertsOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2020-10-01" ) - 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 @@ -79,12 +101,12 @@ 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) -> "MonitorManagementClient": + async def __aenter__(self) -> Self: await self._client.__aenter__() return self diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_10_01/aio/operations/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_10_01/aio/operations/__init__.py index b024a2af0682..41e2b371bc7a 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_10_01/aio/operations/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_10_01/aio/operations/__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 ._activity_log_alerts_operations import ActivityLogAlertsOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._activity_log_alerts_operations import ActivityLogAlertsOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ "ActivityLogAlertsOperations", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_10_01/aio/operations/_activity_log_alerts_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_10_01/aio/operations/_activity_log_alerts_operations.py index 5fae3dda7418..843c8ed410c1 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_10_01/aio/operations/_activity_log_alerts_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_10_01/aio/operations/_activity_log_alerts_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload import urllib.parse @@ -19,15 +20,13 @@ 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 ...operations._activity_log_alerts_operations import ( build_create_or_update_request, build_delete_request, @@ -37,6 +36,10 @@ build_update_request, ) +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -59,6 +62,7 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @overload async def create_or_update( @@ -83,7 +87,6 @@ async def create_or_update( :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: ActivityLogAlertResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2020_10_01.models.ActivityLogAlertResource :raises ~azure.core.exceptions.HttpResponseError: @@ -94,7 +97,7 @@ async def create_or_update( self, resource_group_name: str, activity_log_alert_name: str, - activity_log_alert_rule: IO, + activity_log_alert_rule: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -108,11 +111,10 @@ async def create_or_update( :type activity_log_alert_name: str :param activity_log_alert_rule: The Activity Log Alert rule to create or use for the update. Required. - :type activity_log_alert_rule: IO + :type activity_log_alert_rule: 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: ActivityLogAlertResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2020_10_01.models.ActivityLogAlertResource :raises ~azure.core.exceptions.HttpResponseError: @@ -123,7 +125,7 @@ async def create_or_update( self, resource_group_name: str, activity_log_alert_name: str, - activity_log_alert_rule: Union[_models.ActivityLogAlertResource, IO], + activity_log_alert_rule: Union[_models.ActivityLogAlertResource, IO[bytes]], **kwargs: Any ) -> _models.ActivityLogAlertResource: """Create a new Activity Log Alert rule or update an existing one. @@ -134,18 +136,14 @@ async def create_or_update( :param activity_log_alert_name: The name of the Activity Log Alert rule. Required. :type activity_log_alert_name: str :param activity_log_alert_rule: The Activity Log Alert rule to create or use for the update. Is - either a ActivityLogAlertResource type or a IO type. Required. + either a ActivityLogAlertResource type or a IO[bytes] type. Required. :type activity_log_alert_rule: ~azure.mgmt.monitor.v2020_10_01.models.ActivityLogAlertResource - 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 + or IO[bytes] :return: ActivityLogAlertResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2020_10_01.models.ActivityLogAlertResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -156,19 +154,19 @@ async def create_or_update( _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", "2020-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2020-10-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ActivityLogAlertResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(activity_log_alert_rule, (IO, bytes)): + if isinstance(activity_log_alert_rule, (IOBase, bytes)): _content = activity_log_alert_rule else: _json = self._serialize.body(activity_log_alert_rule, "ActivityLogAlertResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, activity_log_alert_name=activity_log_alert_name, subscription_id=self._config.subscription_id, @@ -176,16 +174,14 @@ async def create_or_update( 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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -195,21 +191,13 @@ async def create_or_update( 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("ActivityLogAlertResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("ActivityLogAlertResource", pipeline_response) + deserialized = self._deserialize("ActivityLogAlertResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/activityLogAlerts/{activityLogAlertName}" - } - @distributed_trace_async async def get( self, resource_group_name: str, activity_log_alert_name: str, **kwargs: Any @@ -221,12 +209,11 @@ async def get( :type resource_group_name: str :param activity_log_alert_name: The name of the Activity Log Alert rule. Required. :type activity_log_alert_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ActivityLogAlertResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2020_10_01.models.ActivityLogAlertResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -237,24 +224,22 @@ async def get( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2020-10-01")) cls: ClsType[_models.ActivityLogAlertResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, activity_log_alert_name=activity_log_alert_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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -264,21 +249,15 @@ async def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ActivityLogAlertResource", pipeline_response) + deserialized = self._deserialize("ActivityLogAlertResource", 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.Insights/activityLogAlerts/{activityLogAlertName}" - } + return deserialized # type: ignore @distributed_trace_async - async def delete( # pylint: disable=inconsistent-return-statements - self, resource_group_name: str, activity_log_alert_name: str, **kwargs: Any - ) -> None: + async def delete(self, resource_group_name: str, activity_log_alert_name: str, **kwargs: Any) -> None: """Delete an Activity Log Alert rule. :param resource_group_name: The name of the resource group. The name is case insensitive. @@ -286,12 +265,11 @@ async def delete( # pylint: disable=inconsistent-return-statements :type resource_group_name: str :param activity_log_alert_name: The name of the Activity Log Alert rule. Required. :type activity_log_alert_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, @@ -302,24 +280,22 @@ async def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2020-10-01")) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, activity_log_alert_name=activity_log_alert_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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -330,11 +306,7 @@ async def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/activityLogAlerts/{activityLogAlertName}" - } + return cls(pipeline_response, None, {}) # type: ignore @overload async def update( @@ -361,7 +333,6 @@ async def update( :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: ActivityLogAlertResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2020_10_01.models.ActivityLogAlertResource :raises ~azure.core.exceptions.HttpResponseError: @@ -372,7 +343,7 @@ async def update( self, resource_group_name: str, activity_log_alert_name: str, - activity_log_alert_rule_patch: IO, + activity_log_alert_rule_patch: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -387,11 +358,10 @@ async def update( :param activity_log_alert_name: The name of the Activity Log Alert rule. Required. :type activity_log_alert_name: str :param activity_log_alert_rule_patch: Parameters supplied to the operation. Required. - :type activity_log_alert_rule_patch: IO + :type activity_log_alert_rule_patch: 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: ActivityLogAlertResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2020_10_01.models.ActivityLogAlertResource :raises ~azure.core.exceptions.HttpResponseError: @@ -402,7 +372,7 @@ async def update( self, resource_group_name: str, activity_log_alert_name: str, - activity_log_alert_rule_patch: Union[_models.AlertRulePatchObject, IO], + activity_log_alert_rule_patch: Union[_models.AlertRulePatchObject, IO[bytes]], **kwargs: Any ) -> _models.ActivityLogAlertResource: """Updates 'tags' and 'enabled' fields in an existing Alert rule. This method is used to update @@ -415,18 +385,14 @@ async def update( :param activity_log_alert_name: The name of the Activity Log Alert rule. Required. :type activity_log_alert_name: str :param activity_log_alert_rule_patch: Parameters supplied to the operation. Is either a - AlertRulePatchObject type or a IO type. Required. + AlertRulePatchObject type or a IO[bytes] type. Required. :type activity_log_alert_rule_patch: - ~azure.mgmt.monitor.v2020_10_01.models.AlertRulePatchObject 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 + ~azure.mgmt.monitor.v2020_10_01.models.AlertRulePatchObject or IO[bytes] :return: ActivityLogAlertResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2020_10_01.models.ActivityLogAlertResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -437,19 +403,19 @@ async def update( _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", "2020-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2020-10-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ActivityLogAlertResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(activity_log_alert_rule_patch, (IO, bytes)): + if isinstance(activity_log_alert_rule_patch, (IOBase, bytes)): _content = activity_log_alert_rule_patch else: _json = self._serialize.body(activity_log_alert_rule_patch, "AlertRulePatchObject") - request = build_update_request( + _request = build_update_request( resource_group_name=resource_group_name, activity_log_alert_name=activity_log_alert_name, subscription_id=self._config.subscription_id, @@ -457,16 +423,14 @@ async def update( 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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -476,22 +440,17 @@ async def update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ActivityLogAlertResource", pipeline_response) + deserialized = self._deserialize("ActivityLogAlertResource", 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.Insights/activityLogAlerts/{activityLogAlertName}" - } + return deserialized # type: ignore @distributed_trace def list_by_subscription_id(self, **kwargs: Any) -> AsyncIterable["_models.ActivityLogAlertResource"]: """Get a list of all Activity Log Alert rules in a subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ActivityLogAlertResource or the result of cls(response) :rtype: @@ -501,10 +460,10 @@ def list_by_subscription_id(self, **kwargs: Any) -> AsyncIterable["_models.Activ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2020-10-01")) cls: ClsType[_models.AlertRuleList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -515,15 +474,13 @@ def list_by_subscription_id(self, **kwargs: Any) -> AsyncIterable["_models.Activ def prepare_request(next_link=None): if not next_link: - request = build_list_by_subscription_id_request( + _request = build_list_by_subscription_id_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_subscription_id.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -534,14 +491,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("AlertRuleList", pipeline_response) @@ -551,11 +507,11 @@ async def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -568,10 +524,6 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_by_subscription_id.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/activityLogAlerts" - } - @distributed_trace def list_by_resource_group( self, resource_group_name: str, **kwargs: Any @@ -581,7 +533,6 @@ def list_by_resource_group( :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ActivityLogAlertResource or the result of cls(response) :rtype: @@ -591,10 +542,10 @@ def list_by_resource_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2020-10-01")) cls: ClsType[_models.AlertRuleList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -605,16 +556,14 @@ 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_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -625,14 +574,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("AlertRuleList", pipeline_response) @@ -642,11 +590,11 @@ async def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -658,7 +606,3 @@ async def get_next(next_link=None): return pipeline_response return AsyncItemPaged(get_next, extract_data) - - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/activityLogAlerts" - } diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_10_01/models/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_10_01/models/__init__.py index 68b921674c5d..2e6d1a08f347 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_10_01/models/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_10_01/models/__init__.py @@ -5,19 +5,28 @@ # 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 ActionGroup -from ._models_py3 import ActionList -from ._models_py3 import ActivityLogAlertResource -from ._models_py3 import AlertRuleAllOfCondition -from ._models_py3 import AlertRuleAnyOfOrLeafCondition -from ._models_py3 import AlertRuleLeafCondition -from ._models_py3 import AlertRuleList -from ._models_py3 import AlertRulePatchObject -from ._models_py3 import AzureResource -from ._models_py3 import ErrorResponse +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models_py3 import ( # type: ignore + ActionGroup, + ActionList, + ActivityLogAlertResource, + AlertRuleAllOfCondition, + AlertRuleAnyOfOrLeafCondition, + AlertRuleLeafCondition, + AlertRuleList, + AlertRulePatchObject, + AzureResource, + ErrorResponse, +) from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ @@ -32,5 +41,5 @@ "AzureResource", "ErrorResponse", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_10_01/models/_models_py3.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_10_01/models/_models_py3.py index c5d3588a63b5..ca2101ea8f46 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_10_01/models/_models_py3.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_10_01/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. @@ -12,14 +11,13 @@ from ... import _serialization if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from .. import models as _models class ActionGroup(_serialization.Model): """A pointer to an Azure Action Group. - 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 action_group_id: The resource ID of the Action Group. This cannot be null or empty. Required. @@ -85,8 +83,8 @@ class AzureResource(_serialization.Model): :vartype name: str :ivar type: The type of the resource. :vartype type: str - :ivar location: The location of the resource. Since Azure Activity Log Alerts is a global - service, the location of the rules should always be 'global'. + :ivar location: The location of the resource. Azure Activity Log Alert rules are supported on + Global, West Europe and North Europe regions. :vartype location: str :ivar tags: The tags of the resource. :vartype tags: dict[str, str] @@ -108,8 +106,8 @@ class AzureResource(_serialization.Model): def __init__(self, *, location: str = "global", tags: Optional[Dict[str, str]] = None, **kwargs: Any) -> None: """ - :keyword location: The location of the resource. Since Azure Activity Log Alerts is a global - service, the location of the rules should always be 'global'. + :keyword location: The location of the resource. Azure Activity Log Alert rules are supported + on Global, West Europe and North Europe regions. :paramtype location: str :keyword tags: The tags of the resource. :paramtype tags: dict[str, str] @@ -133,8 +131,8 @@ class ActivityLogAlertResource(AzureResource): :vartype name: str :ivar type: The type of the resource. :vartype type: str - :ivar location: The location of the resource. Since Azure Activity Log Alerts is a global - service, the location of the rules should always be 'global'. + :ivar location: The location of the resource. Azure Activity Log Alert rules are supported on + Global, West Europe and North Europe regions. :vartype location: str :ivar tags: The tags of the resource. :vartype tags: dict[str, str] @@ -185,8 +183,8 @@ def __init__( **kwargs: Any ) -> None: """ - :keyword location: The location of the resource. Since Azure Activity Log Alerts is a global - service, the location of the rules should always be 'global'. + :keyword location: The location of the resource. Azure Activity Log Alert rules are supported + on Global, West Europe and North Europe regions. :paramtype location: str :keyword tags: The tags of the resource. :paramtype tags: dict[str, str] @@ -215,7 +213,7 @@ def __init__( class AlertRuleAllOfCondition(_serialization.Model): """An Activity Log Alert rule condition that is met when all its member conditions are met. - 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 all_of: The list of Activity Log Alert rule conditions. Required. :vartype all_of: list[~azure.mgmt.monitor.v2020_10_01.models.AlertRuleAnyOfOrLeafCondition] @@ -292,8 +290,8 @@ def __init__( class AlertRuleAnyOfOrLeafCondition(AlertRuleLeafCondition): """An Activity Log Alert rule condition that is met when all its member conditions are met. Each condition can be of one of the following types: - **Important**\ : Each type has its unique subset of properties. Properties from different types - CANNOT exist in one condition. + **Important**\\ : Each type has its unique subset of properties. Properties from different + types CANNOT exist in one condition. * **Leaf Condition -** must contain 'field' and either 'equals' or 'containsAny'. diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_10_01/operations/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_10_01/operations/__init__.py index b024a2af0682..41e2b371bc7a 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_10_01/operations/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_10_01/operations/__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 ._activity_log_alerts_operations import ActivityLogAlertsOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._activity_log_alerts_operations import ActivityLogAlertsOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ "ActivityLogAlertsOperations", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_10_01/operations/_activity_log_alerts_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_10_01/operations/_activity_log_alerts_operations.py index 51efebd9b92d..3462713411d7 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_10_01/operations/_activity_log_alerts_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2020_10_01/operations/_activity_log_alerts_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload import urllib.parse @@ -19,16 +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, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -59,7 +62,7 @@ def build_create_or_update_request( "activityLogAlertName": _SERIALIZER.url("activity_log_alert_name", activity_log_alert_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -94,7 +97,7 @@ def build_get_request( "activityLogAlertName": _SERIALIZER.url("activity_log_alert_name", activity_log_alert_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -127,7 +130,7 @@ def build_delete_request( "activityLogAlertName": _SERIALIZER.url("activity_log_alert_name", activity_log_alert_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -161,7 +164,7 @@ def build_update_request( "activityLogAlertName": _SERIALIZER.url("activity_log_alert_name", activity_log_alert_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -187,7 +190,7 @@ def build_list_by_subscription_id_request(subscription_id: str, **kwargs: Any) - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -217,7 +220,7 @@ def build_list_by_resource_group_request(resource_group_name: str, subscription_ ), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -246,6 +249,7 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @overload def create_or_update( @@ -270,7 +274,6 @@ def create_or_update( :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: ActivityLogAlertResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2020_10_01.models.ActivityLogAlertResource :raises ~azure.core.exceptions.HttpResponseError: @@ -281,7 +284,7 @@ def create_or_update( self, resource_group_name: str, activity_log_alert_name: str, - activity_log_alert_rule: IO, + activity_log_alert_rule: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -295,11 +298,10 @@ def create_or_update( :type activity_log_alert_name: str :param activity_log_alert_rule: The Activity Log Alert rule to create or use for the update. Required. - :type activity_log_alert_rule: IO + :type activity_log_alert_rule: 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: ActivityLogAlertResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2020_10_01.models.ActivityLogAlertResource :raises ~azure.core.exceptions.HttpResponseError: @@ -310,7 +312,7 @@ def create_or_update( self, resource_group_name: str, activity_log_alert_name: str, - activity_log_alert_rule: Union[_models.ActivityLogAlertResource, IO], + activity_log_alert_rule: Union[_models.ActivityLogAlertResource, IO[bytes]], **kwargs: Any ) -> _models.ActivityLogAlertResource: """Create a new Activity Log Alert rule or update an existing one. @@ -321,18 +323,14 @@ def create_or_update( :param activity_log_alert_name: The name of the Activity Log Alert rule. Required. :type activity_log_alert_name: str :param activity_log_alert_rule: The Activity Log Alert rule to create or use for the update. Is - either a ActivityLogAlertResource type or a IO type. Required. + either a ActivityLogAlertResource type or a IO[bytes] type. Required. :type activity_log_alert_rule: ~azure.mgmt.monitor.v2020_10_01.models.ActivityLogAlertResource - 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 + or IO[bytes] :return: ActivityLogAlertResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2020_10_01.models.ActivityLogAlertResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -343,19 +341,19 @@ def create_or_update( _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", "2020-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2020-10-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ActivityLogAlertResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(activity_log_alert_rule, (IO, bytes)): + if isinstance(activity_log_alert_rule, (IOBase, bytes)): _content = activity_log_alert_rule else: _json = self._serialize.body(activity_log_alert_rule, "ActivityLogAlertResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, activity_log_alert_name=activity_log_alert_name, subscription_id=self._config.subscription_id, @@ -363,16 +361,14 @@ def create_or_update( 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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -382,21 +378,13 @@ def create_or_update( 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("ActivityLogAlertResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("ActivityLogAlertResource", pipeline_response) + deserialized = self._deserialize("ActivityLogAlertResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/activityLogAlerts/{activityLogAlertName}" - } - @distributed_trace def get( self, resource_group_name: str, activity_log_alert_name: str, **kwargs: Any @@ -408,12 +396,11 @@ def get( :type resource_group_name: str :param activity_log_alert_name: The name of the Activity Log Alert rule. Required. :type activity_log_alert_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ActivityLogAlertResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2020_10_01.models.ActivityLogAlertResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -424,24 +411,22 @@ def get( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2020-10-01")) cls: ClsType[_models.ActivityLogAlertResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, activity_log_alert_name=activity_log_alert_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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -451,16 +436,12 @@ def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ActivityLogAlertResource", pipeline_response) + deserialized = self._deserialize("ActivityLogAlertResource", 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.Insights/activityLogAlerts/{activityLogAlertName}" - } + return deserialized # type: ignore @distributed_trace def delete( # pylint: disable=inconsistent-return-statements @@ -473,12 +454,11 @@ def delete( # pylint: disable=inconsistent-return-statements :type resource_group_name: str :param activity_log_alert_name: The name of the Activity Log Alert rule. Required. :type activity_log_alert_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, @@ -489,24 +469,22 @@ def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2020-10-01")) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, activity_log_alert_name=activity_log_alert_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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -517,11 +495,7 @@ def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/activityLogAlerts/{activityLogAlertName}" - } + return cls(pipeline_response, None, {}) # type: ignore @overload def update( @@ -548,7 +522,6 @@ def update( :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: ActivityLogAlertResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2020_10_01.models.ActivityLogAlertResource :raises ~azure.core.exceptions.HttpResponseError: @@ -559,7 +532,7 @@ def update( self, resource_group_name: str, activity_log_alert_name: str, - activity_log_alert_rule_patch: IO, + activity_log_alert_rule_patch: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -574,11 +547,10 @@ def update( :param activity_log_alert_name: The name of the Activity Log Alert rule. Required. :type activity_log_alert_name: str :param activity_log_alert_rule_patch: Parameters supplied to the operation. Required. - :type activity_log_alert_rule_patch: IO + :type activity_log_alert_rule_patch: 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: ActivityLogAlertResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2020_10_01.models.ActivityLogAlertResource :raises ~azure.core.exceptions.HttpResponseError: @@ -589,7 +561,7 @@ def update( self, resource_group_name: str, activity_log_alert_name: str, - activity_log_alert_rule_patch: Union[_models.AlertRulePatchObject, IO], + activity_log_alert_rule_patch: Union[_models.AlertRulePatchObject, IO[bytes]], **kwargs: Any ) -> _models.ActivityLogAlertResource: """Updates 'tags' and 'enabled' fields in an existing Alert rule. This method is used to update @@ -602,18 +574,14 @@ def update( :param activity_log_alert_name: The name of the Activity Log Alert rule. Required. :type activity_log_alert_name: str :param activity_log_alert_rule_patch: Parameters supplied to the operation. Is either a - AlertRulePatchObject type or a IO type. Required. + AlertRulePatchObject type or a IO[bytes] type. Required. :type activity_log_alert_rule_patch: - ~azure.mgmt.monitor.v2020_10_01.models.AlertRulePatchObject 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 + ~azure.mgmt.monitor.v2020_10_01.models.AlertRulePatchObject or IO[bytes] :return: ActivityLogAlertResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2020_10_01.models.ActivityLogAlertResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -624,19 +592,19 @@ def update( _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", "2020-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2020-10-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ActivityLogAlertResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(activity_log_alert_rule_patch, (IO, bytes)): + if isinstance(activity_log_alert_rule_patch, (IOBase, bytes)): _content = activity_log_alert_rule_patch else: _json = self._serialize.body(activity_log_alert_rule_patch, "AlertRulePatchObject") - request = build_update_request( + _request = build_update_request( resource_group_name=resource_group_name, activity_log_alert_name=activity_log_alert_name, subscription_id=self._config.subscription_id, @@ -644,16 +612,14 @@ def update( 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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -663,22 +629,17 @@ def update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ActivityLogAlertResource", pipeline_response) + deserialized = self._deserialize("ActivityLogAlertResource", 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.Insights/activityLogAlerts/{activityLogAlertName}" - } + return deserialized # type: ignore @distributed_trace def list_by_subscription_id(self, **kwargs: Any) -> Iterable["_models.ActivityLogAlertResource"]: """Get a list of all Activity Log Alert rules in a subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ActivityLogAlertResource or the result of cls(response) :rtype: @@ -688,10 +649,10 @@ def list_by_subscription_id(self, **kwargs: Any) -> Iterable["_models.ActivityLo _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2020-10-01")) cls: ClsType[_models.AlertRuleList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -702,15 +663,13 @@ def list_by_subscription_id(self, **kwargs: Any) -> Iterable["_models.ActivityLo def prepare_request(next_link=None): if not next_link: - request = build_list_by_subscription_id_request( + _request = build_list_by_subscription_id_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_subscription_id.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -721,14 +680,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("AlertRuleList", pipeline_response) @@ -738,11 +696,11 @@ def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -755,10 +713,6 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_by_subscription_id.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/activityLogAlerts" - } - @distributed_trace def list_by_resource_group( self, resource_group_name: str, **kwargs: Any @@ -768,7 +722,6 @@ def list_by_resource_group( :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ActivityLogAlertResource or the result of cls(response) :rtype: @@ -778,10 +731,10 @@ def list_by_resource_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2020-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2020-10-01")) cls: ClsType[_models.AlertRuleList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -792,16 +745,14 @@ 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_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -812,14 +763,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("AlertRuleList", pipeline_response) @@ -829,11 +779,11 @@ def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -845,7 +795,3 @@ def get_next(next_link=None): return pipeline_response return ItemPaged(get_next, extract_data) - - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/activityLogAlerts" - } diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/__init__.py index 2c7733bfd566..42cc62301757 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/__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 ._monitor_management_client import MonitorManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._monitor_management_client import MonitorManagementClient # type: ignore from ._version import VERSION __version__ = VERSION try: from ._patch import __all__ as _patch_all - from ._patch import * # 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__ = [ "MonitorManagementClient", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/_configuration.py index 7299d9a2317f..b5a423c7b985 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/_configuration.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/_configuration.py @@ -8,18 +8,16 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy from ._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MonitorManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class MonitorManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for MonitorManagementClient. Note that all parameters used to create this instance are saved as instance @@ -35,7 +33,6 @@ class MonitorManagementClientConfiguration(Configuration): # pylint: disable=to """ def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: - super(MonitorManagementClientConfiguration, self).__init__(**kwargs) api_version: str = kwargs.pop("api_version", "2021-04-01") if credential is None: @@ -48,6 +45,7 @@ def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-monitor/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -56,9 +54,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.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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/_metadata.json b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/_metadata.json index 9781de4998c9..33df6a735c65 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/_metadata.json +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/_metadata.json @@ -8,10 +8,10 @@ "host_value": "\"https://management.azure.com\"", "parameterized_host_template": null, "azure_arm": true, - "has_lro_operations": false, + "has_public_lro_operations": false, "client_side_validation": false, - "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"sdkcore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMAutoResourceProviderRegistrationPolicy\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}, \"stdlib\": {\"typing_extensions\": [\"Self\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"sdkcore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"AsyncARMAutoResourceProviderRegistrationPolicy\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}, \"stdlib\": {\"typing_extensions\": [\"Self\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "global_parameters": { "sync": { @@ -101,8 +101,8 @@ "credential_scopes": ["https://management.azure.com/.default"], "credential_call_sync": "ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", "credential_call_async": "AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", - "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "sync_imports": "{\"regular\": {\"sdkcore\": {\"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"regular\": {\"sdkcore\": {\"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "operation_groups": { "data_collection_endpoints": "DataCollectionEndpointsOperations", diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/_monitor_management_client.py index 6dc1fd7840cb..125a81a93095 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/_monitor_management_client.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/_monitor_management_client.py @@ -8,9 +8,12 @@ from copy import deepcopy from typing import Any, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient +from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy from . import models as _models from .._serialization import Deserializer, Serializer @@ -22,11 +25,10 @@ ) if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MonitorManagementClient: # pylint: disable=client-accepts-api-version-keyword +class MonitorManagementClient: """Monitor Management Client. :ivar data_collection_endpoints: DataCollectionEndpointsOperations operations @@ -59,23 +61,41 @@ def __init__( self._config = MonitorManagementClientConfiguration( credential=credential, subscription_id=subscription_id, **kwargs ) - self._client: ARMPipelineClient = ARMPipelineClient(base_url=base_url, config=self._config, **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), + 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=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.data_collection_endpoints = DataCollectionEndpointsOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2021-04-01" ) self.data_collection_rule_associations = DataCollectionRuleAssociationsOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2021-04-01" ) self.data_collection_rules = DataCollectionRulesOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2021-04-01" ) - 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 @@ -95,12 +115,12 @@ 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) -> None: self._client.close() - def __enter__(self) -> "MonitorManagementClient": + def __enter__(self) -> Self: self._client.__enter__() return self diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/_vendor.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/_vendor.py deleted file mode 100644 index bd0df84f5319..000000000000 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/_vendor.py +++ /dev/null @@ -1,30 +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 typing import List, cast - -from azure.core.pipeline.transport import HttpRequest - - -def _convert_request(request, files=None): - data = request.content if not files else None - request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) - if files: - request.set_formdata_body(files) - return request - - -def _format_url_section(template, **kwargs): - components = template.split("/") - while components: - try: - return template.format(**kwargs) - except KeyError as key: - # Need the cast, as for some reasons "split" is typed as list[str | Any] - formatted_components = cast(List[str], template.split("/")) - components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] - template = "/".join(components) diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/_version.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/_version.py index 394ee7c0c03c..e5754a47ce68 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/_version.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "6.0.2" +VERSION = "1.0.0b1" diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/aio/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/aio/__init__.py index 2c151bb41c19..3df30ff42149 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/aio/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/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 ._monitor_management_client import MonitorManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._monitor_management_client import MonitorManagementClient # type: ignore try: from ._patch import __all__ as _patch_all - from ._patch import * # 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__ = [ "MonitorManagementClient", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/aio/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/aio/_configuration.py index 65ce5c443680..b5b2773ac4d8 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/aio/_configuration.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/aio/_configuration.py @@ -8,18 +8,16 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy from .._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MonitorManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class MonitorManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for MonitorManagementClient. Note that all parameters used to create this instance are saved as instance @@ -35,7 +33,6 @@ class MonitorManagementClientConfiguration(Configuration): # pylint: disable=to """ def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: - super(MonitorManagementClientConfiguration, self).__init__(**kwargs) api_version: str = kwargs.pop("api_version", "2021-04-01") if credential is None: @@ -48,6 +45,7 @@ def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **k self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-monitor/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -56,9 +54,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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/aio/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/aio/_monitor_management_client.py index 29882f3f0543..6029e55e0cbb 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/aio/_monitor_management_client.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/aio/_monitor_management_client.py @@ -8,9 +8,12 @@ from copy import deepcopy from typing import Any, Awaitable, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient +from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy from .. import models as _models from ..._serialization import Deserializer, Serializer @@ -22,11 +25,10 @@ ) if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MonitorManagementClient: # pylint: disable=client-accepts-api-version-keyword +class MonitorManagementClient: """Monitor Management Client. :ivar data_collection_endpoints: DataCollectionEndpointsOperations operations @@ -59,23 +61,43 @@ def __init__( self._config = MonitorManagementClientConfiguration( credential=credential, subscription_id=subscription_id, **kwargs ) - self._client: AsyncARMPipelineClient = AsyncARMPipelineClient(base_url=base_url, config=self._config, **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=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.data_collection_endpoints = DataCollectionEndpointsOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2021-04-01" ) self.data_collection_rule_associations = DataCollectionRuleAssociationsOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2021-04-01" ) self.data_collection_rules = DataCollectionRulesOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2021-04-01" ) - 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 @@ -95,12 +117,12 @@ 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) -> "MonitorManagementClient": + async def __aenter__(self) -> Self: await self._client.__aenter__() return self diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/aio/operations/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/aio/operations/__init__.py index 842046dd09e5..fe2d89505e75 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/aio/operations/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/aio/operations/__init__.py @@ -5,13 +5,19 @@ # 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 ._data_collection_endpoints_operations import DataCollectionEndpointsOperations -from ._data_collection_rule_associations_operations import DataCollectionRuleAssociationsOperations -from ._data_collection_rules_operations import DataCollectionRulesOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._data_collection_endpoints_operations import DataCollectionEndpointsOperations # type: ignore +from ._data_collection_rule_associations_operations import DataCollectionRuleAssociationsOperations # type: ignore +from ._data_collection_rules_operations import DataCollectionRulesOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ @@ -19,5 +25,5 @@ "DataCollectionRuleAssociationsOperations", "DataCollectionRulesOperations", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/aio/operations/_data_collection_endpoints_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/aio/operations/_data_collection_endpoints_operations.py index ecffa05e321a..9aa820be75cd 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/aio/operations/_data_collection_endpoints_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/aio/operations/_data_collection_endpoints_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload import urllib.parse @@ -19,15 +20,13 @@ 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 ...operations._data_collection_endpoints_operations import ( build_create_request, build_delete_request, @@ -37,6 +36,10 @@ build_update_request, ) +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -59,6 +62,7 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list_by_resource_group( @@ -71,7 +75,6 @@ def list_by_resource_group( :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either DataCollectionEndpointResource or the result of cls(response) :rtype: @@ -81,10 +84,10 @@ def list_by_resource_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-04-01")) cls: ClsType[_models.DataCollectionEndpointResourceListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -95,16 +98,14 @@ 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_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -115,14 +116,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("DataCollectionEndpointResourceListResult", pipeline_response) @@ -132,11 +132,11 @@ async def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -149,17 +149,12 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionEndpoints" - } - @distributed_trace def list_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.DataCollectionEndpointResource"]: """Lists all data collection endpoints in the specified subscription. Lists all data collection endpoints in the specified subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either DataCollectionEndpointResource or the result of cls(response) :rtype: @@ -169,10 +164,10 @@ def list_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.DataColl _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-04-01")) cls: ClsType[_models.DataCollectionEndpointResourceListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -183,15 +178,13 @@ def list_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.DataColl def prepare_request(next_link=None): if not next_link: - request = build_list_by_subscription_request( + _request = build_list_by_subscription_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_subscription.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -202,14 +195,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("DataCollectionEndpointResourceListResult", pipeline_response) @@ -219,11 +211,11 @@ async def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -236,10 +228,6 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_by_subscription.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/dataCollectionEndpoints" - } - @distributed_trace_async async def get( self, resource_group_name: str, data_collection_endpoint_name: str, **kwargs: Any @@ -254,12 +242,11 @@ async def get( :param data_collection_endpoint_name: The name of the data collection endpoint. The name is case insensitive. Required. :type data_collection_endpoint_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: DataCollectionEndpointResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_04_01.models.DataCollectionEndpointResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -270,24 +257,22 @@ async def get( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-04-01")) cls: ClsType[_models.DataCollectionEndpointResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, data_collection_endpoint_name=data_collection_endpoint_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -297,16 +282,12 @@ async def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponseCommonV2, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("DataCollectionEndpointResource", pipeline_response) + deserialized = self._deserialize("DataCollectionEndpointResource", 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.Insights/dataCollectionEndpoints/{dataCollectionEndpointName}" - } + return deserialized # type: ignore @overload async def create( @@ -333,7 +314,6 @@ async def create( :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: DataCollectionEndpointResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_04_01.models.DataCollectionEndpointResource :raises ~azure.core.exceptions.HttpResponseError: @@ -344,7 +324,7 @@ async def create( self, resource_group_name: str, data_collection_endpoint_name: str, - body: Optional[IO] = None, + body: Optional[IO[bytes]] = None, *, content_type: str = "application/json", **kwargs: Any @@ -360,11 +340,10 @@ async def create( case insensitive. Required. :type data_collection_endpoint_name: str :param body: The payload. Default value is None. - :type body: IO + :type body: 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: DataCollectionEndpointResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_04_01.models.DataCollectionEndpointResource :raises ~azure.core.exceptions.HttpResponseError: @@ -375,7 +354,7 @@ async def create( self, resource_group_name: str, data_collection_endpoint_name: str, - body: Optional[Union[_models.DataCollectionEndpointResource, IO]] = None, + body: Optional[Union[_models.DataCollectionEndpointResource, IO[bytes]]] = None, **kwargs: Any ) -> _models.DataCollectionEndpointResource: """Creates or updates a data collection endpoint. @@ -388,18 +367,14 @@ async def create( :param data_collection_endpoint_name: The name of the data collection endpoint. The name is case insensitive. Required. :type data_collection_endpoint_name: str - :param body: The payload. Is either a DataCollectionEndpointResource type or a IO type. Default - value is None. - :type body: ~azure.mgmt.monitor.v2021_04_01.models.DataCollectionEndpointResource or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + :param body: The payload. Is either a DataCollectionEndpointResource type or a IO[bytes] type. Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response + :type body: ~azure.mgmt.monitor.v2021_04_01.models.DataCollectionEndpointResource or IO[bytes] :return: DataCollectionEndpointResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_04_01.models.DataCollectionEndpointResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -410,14 +385,14 @@ async def create( _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", "2021-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-04-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.DataCollectionEndpointResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(body, (IO, bytes)): + if isinstance(body, (IOBase, bytes)): _content = body else: if body is not None: @@ -425,7 +400,7 @@ async def create( else: _json = None - request = build_create_request( + _request = build_create_request( resource_group_name=resource_group_name, data_collection_endpoint_name=data_collection_endpoint_name, subscription_id=self._config.subscription_id, @@ -433,16 +408,14 @@ async def create( content_type=content_type, json=_json, content=_content, - template_url=self.create.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -452,21 +425,13 @@ async def create( error = self._deserialize.failsafe_deserialize(_models.ErrorResponseCommonV2, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if response.status_code == 200: - deserialized = self._deserialize("DataCollectionEndpointResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("DataCollectionEndpointResource", pipeline_response) + deserialized = self._deserialize("DataCollectionEndpointResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionEndpoints/{dataCollectionEndpointName}" - } - @overload async def update( self, @@ -492,7 +457,6 @@ async def update( :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: DataCollectionEndpointResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_04_01.models.DataCollectionEndpointResource :raises ~azure.core.exceptions.HttpResponseError: @@ -503,7 +467,7 @@ async def update( self, resource_group_name: str, data_collection_endpoint_name: str, - body: Optional[IO] = None, + body: Optional[IO[bytes]] = None, *, content_type: str = "application/json", **kwargs: Any @@ -519,11 +483,10 @@ async def update( case insensitive. Required. :type data_collection_endpoint_name: str :param body: The payload. Default value is None. - :type body: IO + :type body: 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: DataCollectionEndpointResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_04_01.models.DataCollectionEndpointResource :raises ~azure.core.exceptions.HttpResponseError: @@ -534,7 +497,7 @@ async def update( self, resource_group_name: str, data_collection_endpoint_name: str, - body: Optional[Union[_models.ResourceForUpdate, IO]] = None, + body: Optional[Union[_models.ResourceForUpdate, IO[bytes]]] = None, **kwargs: Any ) -> _models.DataCollectionEndpointResource: """Updates part of a data collection endpoint. @@ -547,18 +510,14 @@ async def update( :param data_collection_endpoint_name: The name of the data collection endpoint. The name is case insensitive. Required. :type data_collection_endpoint_name: str - :param body: The payload. Is either a ResourceForUpdate type or a IO type. Default value is - None. - :type body: ~azure.mgmt.monitor.v2021_04_01.models.ResourceForUpdate 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 + :param body: The payload. Is either a ResourceForUpdate type or a IO[bytes] type. Default value + is None. + :type body: ~azure.mgmt.monitor.v2021_04_01.models.ResourceForUpdate or IO[bytes] :return: DataCollectionEndpointResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_04_01.models.DataCollectionEndpointResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -569,14 +528,14 @@ async def update( _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", "2021-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-04-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.DataCollectionEndpointResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(body, (IO, bytes)): + if isinstance(body, (IOBase, bytes)): _content = body else: if body is not None: @@ -584,7 +543,7 @@ async def update( else: _json = None - request = build_update_request( + _request = build_update_request( resource_group_name=resource_group_name, data_collection_endpoint_name=data_collection_endpoint_name, subscription_id=self._config.subscription_id, @@ -592,16 +551,14 @@ async def update( 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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -611,21 +568,15 @@ async def update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponseCommonV2, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("DataCollectionEndpointResource", pipeline_response) + deserialized = self._deserialize("DataCollectionEndpointResource", 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.Insights/dataCollectionEndpoints/{dataCollectionEndpointName}" - } + return deserialized # type: ignore @distributed_trace_async - async def delete( # pylint: disable=inconsistent-return-statements - self, resource_group_name: str, data_collection_endpoint_name: str, **kwargs: Any - ) -> None: + async def delete(self, resource_group_name: str, data_collection_endpoint_name: str, **kwargs: Any) -> None: """Deletes a data collection endpoint. Deletes a data collection endpoint. @@ -636,12 +587,11 @@ async def delete( # pylint: disable=inconsistent-return-statements :param data_collection_endpoint_name: The name of the data collection endpoint. The name is case insensitive. Required. :type data_collection_endpoint_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, @@ -652,24 +602,22 @@ async def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-04-01")) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, data_collection_endpoint_name=data_collection_endpoint_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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -680,8 +628,4 @@ async def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionEndpoints/{dataCollectionEndpointName}" - } + return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/aio/operations/_data_collection_rule_associations_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/aio/operations/_data_collection_rule_associations_operations.py index c46841eecdfe..0f29a290e9dd 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/aio/operations/_data_collection_rule_associations_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/aio/operations/_data_collection_rule_associations_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload import urllib.parse @@ -19,15 +20,13 @@ 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 ...operations._data_collection_rule_associations_operations import ( build_create_request, build_delete_request, @@ -36,6 +35,10 @@ build_list_by_rule_request, ) +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -58,18 +61,19 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list_by_resource( self, resource_uri: str, **kwargs: Any ) -> AsyncIterable["_models.DataCollectionRuleAssociationProxyOnlyResource"]: + # pylint: disable=line-too-long """Lists associations for the specified resource. Lists associations for the specified resource. :param resource_uri: The identifier of the resource. Required. :type resource_uri: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either DataCollectionRuleAssociationProxyOnlyResource or the result of cls(response) :rtype: @@ -79,10 +83,10 @@ def list_by_resource( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-04-01")) cls: ClsType[_models.DataCollectionRuleAssociationProxyOnlyResourceListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -93,15 +97,13 @@ def list_by_resource( def prepare_request(next_link=None): if not next_link: - request = build_list_by_resource_request( + _request = build_list_by_resource_request( resource_uri=resource_uri, api_version=api_version, - template_url=self.list_by_resource.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -112,14 +114,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize( @@ -131,11 +132,11 @@ async def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -148,12 +149,11 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_by_resource.metadata = {"url": "/{resourceUri}/providers/Microsoft.Insights/dataCollectionRuleAssociations"} - @distributed_trace def list_by_rule( self, resource_group_name: str, data_collection_rule_name: str, **kwargs: Any ) -> AsyncIterable["_models.DataCollectionRuleAssociationProxyOnlyResource"]: + # pylint: disable=line-too-long """Lists associations for the specified data collection rule. Lists associations for the specified data collection rule. @@ -164,7 +164,6 @@ def list_by_rule( :param data_collection_rule_name: The name of the data collection rule. The name is case insensitive. Required. :type data_collection_rule_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either DataCollectionRuleAssociationProxyOnlyResource or the result of cls(response) :rtype: @@ -174,10 +173,10 @@ def list_by_rule( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-04-01")) cls: ClsType[_models.DataCollectionRuleAssociationProxyOnlyResourceListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -188,17 +187,15 @@ def list_by_rule( def prepare_request(next_link=None): if not next_link: - request = build_list_by_rule_request( + _request = build_list_by_rule_request( resource_group_name=resource_group_name, data_collection_rule_name=data_collection_rule_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_rule.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -209,14 +206,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize( @@ -228,11 +224,11 @@ async def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -245,10 +241,6 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_by_rule.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionRules/{dataCollectionRuleName}/associations" - } - @distributed_trace_async async def get( self, resource_uri: str, association_name: str, **kwargs: Any @@ -261,12 +253,11 @@ async def get( :type resource_uri: str :param association_name: The name of the association. The name is case insensitive. Required. :type association_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: DataCollectionRuleAssociationProxyOnlyResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_04_01.models.DataCollectionRuleAssociationProxyOnlyResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -277,23 +268,21 @@ async def get( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-04-01")) cls: ClsType[_models.DataCollectionRuleAssociationProxyOnlyResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_uri=resource_uri, association_name=association_name, api_version=api_version, - template_url=self.get.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -303,16 +292,14 @@ async def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponseCommonV2, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("DataCollectionRuleAssociationProxyOnlyResource", pipeline_response) + deserialized = self._deserialize( + "DataCollectionRuleAssociationProxyOnlyResource", pipeline_response.http_response + ) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get.metadata = { - "url": "/{resourceUri}/providers/Microsoft.Insights/dataCollectionRuleAssociations/{associationName}" - } + return deserialized # type: ignore @overload async def create( @@ -338,7 +325,6 @@ async def create( :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: DataCollectionRuleAssociationProxyOnlyResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_04_01.models.DataCollectionRuleAssociationProxyOnlyResource :raises ~azure.core.exceptions.HttpResponseError: @@ -349,7 +335,7 @@ async def create( self, resource_uri: str, association_name: str, - body: Optional[IO] = None, + body: Optional[IO[bytes]] = None, *, content_type: str = "application/json", **kwargs: Any @@ -363,11 +349,10 @@ async def create( :param association_name: The name of the association. The name is case insensitive. Required. :type association_name: str :param body: The payload. Default value is None. - :type body: IO + :type body: 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: DataCollectionRuleAssociationProxyOnlyResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_04_01.models.DataCollectionRuleAssociationProxyOnlyResource :raises ~azure.core.exceptions.HttpResponseError: @@ -378,7 +363,7 @@ async def create( self, resource_uri: str, association_name: str, - body: Optional[Union[_models.DataCollectionRuleAssociationProxyOnlyResource, IO]] = None, + body: Optional[Union[_models.DataCollectionRuleAssociationProxyOnlyResource, IO[bytes]]] = None, **kwargs: Any ) -> _models.DataCollectionRuleAssociationProxyOnlyResource: """Creates or updates an association. @@ -390,18 +375,15 @@ async def create( :param association_name: The name of the association. The name is case insensitive. Required. :type association_name: str :param body: The payload. Is either a DataCollectionRuleAssociationProxyOnlyResource type or a - IO type. Default value is None. + IO[bytes] type. Default value is None. :type body: - ~azure.mgmt.monitor.v2021_04_01.models.DataCollectionRuleAssociationProxyOnlyResource 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 + ~azure.mgmt.monitor.v2021_04_01.models.DataCollectionRuleAssociationProxyOnlyResource or + IO[bytes] :return: DataCollectionRuleAssociationProxyOnlyResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_04_01.models.DataCollectionRuleAssociationProxyOnlyResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -412,14 +394,14 @@ async def create( _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", "2021-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-04-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.DataCollectionRuleAssociationProxyOnlyResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(body, (IO, bytes)): + if isinstance(body, (IOBase, bytes)): _content = body else: if body is not None: @@ -427,23 +409,21 @@ async def create( else: _json = None - request = build_create_request( + _request = build_create_request( resource_uri=resource_uri, association_name=association_name, api_version=api_version, content_type=content_type, json=_json, content=_content, - template_url=self.create.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -453,25 +433,17 @@ async def create( error = self._deserialize.failsafe_deserialize(_models.ErrorResponseCommonV2, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if response.status_code == 200: - deserialized = self._deserialize("DataCollectionRuleAssociationProxyOnlyResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("DataCollectionRuleAssociationProxyOnlyResource", pipeline_response) + deserialized = self._deserialize( + "DataCollectionRuleAssociationProxyOnlyResource", pipeline_response.http_response + ) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create.metadata = { - "url": "/{resourceUri}/providers/Microsoft.Insights/dataCollectionRuleAssociations/{associationName}" - } - @distributed_trace_async - async def delete( # pylint: disable=inconsistent-return-statements - self, resource_uri: str, association_name: str, **kwargs: Any - ) -> None: + async def delete(self, resource_uri: str, association_name: str, **kwargs: Any) -> None: """Deletes an association. Deletes an association. @@ -480,12 +452,11 @@ async def delete( # pylint: disable=inconsistent-return-statements :type resource_uri: str :param association_name: The name of the association. The name is case insensitive. Required. :type association_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, @@ -496,23 +467,21 @@ async def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-04-01")) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_uri=resource_uri, association_name=association_name, api_version=api_version, - template_url=self.delete.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -523,8 +492,4 @@ async def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/{resourceUri}/providers/Microsoft.Insights/dataCollectionRuleAssociations/{associationName}" - } + return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/aio/operations/_data_collection_rules_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/aio/operations/_data_collection_rules_operations.py index 45c77f5cb0c8..135aea2b718c 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/aio/operations/_data_collection_rules_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/aio/operations/_data_collection_rules_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload import urllib.parse @@ -19,15 +20,13 @@ 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 ...operations._data_collection_rules_operations import ( build_create_request, build_delete_request, @@ -37,6 +36,10 @@ build_update_request, ) +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -59,6 +62,7 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list_by_resource_group( @@ -71,7 +75,6 @@ def list_by_resource_group( :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either DataCollectionRuleResource or the result of cls(response) :rtype: @@ -81,10 +84,10 @@ def list_by_resource_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-04-01")) cls: ClsType[_models.DataCollectionRuleResourceListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -95,16 +98,14 @@ 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_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -115,14 +116,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("DataCollectionRuleResourceListResult", pipeline_response) @@ -132,11 +132,11 @@ async def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -149,17 +149,12 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionRules" - } - @distributed_trace def list_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.DataCollectionRuleResource"]: """Lists all data collection rules in the specified subscription. Lists all data collection rules in the specified subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either DataCollectionRuleResource or the result of cls(response) :rtype: @@ -169,10 +164,10 @@ def list_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.DataColl _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-04-01")) cls: ClsType[_models.DataCollectionRuleResourceListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -183,15 +178,13 @@ def list_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.DataColl def prepare_request(next_link=None): if not next_link: - request = build_list_by_subscription_request( + _request = build_list_by_subscription_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_subscription.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -202,14 +195,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("DataCollectionRuleResourceListResult", pipeline_response) @@ -219,11 +211,11 @@ async def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -236,10 +228,6 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_by_subscription.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/dataCollectionRules" - } - @distributed_trace_async async def get( self, resource_group_name: str, data_collection_rule_name: str, **kwargs: Any @@ -254,12 +242,11 @@ async def get( :param data_collection_rule_name: The name of the data collection rule. The name is case insensitive. Required. :type data_collection_rule_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: DataCollectionRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_04_01.models.DataCollectionRuleResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -270,24 +257,22 @@ async def get( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-04-01")) cls: ClsType[_models.DataCollectionRuleResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, data_collection_rule_name=data_collection_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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -297,16 +282,12 @@ async def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponseCommonV2, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("DataCollectionRuleResource", pipeline_response) + deserialized = self._deserialize("DataCollectionRuleResource", 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.Insights/dataCollectionRules/{dataCollectionRuleName}" - } + return deserialized # type: ignore @overload async def create( @@ -333,7 +314,6 @@ async def create( :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: DataCollectionRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_04_01.models.DataCollectionRuleResource :raises ~azure.core.exceptions.HttpResponseError: @@ -344,7 +324,7 @@ async def create( self, resource_group_name: str, data_collection_rule_name: str, - body: Optional[IO] = None, + body: Optional[IO[bytes]] = None, *, content_type: str = "application/json", **kwargs: Any @@ -360,11 +340,10 @@ async def create( insensitive. Required. :type data_collection_rule_name: str :param body: The payload. Default value is None. - :type body: IO + :type body: 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: DataCollectionRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_04_01.models.DataCollectionRuleResource :raises ~azure.core.exceptions.HttpResponseError: @@ -375,7 +354,7 @@ async def create( self, resource_group_name: str, data_collection_rule_name: str, - body: Optional[Union[_models.DataCollectionRuleResource, IO]] = None, + body: Optional[Union[_models.DataCollectionRuleResource, IO[bytes]]] = None, **kwargs: Any ) -> _models.DataCollectionRuleResource: """Creates or updates a data collection rule. @@ -388,18 +367,14 @@ async def create( :param data_collection_rule_name: The name of the data collection rule. The name is case insensitive. Required. :type data_collection_rule_name: str - :param body: The payload. Is either a DataCollectionRuleResource type or a IO type. Default - value is None. - :type body: ~azure.mgmt.monitor.v2021_04_01.models.DataCollectionRuleResource or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + :param body: The payload. Is either a DataCollectionRuleResource type or a IO[bytes] type. Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response + :type body: ~azure.mgmt.monitor.v2021_04_01.models.DataCollectionRuleResource or IO[bytes] :return: DataCollectionRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_04_01.models.DataCollectionRuleResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -410,14 +385,14 @@ async def create( _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", "2021-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-04-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.DataCollectionRuleResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(body, (IO, bytes)): + if isinstance(body, (IOBase, bytes)): _content = body else: if body is not None: @@ -425,7 +400,7 @@ async def create( else: _json = None - request = build_create_request( + _request = build_create_request( resource_group_name=resource_group_name, data_collection_rule_name=data_collection_rule_name, subscription_id=self._config.subscription_id, @@ -433,16 +408,14 @@ async def create( content_type=content_type, json=_json, content=_content, - template_url=self.create.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -452,21 +425,13 @@ async def create( error = self._deserialize.failsafe_deserialize(_models.ErrorResponseCommonV2, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if response.status_code == 200: - deserialized = self._deserialize("DataCollectionRuleResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("DataCollectionRuleResource", pipeline_response) + deserialized = self._deserialize("DataCollectionRuleResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionRules/{dataCollectionRuleName}" - } - @overload async def update( self, @@ -492,7 +457,6 @@ async def update( :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: DataCollectionRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_04_01.models.DataCollectionRuleResource :raises ~azure.core.exceptions.HttpResponseError: @@ -503,7 +467,7 @@ async def update( self, resource_group_name: str, data_collection_rule_name: str, - body: Optional[IO] = None, + body: Optional[IO[bytes]] = None, *, content_type: str = "application/json", **kwargs: Any @@ -519,11 +483,10 @@ async def update( insensitive. Required. :type data_collection_rule_name: str :param body: The payload. Default value is None. - :type body: IO + :type body: 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: DataCollectionRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_04_01.models.DataCollectionRuleResource :raises ~azure.core.exceptions.HttpResponseError: @@ -534,7 +497,7 @@ async def update( self, resource_group_name: str, data_collection_rule_name: str, - body: Optional[Union[_models.ResourceForUpdate, IO]] = None, + body: Optional[Union[_models.ResourceForUpdate, IO[bytes]]] = None, **kwargs: Any ) -> _models.DataCollectionRuleResource: """Updates part of a data collection rule. @@ -547,18 +510,14 @@ async def update( :param data_collection_rule_name: The name of the data collection rule. The name is case insensitive. Required. :type data_collection_rule_name: str - :param body: The payload. Is either a ResourceForUpdate type or a IO type. Default value is - None. - :type body: ~azure.mgmt.monitor.v2021_04_01.models.ResourceForUpdate 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 + :param body: The payload. Is either a ResourceForUpdate type or a IO[bytes] type. Default value + is None. + :type body: ~azure.mgmt.monitor.v2021_04_01.models.ResourceForUpdate or IO[bytes] :return: DataCollectionRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_04_01.models.DataCollectionRuleResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -569,14 +528,14 @@ async def update( _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", "2021-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-04-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.DataCollectionRuleResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(body, (IO, bytes)): + if isinstance(body, (IOBase, bytes)): _content = body else: if body is not None: @@ -584,7 +543,7 @@ async def update( else: _json = None - request = build_update_request( + _request = build_update_request( resource_group_name=resource_group_name, data_collection_rule_name=data_collection_rule_name, subscription_id=self._config.subscription_id, @@ -592,16 +551,14 @@ async def update( 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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -611,21 +568,15 @@ async def update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponseCommonV2, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("DataCollectionRuleResource", pipeline_response) + deserialized = self._deserialize("DataCollectionRuleResource", 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.Insights/dataCollectionRules/{dataCollectionRuleName}" - } + return deserialized # type: ignore @distributed_trace_async - async def delete( # pylint: disable=inconsistent-return-statements - self, resource_group_name: str, data_collection_rule_name: str, **kwargs: Any - ) -> None: + async def delete(self, resource_group_name: str, data_collection_rule_name: str, **kwargs: Any) -> None: """Deletes a data collection rule. Deletes a data collection rule. @@ -636,12 +587,11 @@ async def delete( # pylint: disable=inconsistent-return-statements :param data_collection_rule_name: The name of the data collection rule. The name is case insensitive. Required. :type data_collection_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, @@ -652,24 +602,22 @@ async def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-04-01")) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, data_collection_rule_name=data_collection_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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -680,8 +628,4 @@ async def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionRules/{dataCollectionRuleName}" - } + return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/models/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/models/__init__.py index 69ec359db511..1916690267d0 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/models/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/models/__init__.py @@ -5,62 +5,73 @@ # 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 AzureMonitorMetricsDestination -from ._models_py3 import ConfigurationAccessEndpointSpec -from ._models_py3 import DataCollectionEndpoint -from ._models_py3 import DataCollectionEndpointConfigurationAccess -from ._models_py3 import DataCollectionEndpointLogsIngestion -from ._models_py3 import DataCollectionEndpointNetworkAcls -from ._models_py3 import DataCollectionEndpointResource -from ._models_py3 import DataCollectionEndpointResourceListResult -from ._models_py3 import DataCollectionEndpointResourceProperties -from ._models_py3 import DataCollectionEndpointResourceSystemData -from ._models_py3 import DataCollectionRule -from ._models_py3 import DataCollectionRuleAssociation -from ._models_py3 import DataCollectionRuleAssociationProxyOnlyResource -from ._models_py3 import DataCollectionRuleAssociationProxyOnlyResourceListResult -from ._models_py3 import DataCollectionRuleAssociationProxyOnlyResourceProperties -from ._models_py3 import DataCollectionRuleAssociationProxyOnlyResourceSystemData -from ._models_py3 import DataCollectionRuleDataSources -from ._models_py3 import DataCollectionRuleDestinations -from ._models_py3 import DataCollectionRuleResource -from ._models_py3 import DataCollectionRuleResourceListResult -from ._models_py3 import DataCollectionRuleResourceProperties -from ._models_py3 import DataCollectionRuleResourceSystemData -from ._models_py3 import DataFlow -from ._models_py3 import DataSourcesSpec -from ._models_py3 import DestinationsSpec -from ._models_py3 import DestinationsSpecAzureMonitorMetrics -from ._models_py3 import ErrorAdditionalInfo -from ._models_py3 import ErrorDetail -from ._models_py3 import ErrorResponseCommonV2 -from ._models_py3 import ExtensionDataSource -from ._models_py3 import LogAnalyticsDestination -from ._models_py3 import LogsIngestionEndpointSpec -from ._models_py3 import NetworkRuleSet -from ._models_py3 import PerfCounterDataSource -from ._models_py3 import ResourceForUpdate -from ._models_py3 import SyslogDataSource -from ._models_py3 import SystemData -from ._models_py3 import WindowsEventLogDataSource +from typing import TYPE_CHECKING -from ._monitor_management_client_enums import CreatedByType -from ._monitor_management_client_enums import KnownDataCollectionEndpointProvisioningState -from ._monitor_management_client_enums import KnownDataCollectionEndpointResourceKind -from ._monitor_management_client_enums import KnownDataCollectionRuleAssociationProvisioningState -from ._monitor_management_client_enums import KnownDataCollectionRuleProvisioningState -from ._monitor_management_client_enums import KnownDataCollectionRuleResourceKind -from ._monitor_management_client_enums import KnownDataFlowStreams -from ._monitor_management_client_enums import KnownExtensionDataSourceStreams -from ._monitor_management_client_enums import KnownPerfCounterDataSourceStreams -from ._monitor_management_client_enums import KnownPublicNetworkAccessOptions -from ._monitor_management_client_enums import KnownSyslogDataSourceFacilityNames -from ._monitor_management_client_enums import KnownSyslogDataSourceLogLevels -from ._monitor_management_client_enums import KnownSyslogDataSourceStreams -from ._monitor_management_client_enums import KnownWindowsEventLogDataSourceStreams +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models_py3 import ( # type: ignore + AzureMonitorMetricsDestination, + ConfigurationAccessEndpointSpec, + DataCollectionEndpoint, + DataCollectionEndpointConfigurationAccess, + DataCollectionEndpointLogsIngestion, + DataCollectionEndpointNetworkAcls, + DataCollectionEndpointResource, + DataCollectionEndpointResourceListResult, + DataCollectionEndpointResourceProperties, + DataCollectionEndpointResourceSystemData, + DataCollectionRule, + DataCollectionRuleAssociation, + DataCollectionRuleAssociationProxyOnlyResource, + DataCollectionRuleAssociationProxyOnlyResourceListResult, + DataCollectionRuleAssociationProxyOnlyResourceProperties, + DataCollectionRuleAssociationProxyOnlyResourceSystemData, + DataCollectionRuleDataSources, + DataCollectionRuleDestinations, + DataCollectionRuleResource, + DataCollectionRuleResourceListResult, + DataCollectionRuleResourceProperties, + DataCollectionRuleResourceSystemData, + DataFlow, + DataSourcesSpec, + DestinationsSpec, + DestinationsSpecAzureMonitorMetrics, + ErrorAdditionalInfo, + ErrorDetail, + ErrorResponseCommonV2, + ExtensionDataSource, + LogAnalyticsDestination, + LogsIngestionEndpointSpec, + NetworkRuleSet, + PerfCounterDataSource, + ResourceForUpdate, + SyslogDataSource, + SystemData, + WindowsEventLogDataSource, +) + +from ._monitor_management_client_enums import ( # type: ignore + CreatedByType, + KnownDataCollectionEndpointProvisioningState, + KnownDataCollectionEndpointResourceKind, + KnownDataCollectionRuleAssociationProvisioningState, + KnownDataCollectionRuleProvisioningState, + KnownDataCollectionRuleResourceKind, + KnownDataFlowStreams, + KnownExtensionDataSourceStreams, + KnownPerfCounterDataSourceStreams, + KnownPublicNetworkAccessOptions, + KnownSyslogDataSourceFacilityNames, + KnownSyslogDataSourceLogLevels, + KnownSyslogDataSourceStreams, + KnownWindowsEventLogDataSourceStreams, +) from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ @@ -117,5 +128,5 @@ "KnownSyslogDataSourceStreams", "KnownWindowsEventLogDataSourceStreams", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/models/_models_py3.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/models/_models_py3.py index d1e806110d5f..8d5b77ec9a8e 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/models/_models_py3.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/models/_models_py3.py @@ -1,5 +1,5 @@ -# coding=utf-8 # 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. @@ -16,10 +16,9 @@ if sys.version_info >= (3, 9): from collections.abc import MutableMapping else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports + from typing import MutableMapping # type: ignore if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from .. import models as _models JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object @@ -143,7 +142,7 @@ def __init__( self.provisioning_state = None -class DataCollectionEndpointConfigurationAccess(ConfigurationAccessEndpointSpec): +class DataCollectionEndpointConfigurationAccess(ConfigurationAccessEndpointSpec): # pylint: disable=name-too-long """The endpoint used by agents to access their configuration. Variables are only populated by the server, and will be ignored when sending a request. @@ -152,18 +151,6 @@ class DataCollectionEndpointConfigurationAccess(ConfigurationAccessEndpointSpec) :vartype endpoint: str """ - _validation = { - "endpoint": {"readonly": True}, - } - - _attribute_map = { - "endpoint": {"key": "endpoint", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - class LogsIngestionEndpointSpec(_serialization.Model): """Definition of the endpoint used for ingesting logs. @@ -197,18 +184,6 @@ class DataCollectionEndpointLogsIngestion(LogsIngestionEndpointSpec): :vartype endpoint: str """ - _validation = { - "endpoint": {"readonly": True}, - } - - _attribute_map = { - "endpoint": {"key": "endpoint", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - class NetworkRuleSet(_serialization.Model): """Definition of the network rules. @@ -248,31 +223,13 @@ class DataCollectionEndpointNetworkAcls(NetworkRuleSet): ~azure.mgmt.monitor.v2021_04_01.models.KnownPublicNetworkAccessOptions """ - _attribute_map = { - "public_network_access": {"key": "publicNetworkAccess", "type": "str"}, - } - def __init__( - self, - *, - public_network_access: Optional[Union[str, "_models.KnownPublicNetworkAccessOptions"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword public_network_access: The configuration to set whether network access from public - internet to the endpoints are allowed. Known values are: "Enabled" and "Disabled". - :paramtype public_network_access: str or - ~azure.mgmt.monitor.v2021_04_01.models.KnownPublicNetworkAccessOptions - """ - super().__init__(public_network_access=public_network_access, **kwargs) - - -class DataCollectionEndpointResource(_serialization.Model): # pylint: disable=too-many-instance-attributes +class DataCollectionEndpointResource(_serialization.Model): """Definition of ARM tracked top level 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 location: The geo-location where the resource lives. Required. :vartype location: str @@ -397,7 +354,7 @@ def __init__( class DataCollectionEndpointResourceListResult(_serialization.Model): """A pageable list of resources. - 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 value: A list of resources. Required. :vartype value: list[~azure.mgmt.monitor.v2021_04_01.models.DataCollectionEndpointResource] @@ -452,54 +409,6 @@ class DataCollectionEndpointResourceProperties(DataCollectionEndpoint): ~azure.mgmt.monitor.v2021_04_01.models.KnownDataCollectionEndpointProvisioningState """ - _validation = { - "provisioning_state": {"readonly": True}, - } - - _attribute_map = { - "description": {"key": "description", "type": "str"}, - "immutable_id": {"key": "immutableId", "type": "str"}, - "configuration_access": {"key": "configurationAccess", "type": "DataCollectionEndpointConfigurationAccess"}, - "logs_ingestion": {"key": "logsIngestion", "type": "DataCollectionEndpointLogsIngestion"}, - "network_acls": {"key": "networkAcls", "type": "DataCollectionEndpointNetworkAcls"}, - "provisioning_state": {"key": "provisioningState", "type": "str"}, - } - - def __init__( - self, - *, - description: Optional[str] = None, - immutable_id: Optional[str] = None, - configuration_access: Optional["_models.DataCollectionEndpointConfigurationAccess"] = None, - logs_ingestion: Optional["_models.DataCollectionEndpointLogsIngestion"] = None, - network_acls: Optional["_models.DataCollectionEndpointNetworkAcls"] = None, - **kwargs: Any - ) -> None: - """ - :keyword description: Description of the data collection endpoint. - :paramtype description: str - :keyword immutable_id: The immutable ID of this data collection endpoint resource. This - property is READ-ONLY. - :paramtype immutable_id: str - :keyword configuration_access: The endpoint used by agents to access their configuration. - :paramtype configuration_access: - ~azure.mgmt.monitor.v2021_04_01.models.DataCollectionEndpointConfigurationAccess - :keyword logs_ingestion: The endpoint used by clients to ingest logs. - :paramtype logs_ingestion: - ~azure.mgmt.monitor.v2021_04_01.models.DataCollectionEndpointLogsIngestion - :keyword network_acls: Network access control rules for the endpoints. - :paramtype network_acls: - ~azure.mgmt.monitor.v2021_04_01.models.DataCollectionEndpointNetworkAcls - """ - super().__init__( - description=description, - immutable_id=immutable_id, - configuration_access=configuration_access, - logs_ingestion=logs_ingestion, - network_acls=network_acls, - **kwargs - ) - class SystemData(_serialization.Model): """Metadata pertaining to creation and last modification of the resource. @@ -584,52 +493,6 @@ class DataCollectionEndpointResourceSystemData(SystemData): :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: 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.monitor.v2021_04_01.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.monitor.v2021_04_01.models.CreatedByType - :keyword last_modified_at: The timestamp of resource last modification (UTC). - :paramtype last_modified_at: ~datetime.datetime - """ - super().__init__( - created_by=created_by, - created_by_type=created_by_type, - created_at=created_at, - last_modified_by=last_modified_by, - last_modified_by_type=last_modified_by_type, - last_modified_at=last_modified_at, - **kwargs - ) - class DataCollectionRule(_serialization.Model): """Definition of what monitoring data to collect and where that data should be sent. @@ -753,7 +616,7 @@ def __init__( self.provisioning_state = None -class DataCollectionRuleAssociationProxyOnlyResource(_serialization.Model): +class DataCollectionRuleAssociationProxyOnlyResource(_serialization.Model): # pylint: disable=name-too-long """Definition of generic ARM proxy resource. Variables are only populated by the server, and will be ignored when sending a request. @@ -834,10 +697,10 @@ def __init__( self.provisioning_state = None -class DataCollectionRuleAssociationProxyOnlyResourceListResult(_serialization.Model): +class DataCollectionRuleAssociationProxyOnlyResourceListResult(_serialization.Model): # pylint: disable=name-too-long """A pageable list of resources. - 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 value: A list of resources. Required. :vartype value: @@ -874,7 +737,9 @@ def __init__( self.next_link = next_link -class DataCollectionRuleAssociationProxyOnlyResourceProperties(DataCollectionRuleAssociation): +class DataCollectionRuleAssociationProxyOnlyResourceProperties( + DataCollectionRuleAssociation +): # pylint: disable=name-too-long """Resource properties. Variables are only populated by the server, and will be ignored when sending a request. @@ -893,44 +758,8 @@ class DataCollectionRuleAssociationProxyOnlyResourceProperties(DataCollectionRul ~azure.mgmt.monitor.v2021_04_01.models.KnownDataCollectionRuleAssociationProvisioningState """ - _validation = { - "provisioning_state": {"readonly": True}, - } - - _attribute_map = { - "description": {"key": "description", "type": "str"}, - "data_collection_rule_id": {"key": "dataCollectionRuleId", "type": "str"}, - "data_collection_endpoint_id": {"key": "dataCollectionEndpointId", "type": "str"}, - "provisioning_state": {"key": "provisioningState", "type": "str"}, - } - - def __init__( - self, - *, - description: Optional[str] = None, - data_collection_rule_id: Optional[str] = None, - data_collection_endpoint_id: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword description: Description of the association. - :paramtype description: str - :keyword data_collection_rule_id: The resource ID of the data collection rule that is to be - associated. - :paramtype data_collection_rule_id: str - :keyword data_collection_endpoint_id: The resource ID of the data collection endpoint that is - to be associated. - :paramtype data_collection_endpoint_id: str - """ - super().__init__( - description=description, - data_collection_rule_id=data_collection_rule_id, - data_collection_endpoint_id=data_collection_endpoint_id, - **kwargs - ) - -class DataCollectionRuleAssociationProxyOnlyResourceSystemData(SystemData): +class DataCollectionRuleAssociationProxyOnlyResourceSystemData(SystemData): # pylint: disable=name-too-long """Metadata pertaining to creation and last modification of the resource. :ivar created_by: The identity that created the resource. @@ -949,52 +778,6 @@ class DataCollectionRuleAssociationProxyOnlyResourceSystemData(SystemData): :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: 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.monitor.v2021_04_01.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.monitor.v2021_04_01.models.CreatedByType - :keyword last_modified_at: The timestamp of resource last modification (UTC). - :paramtype last_modified_at: ~datetime.datetime - """ - super().__init__( - created_by=created_by, - created_by_type=created_by_type, - created_at=created_at, - last_modified_by=last_modified_by, - last_modified_by_type=last_modified_by_type, - last_modified_at=last_modified_at, - **kwargs - ) - class DataSourcesSpec(_serialization.Model): """Specification of data sources that will be collected. @@ -1063,42 +846,6 @@ class DataCollectionRuleDataSources(DataSourcesSpec): :vartype extensions: list[~azure.mgmt.monitor.v2021_04_01.models.ExtensionDataSource] """ - _attribute_map = { - "performance_counters": {"key": "performanceCounters", "type": "[PerfCounterDataSource]"}, - "windows_event_logs": {"key": "windowsEventLogs", "type": "[WindowsEventLogDataSource]"}, - "syslog": {"key": "syslog", "type": "[SyslogDataSource]"}, - "extensions": {"key": "extensions", "type": "[ExtensionDataSource]"}, - } - - def __init__( - self, - *, - performance_counters: Optional[List["_models.PerfCounterDataSource"]] = None, - windows_event_logs: Optional[List["_models.WindowsEventLogDataSource"]] = None, - syslog: Optional[List["_models.SyslogDataSource"]] = None, - extensions: Optional[List["_models.ExtensionDataSource"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword performance_counters: The list of performance counter data source configurations. - :paramtype performance_counters: - list[~azure.mgmt.monitor.v2021_04_01.models.PerfCounterDataSource] - :keyword windows_event_logs: The list of Windows Event Log data source configurations. - :paramtype windows_event_logs: - list[~azure.mgmt.monitor.v2021_04_01.models.WindowsEventLogDataSource] - :keyword syslog: The list of Syslog data source configurations. - :paramtype syslog: list[~azure.mgmt.monitor.v2021_04_01.models.SyslogDataSource] - :keyword extensions: The list of Azure VM extension data source configurations. - :paramtype extensions: list[~azure.mgmt.monitor.v2021_04_01.models.ExtensionDataSource] - """ - super().__init__( - performance_counters=performance_counters, - windows_event_logs=windows_event_logs, - syslog=syslog, - extensions=extensions, - **kwargs - ) - class DestinationsSpec(_serialization.Model): """Specification of destinations that can be used in data flows. @@ -1144,34 +891,13 @@ class DataCollectionRuleDestinations(DestinationsSpec): ~azure.mgmt.monitor.v2021_04_01.models.DestinationsSpecAzureMonitorMetrics """ - _attribute_map = { - "log_analytics": {"key": "logAnalytics", "type": "[LogAnalyticsDestination]"}, - "azure_monitor_metrics": {"key": "azureMonitorMetrics", "type": "DestinationsSpecAzureMonitorMetrics"}, - } - - def __init__( - self, - *, - log_analytics: Optional[List["_models.LogAnalyticsDestination"]] = None, - azure_monitor_metrics: Optional["_models.DestinationsSpecAzureMonitorMetrics"] = None, - **kwargs: Any - ) -> None: - """ - :keyword log_analytics: List of Log Analytics destinations. - :paramtype log_analytics: list[~azure.mgmt.monitor.v2021_04_01.models.LogAnalyticsDestination] - :keyword azure_monitor_metrics: Azure Monitor Metrics destination. - :paramtype azure_monitor_metrics: - ~azure.mgmt.monitor.v2021_04_01.models.DestinationsSpecAzureMonitorMetrics - """ - super().__init__(log_analytics=log_analytics, azure_monitor_metrics=azure_monitor_metrics, **kwargs) - -class DataCollectionRuleResource(_serialization.Model): # pylint: disable=too-many-instance-attributes +class DataCollectionRuleResource(_serialization.Model): """Definition of ARM tracked top level 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 location: The geo-location where the resource lives. Required. :vartype location: str @@ -1288,7 +1014,7 @@ def __init__( class DataCollectionRuleResourceListResult(_serialization.Model): """A pageable list of resources. - 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 value: A list of resources. Required. :vartype value: list[~azure.mgmt.monitor.v2021_04_01.models.DataCollectionRuleResource] @@ -1342,49 +1068,6 @@ class DataCollectionRuleResourceProperties(DataCollectionRule): ~azure.mgmt.monitor.v2021_04_01.models.KnownDataCollectionRuleProvisioningState """ - _validation = { - "immutable_id": {"readonly": True}, - "provisioning_state": {"readonly": True}, - } - - _attribute_map = { - "description": {"key": "description", "type": "str"}, - "immutable_id": {"key": "immutableId", "type": "str"}, - "data_sources": {"key": "dataSources", "type": "DataCollectionRuleDataSources"}, - "destinations": {"key": "destinations", "type": "DataCollectionRuleDestinations"}, - "data_flows": {"key": "dataFlows", "type": "[DataFlow]"}, - "provisioning_state": {"key": "provisioningState", "type": "str"}, - } - - def __init__( - self, - *, - description: Optional[str] = None, - data_sources: Optional["_models.DataCollectionRuleDataSources"] = None, - destinations: Optional["_models.DataCollectionRuleDestinations"] = None, - data_flows: Optional[List["_models.DataFlow"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword description: Description of the data collection rule. - :paramtype description: str - :keyword data_sources: The specification of data sources. - This property is optional and can be omitted if the rule is meant to be used via direct calls - to the provisioned endpoint. - :paramtype data_sources: ~azure.mgmt.monitor.v2021_04_01.models.DataCollectionRuleDataSources - :keyword destinations: The specification of destinations. - :paramtype destinations: ~azure.mgmt.monitor.v2021_04_01.models.DataCollectionRuleDestinations - :keyword data_flows: The specification of data flows. - :paramtype data_flows: list[~azure.mgmt.monitor.v2021_04_01.models.DataFlow] - """ - super().__init__( - description=description, - data_sources=data_sources, - destinations=destinations, - data_flows=data_flows, - **kwargs - ) - class DataCollectionRuleResourceSystemData(SystemData): """Metadata pertaining to creation and last modification of the resource. @@ -1405,52 +1088,6 @@ class DataCollectionRuleResourceSystemData(SystemData): :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: 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.monitor.v2021_04_01.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.monitor.v2021_04_01.models.CreatedByType - :keyword last_modified_at: The timestamp of resource last modification (UTC). - :paramtype last_modified_at: ~datetime.datetime - """ - super().__init__( - created_by=created_by, - created_by_type=created_by_type, - created_at=created_at, - last_modified_by=last_modified_by, - last_modified_by_type=last_modified_by_type, - last_modified_at=last_modified_at, - **kwargs - ) - class DataFlow(_serialization.Model): """Definition of which streams are sent to which destinations. @@ -1493,19 +1130,6 @@ class DestinationsSpecAzureMonitorMetrics(AzureMonitorMetricsDestination): :vartype name: str """ - _attribute_map = { - "name": {"key": "name", "type": "str"}, - } - - def __init__(self, *, name: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword name: A friendly name for the destination. - This name should be unique across all destinations (regardless of type) within the data - collection rule. - :paramtype name: str - """ - super().__init__(name=name, **kwargs) - class ErrorAdditionalInfo(_serialization.Model): """The resource management error additional info. @@ -1604,7 +1228,7 @@ class ExtensionDataSource(_serialization.Model): the Azure Monitor Agent. Collected from either Windows and Linux machines, depending on which extension is defined. - 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 streams: List of streams that this data source will be sent to. A stream indicates what schema will be used for this data and usually what table in Log diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/models/_monitor_management_client_enums.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/models/_monitor_management_client_enums.py index c9edaf22bd95..492d9777f2c0 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/models/_monitor_management_client_enums.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/models/_monitor_management_client_enums.py @@ -102,15 +102,21 @@ class KnownPublicNetworkAccessOptions(str, Enum, metaclass=CaseInsensitiveEnumMe class KnownSyslogDataSourceFacilityNames(str, Enum, metaclass=CaseInsensitiveEnumMeta): """KnownSyslogDataSourceFacilityNames.""" + ALERT = "alert" + AUDIT = "audit" AUTH = "auth" AUTHPRIV = "authpriv" + CLOCK = "clock" CRON = "cron" DAEMON = "daemon" + FTP = "ftp" KERN = "kern" LPR = "lpr" MAIL = "mail" MARK = "mark" NEWS = "news" + NOPRI = "nopri" + NTP = "ntp" SYSLOG = "syslog" USER = "user" UUCP = "uucp" diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/operations/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/operations/__init__.py index 842046dd09e5..fe2d89505e75 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/operations/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/operations/__init__.py @@ -5,13 +5,19 @@ # 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 ._data_collection_endpoints_operations import DataCollectionEndpointsOperations -from ._data_collection_rule_associations_operations import DataCollectionRuleAssociationsOperations -from ._data_collection_rules_operations import DataCollectionRulesOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._data_collection_endpoints_operations import DataCollectionEndpointsOperations # type: ignore +from ._data_collection_rule_associations_operations import DataCollectionRuleAssociationsOperations # type: ignore +from ._data_collection_rules_operations import DataCollectionRulesOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ @@ -19,5 +25,5 @@ "DataCollectionRuleAssociationsOperations", "DataCollectionRulesOperations", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/operations/_data_collection_endpoints_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/operations/_data_collection_endpoints_operations.py index 275196ff00b7..789e1da31d97 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/operations/_data_collection_endpoints_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/operations/_data_collection_endpoints_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload import urllib.parse @@ -19,16 +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, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -55,7 +58,7 @@ def build_list_by_resource_group_request(resource_group_name: str, subscription_ ), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -81,7 +84,7 @@ def build_list_by_subscription_request(subscription_id: str, **kwargs: Any) -> H "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -116,7 +119,7 @@ def build_get_request( ), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -152,7 +155,7 @@ def build_create_request( ), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -190,7 +193,7 @@ def build_update_request( ), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -227,7 +230,7 @@ def build_delete_request( ), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -256,6 +259,7 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list_by_resource_group( @@ -268,7 +272,6 @@ def list_by_resource_group( :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either DataCollectionEndpointResource or the result of cls(response) :rtype: @@ -278,10 +281,10 @@ def list_by_resource_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-04-01")) cls: ClsType[_models.DataCollectionEndpointResourceListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -292,16 +295,14 @@ 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_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -312,14 +313,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("DataCollectionEndpointResourceListResult", pipeline_response) @@ -329,11 +329,11 @@ def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -346,17 +346,12 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionEndpoints" - } - @distributed_trace def list_by_subscription(self, **kwargs: Any) -> Iterable["_models.DataCollectionEndpointResource"]: """Lists all data collection endpoints in the specified subscription. Lists all data collection endpoints in the specified subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either DataCollectionEndpointResource or the result of cls(response) :rtype: @@ -366,10 +361,10 @@ def list_by_subscription(self, **kwargs: Any) -> Iterable["_models.DataCollectio _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-04-01")) cls: ClsType[_models.DataCollectionEndpointResourceListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -380,15 +375,13 @@ def list_by_subscription(self, **kwargs: Any) -> Iterable["_models.DataCollectio def prepare_request(next_link=None): if not next_link: - request = build_list_by_subscription_request( + _request = build_list_by_subscription_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_subscription.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -399,14 +392,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("DataCollectionEndpointResourceListResult", pipeline_response) @@ -416,11 +408,11 @@ def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -433,10 +425,6 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_by_subscription.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/dataCollectionEndpoints" - } - @distributed_trace def get( self, resource_group_name: str, data_collection_endpoint_name: str, **kwargs: Any @@ -451,12 +439,11 @@ def get( :param data_collection_endpoint_name: The name of the data collection endpoint. The name is case insensitive. Required. :type data_collection_endpoint_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: DataCollectionEndpointResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_04_01.models.DataCollectionEndpointResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -467,24 +454,22 @@ def get( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-04-01")) cls: ClsType[_models.DataCollectionEndpointResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, data_collection_endpoint_name=data_collection_endpoint_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -494,16 +479,12 @@ def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponseCommonV2, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("DataCollectionEndpointResource", pipeline_response) + deserialized = self._deserialize("DataCollectionEndpointResource", 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.Insights/dataCollectionEndpoints/{dataCollectionEndpointName}" - } + return deserialized # type: ignore @overload def create( @@ -530,7 +511,6 @@ def create( :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: DataCollectionEndpointResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_04_01.models.DataCollectionEndpointResource :raises ~azure.core.exceptions.HttpResponseError: @@ -541,7 +521,7 @@ def create( self, resource_group_name: str, data_collection_endpoint_name: str, - body: Optional[IO] = None, + body: Optional[IO[bytes]] = None, *, content_type: str = "application/json", **kwargs: Any @@ -557,11 +537,10 @@ def create( case insensitive. Required. :type data_collection_endpoint_name: str :param body: The payload. Default value is None. - :type body: IO + :type body: 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: DataCollectionEndpointResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_04_01.models.DataCollectionEndpointResource :raises ~azure.core.exceptions.HttpResponseError: @@ -572,7 +551,7 @@ def create( self, resource_group_name: str, data_collection_endpoint_name: str, - body: Optional[Union[_models.DataCollectionEndpointResource, IO]] = None, + body: Optional[Union[_models.DataCollectionEndpointResource, IO[bytes]]] = None, **kwargs: Any ) -> _models.DataCollectionEndpointResource: """Creates or updates a data collection endpoint. @@ -585,18 +564,14 @@ def create( :param data_collection_endpoint_name: The name of the data collection endpoint. The name is case insensitive. Required. :type data_collection_endpoint_name: str - :param body: The payload. Is either a DataCollectionEndpointResource type or a IO type. Default - value is None. - :type body: ~azure.mgmt.monitor.v2021_04_01.models.DataCollectionEndpointResource or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + :param body: The payload. Is either a DataCollectionEndpointResource type or a IO[bytes] type. Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response + :type body: ~azure.mgmt.monitor.v2021_04_01.models.DataCollectionEndpointResource or IO[bytes] :return: DataCollectionEndpointResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_04_01.models.DataCollectionEndpointResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -607,14 +582,14 @@ def create( _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", "2021-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-04-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.DataCollectionEndpointResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(body, (IO, bytes)): + if isinstance(body, (IOBase, bytes)): _content = body else: if body is not None: @@ -622,7 +597,7 @@ def create( else: _json = None - request = build_create_request( + _request = build_create_request( resource_group_name=resource_group_name, data_collection_endpoint_name=data_collection_endpoint_name, subscription_id=self._config.subscription_id, @@ -630,16 +605,14 @@ def create( content_type=content_type, json=_json, content=_content, - template_url=self.create.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -649,21 +622,13 @@ def create( error = self._deserialize.failsafe_deserialize(_models.ErrorResponseCommonV2, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if response.status_code == 200: - deserialized = self._deserialize("DataCollectionEndpointResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("DataCollectionEndpointResource", pipeline_response) + deserialized = self._deserialize("DataCollectionEndpointResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionEndpoints/{dataCollectionEndpointName}" - } - @overload def update( self, @@ -689,7 +654,6 @@ def update( :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: DataCollectionEndpointResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_04_01.models.DataCollectionEndpointResource :raises ~azure.core.exceptions.HttpResponseError: @@ -700,7 +664,7 @@ def update( self, resource_group_name: str, data_collection_endpoint_name: str, - body: Optional[IO] = None, + body: Optional[IO[bytes]] = None, *, content_type: str = "application/json", **kwargs: Any @@ -716,11 +680,10 @@ def update( case insensitive. Required. :type data_collection_endpoint_name: str :param body: The payload. Default value is None. - :type body: IO + :type body: 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: DataCollectionEndpointResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_04_01.models.DataCollectionEndpointResource :raises ~azure.core.exceptions.HttpResponseError: @@ -731,7 +694,7 @@ def update( self, resource_group_name: str, data_collection_endpoint_name: str, - body: Optional[Union[_models.ResourceForUpdate, IO]] = None, + body: Optional[Union[_models.ResourceForUpdate, IO[bytes]]] = None, **kwargs: Any ) -> _models.DataCollectionEndpointResource: """Updates part of a data collection endpoint. @@ -744,18 +707,14 @@ def update( :param data_collection_endpoint_name: The name of the data collection endpoint. The name is case insensitive. Required. :type data_collection_endpoint_name: str - :param body: The payload. Is either a ResourceForUpdate type or a IO type. Default value is - None. - :type body: ~azure.mgmt.monitor.v2021_04_01.models.ResourceForUpdate 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 + :param body: The payload. Is either a ResourceForUpdate type or a IO[bytes] type. Default value + is None. + :type body: ~azure.mgmt.monitor.v2021_04_01.models.ResourceForUpdate or IO[bytes] :return: DataCollectionEndpointResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_04_01.models.DataCollectionEndpointResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -766,14 +725,14 @@ def update( _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", "2021-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-04-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.DataCollectionEndpointResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(body, (IO, bytes)): + if isinstance(body, (IOBase, bytes)): _content = body else: if body is not None: @@ -781,7 +740,7 @@ def update( else: _json = None - request = build_update_request( + _request = build_update_request( resource_group_name=resource_group_name, data_collection_endpoint_name=data_collection_endpoint_name, subscription_id=self._config.subscription_id, @@ -789,16 +748,14 @@ def update( 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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -808,16 +765,12 @@ def update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponseCommonV2, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("DataCollectionEndpointResource", pipeline_response) + deserialized = self._deserialize("DataCollectionEndpointResource", 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.Insights/dataCollectionEndpoints/{dataCollectionEndpointName}" - } + return deserialized # type: ignore @distributed_trace def delete( # pylint: disable=inconsistent-return-statements @@ -833,12 +786,11 @@ def delete( # pylint: disable=inconsistent-return-statements :param data_collection_endpoint_name: The name of the data collection endpoint. The name is case insensitive. Required. :type data_collection_endpoint_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, @@ -849,24 +801,22 @@ def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-04-01")) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, data_collection_endpoint_name=data_collection_endpoint_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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -877,8 +827,4 @@ def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionEndpoints/{dataCollectionEndpointName}" - } + return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/operations/_data_collection_rule_associations_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/operations/_data_collection_rule_associations_operations.py index 325f312c5f89..9d5ff1b119d1 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/operations/_data_collection_rule_associations_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/operations/_data_collection_rule_associations_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload import urllib.parse @@ -19,16 +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, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -49,7 +52,7 @@ def build_list_by_resource_request(resource_uri: str, **kwargs: Any) -> HttpRequ "resourceUri": _SERIALIZER.url("resource_uri", resource_uri, "str", skip_quote=True, min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -82,7 +85,7 @@ def build_list_by_rule_request( "dataCollectionRuleName": _SERIALIZER.url("data_collection_rule_name", data_collection_rule_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -109,7 +112,7 @@ def build_get_request(resource_uri: str, association_name: str, **kwargs: Any) - "associationName": _SERIALIZER.url("association_name", association_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -137,7 +140,7 @@ def build_create_request(resource_uri: str, association_name: str, **kwargs: Any "associationName": _SERIALIZER.url("association_name", association_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -166,7 +169,7 @@ def build_delete_request(resource_uri: str, association_name: str, **kwargs: Any "associationName": _SERIALIZER.url("association_name", association_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -195,18 +198,19 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list_by_resource( self, resource_uri: str, **kwargs: Any ) -> Iterable["_models.DataCollectionRuleAssociationProxyOnlyResource"]: + # pylint: disable=line-too-long """Lists associations for the specified resource. Lists associations for the specified resource. :param resource_uri: The identifier of the resource. Required. :type resource_uri: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either DataCollectionRuleAssociationProxyOnlyResource or the result of cls(response) :rtype: @@ -216,10 +220,10 @@ def list_by_resource( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-04-01")) cls: ClsType[_models.DataCollectionRuleAssociationProxyOnlyResourceListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -230,15 +234,13 @@ def list_by_resource( def prepare_request(next_link=None): if not next_link: - request = build_list_by_resource_request( + _request = build_list_by_resource_request( resource_uri=resource_uri, api_version=api_version, - template_url=self.list_by_resource.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -249,14 +251,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize( @@ -268,11 +269,11 @@ def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -285,12 +286,11 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_by_resource.metadata = {"url": "/{resourceUri}/providers/Microsoft.Insights/dataCollectionRuleAssociations"} - @distributed_trace def list_by_rule( self, resource_group_name: str, data_collection_rule_name: str, **kwargs: Any ) -> Iterable["_models.DataCollectionRuleAssociationProxyOnlyResource"]: + # pylint: disable=line-too-long """Lists associations for the specified data collection rule. Lists associations for the specified data collection rule. @@ -301,7 +301,6 @@ def list_by_rule( :param data_collection_rule_name: The name of the data collection rule. The name is case insensitive. Required. :type data_collection_rule_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either DataCollectionRuleAssociationProxyOnlyResource or the result of cls(response) :rtype: @@ -311,10 +310,10 @@ def list_by_rule( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-04-01")) cls: ClsType[_models.DataCollectionRuleAssociationProxyOnlyResourceListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -325,17 +324,15 @@ def list_by_rule( def prepare_request(next_link=None): if not next_link: - request = build_list_by_rule_request( + _request = build_list_by_rule_request( resource_group_name=resource_group_name, data_collection_rule_name=data_collection_rule_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_rule.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -346,14 +343,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize( @@ -365,11 +361,11 @@ def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -382,10 +378,6 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_by_rule.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionRules/{dataCollectionRuleName}/associations" - } - @distributed_trace def get( self, resource_uri: str, association_name: str, **kwargs: Any @@ -398,12 +390,11 @@ def get( :type resource_uri: str :param association_name: The name of the association. The name is case insensitive. Required. :type association_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: DataCollectionRuleAssociationProxyOnlyResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_04_01.models.DataCollectionRuleAssociationProxyOnlyResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -414,23 +405,21 @@ def get( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-04-01")) cls: ClsType[_models.DataCollectionRuleAssociationProxyOnlyResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_uri=resource_uri, association_name=association_name, api_version=api_version, - template_url=self.get.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -440,16 +429,14 @@ def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponseCommonV2, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("DataCollectionRuleAssociationProxyOnlyResource", pipeline_response) + deserialized = self._deserialize( + "DataCollectionRuleAssociationProxyOnlyResource", pipeline_response.http_response + ) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get.metadata = { - "url": "/{resourceUri}/providers/Microsoft.Insights/dataCollectionRuleAssociations/{associationName}" - } + return deserialized # type: ignore @overload def create( @@ -475,7 +462,6 @@ def create( :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: DataCollectionRuleAssociationProxyOnlyResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_04_01.models.DataCollectionRuleAssociationProxyOnlyResource :raises ~azure.core.exceptions.HttpResponseError: @@ -486,7 +472,7 @@ def create( self, resource_uri: str, association_name: str, - body: Optional[IO] = None, + body: Optional[IO[bytes]] = None, *, content_type: str = "application/json", **kwargs: Any @@ -500,11 +486,10 @@ def create( :param association_name: The name of the association. The name is case insensitive. Required. :type association_name: str :param body: The payload. Default value is None. - :type body: IO + :type body: 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: DataCollectionRuleAssociationProxyOnlyResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_04_01.models.DataCollectionRuleAssociationProxyOnlyResource :raises ~azure.core.exceptions.HttpResponseError: @@ -515,7 +500,7 @@ def create( self, resource_uri: str, association_name: str, - body: Optional[Union[_models.DataCollectionRuleAssociationProxyOnlyResource, IO]] = None, + body: Optional[Union[_models.DataCollectionRuleAssociationProxyOnlyResource, IO[bytes]]] = None, **kwargs: Any ) -> _models.DataCollectionRuleAssociationProxyOnlyResource: """Creates or updates an association. @@ -527,18 +512,15 @@ def create( :param association_name: The name of the association. The name is case insensitive. Required. :type association_name: str :param body: The payload. Is either a DataCollectionRuleAssociationProxyOnlyResource type or a - IO type. Default value is None. + IO[bytes] type. Default value is None. :type body: - ~azure.mgmt.monitor.v2021_04_01.models.DataCollectionRuleAssociationProxyOnlyResource 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 + ~azure.mgmt.monitor.v2021_04_01.models.DataCollectionRuleAssociationProxyOnlyResource or + IO[bytes] :return: DataCollectionRuleAssociationProxyOnlyResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_04_01.models.DataCollectionRuleAssociationProxyOnlyResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -549,14 +531,14 @@ def create( _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", "2021-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-04-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.DataCollectionRuleAssociationProxyOnlyResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(body, (IO, bytes)): + if isinstance(body, (IOBase, bytes)): _content = body else: if body is not None: @@ -564,23 +546,21 @@ def create( else: _json = None - request = build_create_request( + _request = build_create_request( resource_uri=resource_uri, association_name=association_name, api_version=api_version, content_type=content_type, json=_json, content=_content, - template_url=self.create.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -590,21 +570,15 @@ def create( error = self._deserialize.failsafe_deserialize(_models.ErrorResponseCommonV2, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if response.status_code == 200: - deserialized = self._deserialize("DataCollectionRuleAssociationProxyOnlyResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("DataCollectionRuleAssociationProxyOnlyResource", pipeline_response) + deserialized = self._deserialize( + "DataCollectionRuleAssociationProxyOnlyResource", pipeline_response.http_response + ) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create.metadata = { - "url": "/{resourceUri}/providers/Microsoft.Insights/dataCollectionRuleAssociations/{associationName}" - } - @distributed_trace def delete( # pylint: disable=inconsistent-return-statements self, resource_uri: str, association_name: str, **kwargs: Any @@ -617,12 +591,11 @@ def delete( # pylint: disable=inconsistent-return-statements :type resource_uri: str :param association_name: The name of the association. The name is case insensitive. Required. :type association_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, @@ -633,23 +606,21 @@ def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-04-01")) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_uri=resource_uri, association_name=association_name, api_version=api_version, - template_url=self.delete.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -660,8 +631,4 @@ def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/{resourceUri}/providers/Microsoft.Insights/dataCollectionRuleAssociations/{associationName}" - } + return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/operations/_data_collection_rules_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/operations/_data_collection_rules_operations.py index 0442719232c5..0da68d0a198c 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/operations/_data_collection_rules_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/operations/_data_collection_rules_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload import urllib.parse @@ -19,16 +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, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -55,7 +58,7 @@ def build_list_by_resource_group_request(resource_group_name: str, subscription_ ), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -81,7 +84,7 @@ def build_list_by_subscription_request(subscription_id: str, **kwargs: Any) -> H "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -114,7 +117,7 @@ def build_get_request( "dataCollectionRuleName": _SERIALIZER.url("data_collection_rule_name", data_collection_rule_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -148,7 +151,7 @@ def build_create_request( "dataCollectionRuleName": _SERIALIZER.url("data_collection_rule_name", data_collection_rule_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -184,7 +187,7 @@ def build_update_request( "dataCollectionRuleName": _SERIALIZER.url("data_collection_rule_name", data_collection_rule_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -219,7 +222,7 @@ def build_delete_request( "dataCollectionRuleName": _SERIALIZER.url("data_collection_rule_name", data_collection_rule_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -248,6 +251,7 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list_by_resource_group( @@ -260,7 +264,6 @@ def list_by_resource_group( :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either DataCollectionRuleResource or the result of cls(response) :rtype: @@ -270,10 +273,10 @@ def list_by_resource_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-04-01")) cls: ClsType[_models.DataCollectionRuleResourceListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -284,16 +287,14 @@ 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_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -304,14 +305,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("DataCollectionRuleResourceListResult", pipeline_response) @@ -321,11 +321,11 @@ def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -338,17 +338,12 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionRules" - } - @distributed_trace def list_by_subscription(self, **kwargs: Any) -> Iterable["_models.DataCollectionRuleResource"]: """Lists all data collection rules in the specified subscription. Lists all data collection rules in the specified subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either DataCollectionRuleResource or the result of cls(response) :rtype: @@ -358,10 +353,10 @@ def list_by_subscription(self, **kwargs: Any) -> Iterable["_models.DataCollectio _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-04-01")) cls: ClsType[_models.DataCollectionRuleResourceListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -372,15 +367,13 @@ def list_by_subscription(self, **kwargs: Any) -> Iterable["_models.DataCollectio def prepare_request(next_link=None): if not next_link: - request = build_list_by_subscription_request( + _request = build_list_by_subscription_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_subscription.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -391,14 +384,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("DataCollectionRuleResourceListResult", pipeline_response) @@ -408,11 +400,11 @@ def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -425,10 +417,6 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_by_subscription.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/dataCollectionRules" - } - @distributed_trace def get( self, resource_group_name: str, data_collection_rule_name: str, **kwargs: Any @@ -443,12 +431,11 @@ def get( :param data_collection_rule_name: The name of the data collection rule. The name is case insensitive. Required. :type data_collection_rule_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: DataCollectionRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_04_01.models.DataCollectionRuleResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -459,24 +446,22 @@ def get( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-04-01")) cls: ClsType[_models.DataCollectionRuleResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, data_collection_rule_name=data_collection_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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -486,16 +471,12 @@ def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponseCommonV2, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("DataCollectionRuleResource", pipeline_response) + deserialized = self._deserialize("DataCollectionRuleResource", 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.Insights/dataCollectionRules/{dataCollectionRuleName}" - } + return deserialized # type: ignore @overload def create( @@ -522,7 +503,6 @@ def create( :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: DataCollectionRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_04_01.models.DataCollectionRuleResource :raises ~azure.core.exceptions.HttpResponseError: @@ -533,7 +513,7 @@ def create( self, resource_group_name: str, data_collection_rule_name: str, - body: Optional[IO] = None, + body: Optional[IO[bytes]] = None, *, content_type: str = "application/json", **kwargs: Any @@ -549,11 +529,10 @@ def create( insensitive. Required. :type data_collection_rule_name: str :param body: The payload. Default value is None. - :type body: IO + :type body: 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: DataCollectionRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_04_01.models.DataCollectionRuleResource :raises ~azure.core.exceptions.HttpResponseError: @@ -564,7 +543,7 @@ def create( self, resource_group_name: str, data_collection_rule_name: str, - body: Optional[Union[_models.DataCollectionRuleResource, IO]] = None, + body: Optional[Union[_models.DataCollectionRuleResource, IO[bytes]]] = None, **kwargs: Any ) -> _models.DataCollectionRuleResource: """Creates or updates a data collection rule. @@ -577,18 +556,14 @@ def create( :param data_collection_rule_name: The name of the data collection rule. The name is case insensitive. Required. :type data_collection_rule_name: str - :param body: The payload. Is either a DataCollectionRuleResource type or a IO type. Default - value is None. - :type body: ~azure.mgmt.monitor.v2021_04_01.models.DataCollectionRuleResource or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + :param body: The payload. Is either a DataCollectionRuleResource type or a IO[bytes] type. Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response + :type body: ~azure.mgmt.monitor.v2021_04_01.models.DataCollectionRuleResource or IO[bytes] :return: DataCollectionRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_04_01.models.DataCollectionRuleResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -599,14 +574,14 @@ def create( _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", "2021-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-04-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.DataCollectionRuleResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(body, (IO, bytes)): + if isinstance(body, (IOBase, bytes)): _content = body else: if body is not None: @@ -614,7 +589,7 @@ def create( else: _json = None - request = build_create_request( + _request = build_create_request( resource_group_name=resource_group_name, data_collection_rule_name=data_collection_rule_name, subscription_id=self._config.subscription_id, @@ -622,16 +597,14 @@ def create( content_type=content_type, json=_json, content=_content, - template_url=self.create.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -641,21 +614,13 @@ def create( error = self._deserialize.failsafe_deserialize(_models.ErrorResponseCommonV2, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if response.status_code == 200: - deserialized = self._deserialize("DataCollectionRuleResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("DataCollectionRuleResource", pipeline_response) + deserialized = self._deserialize("DataCollectionRuleResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionRules/{dataCollectionRuleName}" - } - @overload def update( self, @@ -681,7 +646,6 @@ def update( :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: DataCollectionRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_04_01.models.DataCollectionRuleResource :raises ~azure.core.exceptions.HttpResponseError: @@ -692,7 +656,7 @@ def update( self, resource_group_name: str, data_collection_rule_name: str, - body: Optional[IO] = None, + body: Optional[IO[bytes]] = None, *, content_type: str = "application/json", **kwargs: Any @@ -708,11 +672,10 @@ def update( insensitive. Required. :type data_collection_rule_name: str :param body: The payload. Default value is None. - :type body: IO + :type body: 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: DataCollectionRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_04_01.models.DataCollectionRuleResource :raises ~azure.core.exceptions.HttpResponseError: @@ -723,7 +686,7 @@ def update( self, resource_group_name: str, data_collection_rule_name: str, - body: Optional[Union[_models.ResourceForUpdate, IO]] = None, + body: Optional[Union[_models.ResourceForUpdate, IO[bytes]]] = None, **kwargs: Any ) -> _models.DataCollectionRuleResource: """Updates part of a data collection rule. @@ -736,18 +699,14 @@ def update( :param data_collection_rule_name: The name of the data collection rule. The name is case insensitive. Required. :type data_collection_rule_name: str - :param body: The payload. Is either a ResourceForUpdate type or a IO type. Default value is - None. - :type body: ~azure.mgmt.monitor.v2021_04_01.models.ResourceForUpdate 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 + :param body: The payload. Is either a ResourceForUpdate type or a IO[bytes] type. Default value + is None. + :type body: ~azure.mgmt.monitor.v2021_04_01.models.ResourceForUpdate or IO[bytes] :return: DataCollectionRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_04_01.models.DataCollectionRuleResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -758,14 +717,14 @@ def update( _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", "2021-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-04-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.DataCollectionRuleResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(body, (IO, bytes)): + if isinstance(body, (IOBase, bytes)): _content = body else: if body is not None: @@ -773,7 +732,7 @@ def update( else: _json = None - request = build_update_request( + _request = build_update_request( resource_group_name=resource_group_name, data_collection_rule_name=data_collection_rule_name, subscription_id=self._config.subscription_id, @@ -781,16 +740,14 @@ def update( 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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -800,16 +757,12 @@ def update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponseCommonV2, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("DataCollectionRuleResource", pipeline_response) + deserialized = self._deserialize("DataCollectionRuleResource", 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.Insights/dataCollectionRules/{dataCollectionRuleName}" - } + return deserialized # type: ignore @distributed_trace def delete( # pylint: disable=inconsistent-return-statements @@ -825,12 +778,11 @@ def delete( # pylint: disable=inconsistent-return-statements :param data_collection_rule_name: The name of the data collection rule. The name is case insensitive. Required. :type data_collection_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, @@ -841,24 +793,22 @@ def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-04-01")) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, data_collection_rule_name=data_collection_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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -869,8 +819,4 @@ def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionRules/{dataCollectionRuleName}" - } + return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/__init__.py index 2c7733bfd566..42cc62301757 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/__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 ._monitor_management_client import MonitorManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._monitor_management_client import MonitorManagementClient # type: ignore from ._version import VERSION __version__ = VERSION try: from ._patch import __all__ as _patch_all - from ._patch import * # 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__ = [ "MonitorManagementClient", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/_configuration.py index 7f084d2540de..650e1f738788 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/_configuration.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/_configuration.py @@ -8,18 +8,16 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy from ._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MonitorManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class MonitorManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for MonitorManagementClient. Note that all parameters used to create this instance are saved as instance @@ -35,7 +33,6 @@ class MonitorManagementClientConfiguration(Configuration): # pylint: disable=to """ def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: - super(MonitorManagementClientConfiguration, self).__init__(**kwargs) api_version: str = kwargs.pop("api_version", "2021-05-01") if credential is None: @@ -48,6 +45,7 @@ def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-monitor/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -56,9 +54,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.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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/_metadata.json b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/_metadata.json index 61e2ad24f17a..43f6c74e2100 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/_metadata.json +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/_metadata.json @@ -8,10 +8,10 @@ "host_value": "\"https://management.azure.com\"", "parameterized_host_template": null, "azure_arm": true, - "has_lro_operations": false, + "has_public_lro_operations": false, "client_side_validation": false, - "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"sdkcore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMAutoResourceProviderRegistrationPolicy\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}, \"stdlib\": {\"typing_extensions\": [\"Self\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"sdkcore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"AsyncARMAutoResourceProviderRegistrationPolicy\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}, \"stdlib\": {\"typing_extensions\": [\"Self\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "global_parameters": { "sync": { @@ -101,8 +101,8 @@ "credential_scopes": ["https://management.azure.com/.default"], "credential_call_sync": "ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", "credential_call_async": "AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", - "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "sync_imports": "{\"regular\": {\"sdkcore\": {\"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"regular\": {\"sdkcore\": {\"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "operation_groups": { "metrics": "MetricsOperations", diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/_monitor_management_client.py index 448ef59afa73..46712fae34a2 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/_monitor_management_client.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/_monitor_management_client.py @@ -8,9 +8,12 @@ from copy import deepcopy from typing import Any, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient +from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy from . import models as _models from .._serialization import Deserializer, Serializer @@ -18,11 +21,10 @@ from .operations import MetricDefinitionsOperations, MetricsOperations, Operations if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MonitorManagementClient: # pylint: disable=client-accepts-api-version-keyword +class MonitorManagementClient: """Monitor Management Client. :ivar metrics: MetricsOperations operations @@ -53,19 +55,37 @@ def __init__( self._config = MonitorManagementClientConfiguration( credential=credential, subscription_id=subscription_id, **kwargs ) - self._client: ARMPipelineClient = ARMPipelineClient(base_url=base_url, config=self._config, **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), + 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=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.metrics = MetricsOperations(self._client, self._config, self._serialize, self._deserialize) + self.metrics = MetricsOperations(self._client, self._config, self._serialize, self._deserialize, "2021-05-01") self.metric_definitions = MetricDefinitionsOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2021-05-01" ) - self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) + self.operations = Operations(self._client, self._config, self._serialize, self._deserialize, "2021-05-01") - 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 @@ -85,12 +105,12 @@ 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) -> None: self._client.close() - def __enter__(self) -> "MonitorManagementClient": + def __enter__(self) -> Self: self._client.__enter__() return self diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/_vendor.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/_vendor.py deleted file mode 100644 index bd0df84f5319..000000000000 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/_vendor.py +++ /dev/null @@ -1,30 +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 typing import List, cast - -from azure.core.pipeline.transport import HttpRequest - - -def _convert_request(request, files=None): - data = request.content if not files else None - request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) - if files: - request.set_formdata_body(files) - return request - - -def _format_url_section(template, **kwargs): - components = template.split("/") - while components: - try: - return template.format(**kwargs) - except KeyError as key: - # Need the cast, as for some reasons "split" is typed as list[str | Any] - formatted_components = cast(List[str], template.split("/")) - components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] - template = "/".join(components) diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/_version.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/_version.py index 394ee7c0c03c..e5754a47ce68 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/_version.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "6.0.2" +VERSION = "1.0.0b1" diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/aio/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/aio/__init__.py index 2c151bb41c19..3df30ff42149 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/aio/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/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 ._monitor_management_client import MonitorManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._monitor_management_client import MonitorManagementClient # type: ignore try: from ._patch import __all__ as _patch_all - from ._patch import * # 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__ = [ "MonitorManagementClient", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/aio/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/aio/_configuration.py index f210214ef4bf..e3720b749123 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/aio/_configuration.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/aio/_configuration.py @@ -8,18 +8,16 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy from .._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MonitorManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class MonitorManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for MonitorManagementClient. Note that all parameters used to create this instance are saved as instance @@ -35,7 +33,6 @@ class MonitorManagementClientConfiguration(Configuration): # pylint: disable=to """ def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: - super(MonitorManagementClientConfiguration, self).__init__(**kwargs) api_version: str = kwargs.pop("api_version", "2021-05-01") if credential is None: @@ -48,6 +45,7 @@ def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **k self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-monitor/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -56,9 +54,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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/aio/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/aio/_monitor_management_client.py index 2a774106d536..b20d14cfd38f 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/aio/_monitor_management_client.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/aio/_monitor_management_client.py @@ -8,9 +8,12 @@ from copy import deepcopy from typing import Any, Awaitable, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient +from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy from .. import models as _models from ..._serialization import Deserializer, Serializer @@ -18,11 +21,10 @@ from .operations import MetricDefinitionsOperations, MetricsOperations, Operations if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MonitorManagementClient: # pylint: disable=client-accepts-api-version-keyword +class MonitorManagementClient: """Monitor Management Client. :ivar metrics: MetricsOperations operations @@ -53,19 +55,39 @@ def __init__( self._config = MonitorManagementClientConfiguration( credential=credential, subscription_id=subscription_id, **kwargs ) - self._client: AsyncARMPipelineClient = AsyncARMPipelineClient(base_url=base_url, config=self._config, **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=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.metrics = MetricsOperations(self._client, self._config, self._serialize, self._deserialize) + self.metrics = MetricsOperations(self._client, self._config, self._serialize, self._deserialize, "2021-05-01") self.metric_definitions = MetricDefinitionsOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2021-05-01" ) - self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) + self.operations = Operations(self._client, self._config, self._serialize, self._deserialize, "2021-05-01") - 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 @@ -85,12 +107,12 @@ 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) -> "MonitorManagementClient": + async def __aenter__(self) -> Self: await self._client.__aenter__() return self diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/aio/operations/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/aio/operations/__init__.py index ca1fe1731e6b..691e9ca92fbe 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/aio/operations/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/aio/operations/__init__.py @@ -5,13 +5,19 @@ # 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 ._metrics_operations import MetricsOperations -from ._metric_definitions_operations import MetricDefinitionsOperations -from ._operations import Operations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._metrics_operations import MetricsOperations # type: ignore +from ._metric_definitions_operations import MetricDefinitionsOperations # type: ignore +from ._operations import Operations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ @@ -19,5 +25,5 @@ "MetricDefinitionsOperations", "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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/aio/operations/_metric_definitions_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/aio/operations/_metric_definitions_operations.py index 3979d162f2f3..6230ad1dcba7 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/aio/operations/_metric_definitions_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/aio/operations/_metric_definitions_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,7 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar import urllib.parse @@ -19,16 +19,18 @@ 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 ...operations._metric_definitions_operations import build_list_at_subscription_scope_request, build_list_request +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -51,11 +53,13 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list_at_subscription_scope( self, region: str, metricnamespace: Optional[str] = None, **kwargs: Any ) -> AsyncIterable["_models.SubscriptionScopeMetricDefinition"]: + # pylint: disable=line-too-long """Lists the metric definitions for the subscription. :param region: The region where the metrics you want reside. Required. @@ -63,7 +67,6 @@ def list_at_subscription_scope( :param metricnamespace: Metric namespace where the metrics you want reside. Default value is None. :type metricnamespace: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either SubscriptionScopeMetricDefinition or the result of cls(response) :rtype: @@ -73,10 +76,10 @@ def list_at_subscription_scope( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-05-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-05-01")) cls: ClsType[_models.SubscriptionScopeMetricDefinitionCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -87,17 +90,15 @@ def list_at_subscription_scope( def prepare_request(next_link=None): if not next_link: - request = build_list_at_subscription_scope_request( + _request = build_list_at_subscription_scope_request( subscription_id=self._config.subscription_id, region=region, metricnamespace=metricnamespace, api_version=api_version, - template_url=self.list_at_subscription_scope.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -108,14 +109,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("SubscriptionScopeMetricDefinitionCollection", pipeline_response) @@ -125,11 +125,11 @@ async def extract_data(pipeline_response): return None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -142,10 +142,6 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_at_subscription_scope.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/metricDefinitions" - } - @distributed_trace def list( self, resource_uri: str, metricnamespace: Optional[str] = None, **kwargs: Any @@ -157,7 +153,6 @@ def list( :param metricnamespace: Metric namespace where the metrics you want reside. Default value is None. :type metricnamespace: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either MetricDefinition or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.monitor.v2021_05_01.models.MetricDefinition] @@ -166,10 +161,10 @@ def list( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-05-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-05-01")) cls: ClsType[_models.MetricDefinitionCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -180,16 +175,14 @@ def list( def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( resource_uri=resource_uri, metricnamespace=metricnamespace, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -200,14 +193,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("MetricDefinitionCollection", pipeline_response) @@ -217,11 +209,11 @@ async def extract_data(pipeline_response): return None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -233,5 +225,3 @@ async def get_next(next_link=None): return pipeline_response return AsyncItemPaged(get_next, extract_data) - - list.metadata = {"url": "/{resourceUri}/providers/Microsoft.Insights/metricDefinitions"} diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/aio/operations/_metrics_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/aio/operations/_metrics_operations.py index c91e57bd95da..565d66e8d692 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/aio/operations/_metrics_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/aio/operations/_metrics_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +6,8 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- import datetime +from io import IOBase +import sys from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload from azure.core.exceptions import ( @@ -18,20 +19,22 @@ 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_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._metrics_operations import ( build_list_at_subscription_scope_post_request, build_list_at_subscription_scope_request, build_list_request, ) +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -54,6 +57,7 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace_async async def list_at_subscription_scope( @@ -97,13 +101,13 @@ async def list_at_subscription_scope( :type orderby: str :param filter: The **$filter** is used to reduce the set of metric data returned.:code:`
`Example::code:`
`Metric contains metadata A, B and C.:code:`
`- - Return all time series of C where A = a1 and B = b1 or b2:code:`
`\ **$filter=A eq ‘a1’ and - B eq ‘b1’ or B eq ‘b2’ and C eq ‘*’**\ :code:`
`- Invalid variant::code:`
`\ **$filter=A - eq ‘a1’ and B eq ‘b1’ and C eq ‘*’ or B = ‘b2’**\ :code:`
`This is invalid because the - logical or operator cannot separate two different metadata names.:code:`
`- Return all time - series where A = a1, B = b1 and C = c1::code:`
`\ **$filter=A eq ‘a1’ and B eq ‘b1’ and C eq - ‘c1’**\ :code:`
`- Return all time series where A = a1:code:`
`\ **$filter=A eq ‘a1’ and - B eq ‘\ *’ and C eq ‘*\ ’**. Default value is None. + Return all time series of C where A = a1 and B = b1 or b2:code:`
`\\ **$filter=A eq ‘a1’ and + B eq ‘b1’ or B eq ‘b2’ and C eq ‘*’**\\ :code:`
`- Invalid variant::code:`
`\\ + **$filter=A eq ‘a1’ and B eq ‘b1’ and C eq ‘*’ or B = ‘b2’**\\ :code:`
`This is invalid + because the logical or operator cannot separate two different metadata names.:code:`
`- + Return all time series where A = a1, B = b1 and C = c1::code:`
`\\ **$filter=A eq ‘a1’ and B + eq ‘b1’ and C eq ‘c1’**\\ :code:`
`- Return all time series where A = a1:code:`
`\\ + **$filter=A eq ‘a1’ and B eq ‘\\ *’ and C eq ‘*\\ ’**. Default value is None. :type filter: str :param result_type: Reduces the set of data collected. The syntax allowed depends on the operation. See the operation's description for details. Known values are: "Data" and @@ -121,12 +125,11 @@ async def list_at_subscription_scope( When set to true, an error is returned for invalid filter parameters. Defaults to true. Default value is None. :type validate_dimensions: bool - :keyword callable cls: A custom type or function that will be passed the direct response :return: SubscriptionScopeMetricResponse or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_05_01.models.SubscriptionScopeMetricResponse :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -137,10 +140,10 @@ async def list_at_subscription_scope( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-05-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-05-01")) cls: ClsType[_models.SubscriptionScopeMetricResponse] = kwargs.pop("cls", None) - request = build_list_at_subscription_scope_request( + _request = build_list_at_subscription_scope_request( subscription_id=self._config.subscription_id, region=region, timespan=timespan, @@ -155,16 +158,14 @@ async def list_at_subscription_scope( auto_adjust_timegrain=auto_adjust_timegrain, validate_dimensions=validate_dimensions, api_version=api_version, - template_url=self.list_at_subscription_scope.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -174,16 +175,12 @@ async def list_at_subscription_scope( error = self._deserialize.failsafe_deserialize(_models.ErrorContract, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("SubscriptionScopeMetricResponse", pipeline_response) + deserialized = self._deserialize("SubscriptionScopeMetricResponse", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - list_at_subscription_scope.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/metrics" - } + return deserialized # type: ignore @overload async def list_at_subscription_scope_post( @@ -231,13 +228,13 @@ async def list_at_subscription_scope_post( :type orderby: str :param filter: The **$filter** is used to reduce the set of metric data returned.:code:`
`Example::code:`
`Metric contains metadata A, B and C.:code:`
`- - Return all time series of C where A = a1 and B = b1 or b2:code:`
`\ **$filter=A eq ‘a1’ and - B eq ‘b1’ or B eq ‘b2’ and C eq ‘*’**\ :code:`
`- Invalid variant::code:`
`\ **$filter=A - eq ‘a1’ and B eq ‘b1’ and C eq ‘*’ or B = ‘b2’**\ :code:`
`This is invalid because the - logical or operator cannot separate two different metadata names.:code:`
`- Return all time - series where A = a1, B = b1 and C = c1::code:`
`\ **$filter=A eq ‘a1’ and B eq ‘b1’ and C eq - ‘c1’**\ :code:`
`- Return all time series where A = a1:code:`
`\ **$filter=A eq ‘a1’ and - B eq ‘\ *’ and C eq ‘*\ ’**. Default value is None. + Return all time series of C where A = a1 and B = b1 or b2:code:`
`\\ **$filter=A eq ‘a1’ and + B eq ‘b1’ or B eq ‘b2’ and C eq ‘*’**\\ :code:`
`- Invalid variant::code:`
`\\ + **$filter=A eq ‘a1’ and B eq ‘b1’ and C eq ‘*’ or B = ‘b2’**\\ :code:`
`This is invalid + because the logical or operator cannot separate two different metadata names.:code:`
`- + Return all time series where A = a1, B = b1 and C = c1::code:`
`\\ **$filter=A eq ‘a1’ and B + eq ‘b1’ and C eq ‘c1’**\\ :code:`
`- Return all time series where A = a1:code:`
`\\ + **$filter=A eq ‘a1’ and B eq ‘\\ *’ and C eq ‘*\\ ’**. Default value is None. :type filter: str :param result_type: Reduces the set of data collected. The syntax allowed depends on the operation. See the operation's description for details. Known values are: "Data" and @@ -261,7 +258,6 @@ async def list_at_subscription_scope_post( :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: SubscriptionScopeMetricResponse or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_05_01.models.SubscriptionScopeMetricResponse :raises ~azure.core.exceptions.HttpResponseError: @@ -282,7 +278,7 @@ async def list_at_subscription_scope_post( metricnamespace: Optional[str] = None, auto_adjust_timegrain: Optional[bool] = None, validate_dimensions: Optional[bool] = None, - body: Optional[IO] = None, + body: Optional[IO[bytes]] = None, *, content_type: str = "application/json", **kwargs: Any @@ -313,13 +309,13 @@ async def list_at_subscription_scope_post( :type orderby: str :param filter: The **$filter** is used to reduce the set of metric data returned.:code:`
`Example::code:`
`Metric contains metadata A, B and C.:code:`
`- - Return all time series of C where A = a1 and B = b1 or b2:code:`
`\ **$filter=A eq ‘a1’ and - B eq ‘b1’ or B eq ‘b2’ and C eq ‘*’**\ :code:`
`- Invalid variant::code:`
`\ **$filter=A - eq ‘a1’ and B eq ‘b1’ and C eq ‘*’ or B = ‘b2’**\ :code:`
`This is invalid because the - logical or operator cannot separate two different metadata names.:code:`
`- Return all time - series where A = a1, B = b1 and C = c1::code:`
`\ **$filter=A eq ‘a1’ and B eq ‘b1’ and C eq - ‘c1’**\ :code:`
`- Return all time series where A = a1:code:`
`\ **$filter=A eq ‘a1’ and - B eq ‘\ *’ and C eq ‘*\ ’**. Default value is None. + Return all time series of C where A = a1 and B = b1 or b2:code:`
`\\ **$filter=A eq ‘a1’ and + B eq ‘b1’ or B eq ‘b2’ and C eq ‘*’**\\ :code:`
`- Invalid variant::code:`
`\\ + **$filter=A eq ‘a1’ and B eq ‘b1’ and C eq ‘*’ or B = ‘b2’**\\ :code:`
`This is invalid + because the logical or operator cannot separate two different metadata names.:code:`
`- + Return all time series where A = a1, B = b1 and C = c1::code:`
`\\ **$filter=A eq ‘a1’ and B + eq ‘b1’ and C eq ‘c1’**\\ :code:`
`- Return all time series where A = a1:code:`
`\\ + **$filter=A eq ‘a1’ and B eq ‘\\ *’ and C eq ‘*\\ ’**. Default value is None. :type filter: str :param result_type: Reduces the set of data collected. The syntax allowed depends on the operation. See the operation's description for details. Known values are: "Data" and @@ -338,11 +334,10 @@ async def list_at_subscription_scope_post( value is None. :type validate_dimensions: bool :param body: Parameters serialized in the body. Default value is None. - :type body: IO + :type body: 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: SubscriptionScopeMetricResponse or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_05_01.models.SubscriptionScopeMetricResponse :raises ~azure.core.exceptions.HttpResponseError: @@ -363,7 +358,7 @@ async def list_at_subscription_scope_post( metricnamespace: Optional[str] = None, auto_adjust_timegrain: Optional[bool] = None, validate_dimensions: Optional[bool] = None, - body: Optional[Union[_models.SubscriptionScopeMetricsRequestBodyParameters, IO]] = None, + body: Optional[Union[_models.SubscriptionScopeMetricsRequestBodyParameters, IO[bytes]]] = None, **kwargs: Any ) -> _models.SubscriptionScopeMetricResponse: """**Lists the metric data for a subscription**. Parameters can be specified on either query @@ -392,13 +387,13 @@ async def list_at_subscription_scope_post( :type orderby: str :param filter: The **$filter** is used to reduce the set of metric data returned.:code:`
`Example::code:`
`Metric contains metadata A, B and C.:code:`
`- - Return all time series of C where A = a1 and B = b1 or b2:code:`
`\ **$filter=A eq ‘a1’ and - B eq ‘b1’ or B eq ‘b2’ and C eq ‘*’**\ :code:`
`- Invalid variant::code:`
`\ **$filter=A - eq ‘a1’ and B eq ‘b1’ and C eq ‘*’ or B = ‘b2’**\ :code:`
`This is invalid because the - logical or operator cannot separate two different metadata names.:code:`
`- Return all time - series where A = a1, B = b1 and C = c1::code:`
`\ **$filter=A eq ‘a1’ and B eq ‘b1’ and C eq - ‘c1’**\ :code:`
`- Return all time series where A = a1:code:`
`\ **$filter=A eq ‘a1’ and - B eq ‘\ *’ and C eq ‘*\ ’**. Default value is None. + Return all time series of C where A = a1 and B = b1 or b2:code:`
`\\ **$filter=A eq ‘a1’ and + B eq ‘b1’ or B eq ‘b2’ and C eq ‘*’**\\ :code:`
`- Invalid variant::code:`
`\\ + **$filter=A eq ‘a1’ and B eq ‘b1’ and C eq ‘*’ or B = ‘b2’**\\ :code:`
`This is invalid + because the logical or operator cannot separate two different metadata names.:code:`
`- + Return all time series where A = a1, B = b1 and C = c1::code:`
`\\ **$filter=A eq ‘a1’ and B + eq ‘b1’ and C eq ‘c1’**\\ :code:`
`- Return all time series where A = a1:code:`
`\\ + **$filter=A eq ‘a1’ and B eq ‘\\ *’ and C eq ‘*\\ ’**. Default value is None. :type filter: str :param result_type: Reduces the set of data collected. The syntax allowed depends on the operation. See the operation's description for details. Known values are: "Data" and @@ -417,18 +412,15 @@ async def list_at_subscription_scope_post( value is None. :type validate_dimensions: bool :param body: Parameters serialized in the body. Is either a - SubscriptionScopeMetricsRequestBodyParameters type or a IO type. Default value is None. + SubscriptionScopeMetricsRequestBodyParameters type or a IO[bytes] type. Default value is None. :type body: - ~azure.mgmt.monitor.v2021_05_01.models.SubscriptionScopeMetricsRequestBodyParameters 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 + ~azure.mgmt.monitor.v2021_05_01.models.SubscriptionScopeMetricsRequestBodyParameters or + IO[bytes] :return: SubscriptionScopeMetricResponse or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_05_01.models.SubscriptionScopeMetricResponse :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -439,14 +431,14 @@ async def list_at_subscription_scope_post( _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", "2021-05-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-05-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.SubscriptionScopeMetricResponse] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(body, (IO, bytes)): + if isinstance(body, (IOBase, bytes)): _content = body else: if body is not None: @@ -454,7 +446,7 @@ async def list_at_subscription_scope_post( else: _json = None - request = build_list_at_subscription_scope_post_request( + _request = build_list_at_subscription_scope_post_request( subscription_id=self._config.subscription_id, region=region, timespan=timespan, @@ -472,16 +464,14 @@ async def list_at_subscription_scope_post( content_type=content_type, json=_json, content=_content, - template_url=self.list_at_subscription_scope_post.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -491,16 +481,12 @@ async def list_at_subscription_scope_post( error = self._deserialize.failsafe_deserialize(_models.ErrorContract, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("SubscriptionScopeMetricResponse", pipeline_response) + deserialized = self._deserialize("SubscriptionScopeMetricResponse", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - list_at_subscription_scope_post.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/metrics" - } + return deserialized # type: ignore @distributed_trace_async async def list( @@ -544,13 +530,13 @@ async def list( :type orderby: str :param filter: The **$filter** is used to reduce the set of metric data returned.:code:`
`Example::code:`
`Metric contains metadata A, B and C.:code:`
`- - Return all time series of C where A = a1 and B = b1 or b2:code:`
`\ **$filter=A eq ‘a1’ and - B eq ‘b1’ or B eq ‘b2’ and C eq ‘*’**\ :code:`
`- Invalid variant::code:`
`\ **$filter=A - eq ‘a1’ and B eq ‘b1’ and C eq ‘*’ or B = ‘b2’**\ :code:`
`This is invalid because the - logical or operator cannot separate two different metadata names.:code:`
`- Return all time - series where A = a1, B = b1 and C = c1::code:`
`\ **$filter=A eq ‘a1’ and B eq ‘b1’ and C eq - ‘c1’**\ :code:`
`- Return all time series where A = a1:code:`
`\ **$filter=A eq ‘a1’ and - B eq ‘\ *’ and C eq ‘*\ ’**. Default value is None. + Return all time series of C where A = a1 and B = b1 or b2:code:`
`\\ **$filter=A eq ‘a1’ and + B eq ‘b1’ or B eq ‘b2’ and C eq ‘*’**\\ :code:`
`- Invalid variant::code:`
`\\ + **$filter=A eq ‘a1’ and B eq ‘b1’ and C eq ‘*’ or B = ‘b2’**\\ :code:`
`This is invalid + because the logical or operator cannot separate two different metadata names.:code:`
`- + Return all time series where A = a1, B = b1 and C = c1::code:`
`\\ **$filter=A eq ‘a1’ and B + eq ‘b1’ and C eq ‘c1’**\\ :code:`
`- Return all time series where A = a1:code:`
`\\ + **$filter=A eq ‘a1’ and B eq ‘\\ *’ and C eq ‘*\\ ’**. Default value is None. :type filter: str :param result_type: Reduces the set of data collected. The syntax allowed depends on the operation. See the operation's description for details. Known values are: "Data" and @@ -568,12 +554,11 @@ async def list( When set to true, an error is returned for invalid filter parameters. Defaults to true. Default value is None. :type validate_dimensions: bool - :keyword callable cls: A custom type or function that will be passed the direct response :return: Response or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_05_01.models.Response :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -584,10 +569,10 @@ async def list( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-05-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-05-01")) cls: ClsType[_models.Response] = kwargs.pop("cls", None) - request = build_list_request( + _request = build_list_request( resource_uri=resource_uri, timespan=timespan, interval=interval, @@ -601,16 +586,14 @@ async def list( auto_adjust_timegrain=auto_adjust_timegrain, validate_dimensions=validate_dimensions, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -620,11 +603,9 @@ async def list( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("Response", pipeline_response) + deserialized = self._deserialize("Response", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - list.metadata = {"url": "/{resourceUri}/providers/Microsoft.Insights/metrics"} + return deserialized # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/aio/operations/_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/aio/operations/_operations.py index 81c47663e491..c0a42b00828d 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/aio/operations/_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/aio/operations/_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,7 @@ # 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 ( @@ -17,16 +17,18 @@ 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_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._operations import build_list_request +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -49,17 +51,17 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace_async async def list(self, **kwargs: Any) -> _models.OperationListResult: """Lists all of the available operations from Microsoft.Insights provider. - :keyword callable cls: A custom type or function that will be passed the direct response :return: OperationListResult or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_05_01.models.OperationListResult :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -70,21 +72,19 @@ async def list(self, **kwargs: Any) -> _models.OperationListResult: _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-05-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-05-01")) cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) - 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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -94,11 +94,9 @@ async def list(self, **kwargs: Any) -> _models.OperationListResult: error = self._deserialize.failsafe_deserialize(_models.ErrorContract, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("OperationListResult", pipeline_response) + deserialized = self._deserialize("OperationListResult", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - list.metadata = {"url": "/providers/Microsoft.Insights/operations"} + return deserialized # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/models/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/models/__init__.py index 9e8662c0512f..1fdeb9602456 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/models/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/models/__init__.py @@ -5,40 +5,51 @@ # 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 DimensionProperties -from ._models_py3 import ErrorContract -from ._models_py3 import ErrorResponse -from ._models_py3 import LocalizableString -from ._models_py3 import LogSpecification -from ._models_py3 import MetadataValue -from ._models_py3 import Metric -from ._models_py3 import MetricAvailability -from ._models_py3 import MetricDefinition -from ._models_py3 import MetricDefinitionCollection -from ._models_py3 import MetricSpecification -from ._models_py3 import MetricValue -from ._models_py3 import Operation -from ._models_py3 import OperationDisplay -from ._models_py3 import OperationListResult -from ._models_py3 import Response -from ._models_py3 import ServiceSpecification -from ._models_py3 import SubscriptionScopeMetric -from ._models_py3 import SubscriptionScopeMetricDefinition -from ._models_py3 import SubscriptionScopeMetricDefinitionCollection -from ._models_py3 import SubscriptionScopeMetricResponse -from ._models_py3 import SubscriptionScopeMetricsRequestBodyParameters -from ._models_py3 import TimeSeriesElement +from typing import TYPE_CHECKING -from ._monitor_management_client_enums import AggregationType -from ._monitor_management_client_enums import MetricAggregationType -from ._monitor_management_client_enums import MetricClass -from ._monitor_management_client_enums import MetricResultType -from ._monitor_management_client_enums import MetricUnit -from ._monitor_management_client_enums import ResultType -from ._monitor_management_client_enums import Unit +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models_py3 import ( # type: ignore + DimensionProperties, + ErrorContract, + ErrorResponse, + LocalizableString, + LogSpecification, + MetadataValue, + Metric, + MetricAvailability, + MetricDefinition, + MetricDefinitionCollection, + MetricSpecification, + MetricValue, + Operation, + OperationDisplay, + OperationListResult, + Response, + ServiceSpecification, + SubscriptionScopeMetric, + SubscriptionScopeMetricDefinition, + SubscriptionScopeMetricDefinitionCollection, + SubscriptionScopeMetricResponse, + SubscriptionScopeMetricsRequestBodyParameters, + TimeSeriesElement, +) + +from ._monitor_management_client_enums import ( # type: ignore + AggregationType, + MetricAggregationType, + MetricClass, + MetricResultType, + MetricUnit, + ResultType, + Unit, +) from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ @@ -73,5 +84,5 @@ "ResultType", "Unit", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/models/_models_py3.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/models/_models_py3.py index 11c8187396fc..055452555f24 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/models/_models_py3.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/models/_models_py3.py @@ -1,5 +1,5 @@ -# coding=utf-8 # 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. @@ -16,10 +16,9 @@ if sys.version_info >= (3, 9): from collections.abc import MutableMapping else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports + from typing import MutableMapping # type: ignore if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from .. import models as _models JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object @@ -131,7 +130,7 @@ def __init__(self, *, code: Optional[str] = None, message: Optional[str] = None, class LocalizableString(_serialization.Model): """The localizable string class. - 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 value: the invariant value. Required. :vartype value: str @@ -230,7 +229,7 @@ def __init__( class Metric(_serialization.Model): """The result data of a query. - 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: the metric Id. Required. :vartype id: str @@ -354,7 +353,7 @@ def __init__( self.retention = retention -class MetricDefinition(_serialization.Model): # pylint: disable=too-many-instance-attributes +class MetricDefinition(_serialization.Model): """Metric definition class specifies the metadata for a metric. :ivar is_dimension_required: Flag to indicate whether the dimension is required. @@ -485,7 +484,7 @@ def __init__( class MetricDefinitionCollection(_serialization.Model): """Represents collection of metric definitions. - 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 value: the values for the metric definitions. Required. :vartype value: list[~azure.mgmt.monitor.v2021_05_01.models.MetricDefinition] @@ -508,7 +507,7 @@ def __init__(self, *, value: List["_models.MetricDefinition"], **kwargs: Any) -> self.value = value -class MetricSpecification(_serialization.Model): # pylint: disable=too-many-instance-attributes +class MetricSpecification(_serialization.Model): """Metric specification of operation. :ivar name: The name of the metric. @@ -518,7 +517,7 @@ class MetricSpecification(_serialization.Model): # pylint: disable=too-many-ins :ivar display_description: Display description of the metric. :vartype display_description: str :ivar unit: The metric unit. Possible values include: - Count,Bytes,Seconds,Percent,CountPerSecond,BytesPerSecond,MilliSeconds,ByteSeconds,Unspecified,BitsPerSecond,Cores,MilliCores,NanoCores. + Count,Bytes,Seconds,Percent,CountPerSecond,BytesPerSecond,MilliSeconds,ByteSeconds,Unspecified,BitsPerSecond,Cores,MilliCores,NanoCores. # pylint: disable=line-too-long :vartype unit: str :ivar aggregation_type: The default metric aggregation type. Possible values include: Total,Average,Maximum,Minimum,Count. @@ -583,7 +582,7 @@ def __init__( :keyword display_description: Display description of the metric. :paramtype display_description: str :keyword unit: The metric unit. Possible values include: - Count,Bytes,Seconds,Percent,CountPerSecond,BytesPerSecond,MilliSeconds,ByteSeconds,Unspecified,BitsPerSecond,Cores,MilliCores,NanoCores. + Count,Bytes,Seconds,Percent,CountPerSecond,BytesPerSecond,MilliSeconds,ByteSeconds,Unspecified,BitsPerSecond,Cores,MilliCores,NanoCores. # pylint: disable=line-too-long :paramtype unit: str :keyword aggregation_type: The default metric aggregation type. Possible values include: Total,Average,Maximum,Minimum,Count. @@ -624,7 +623,7 @@ def __init__( class MetricValue(_serialization.Model): """Represents a metric value. - 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 time_stamp: the timestamp for the metric value in ISO 8601 format. Required. :vartype time_stamp: ~datetime.datetime @@ -820,7 +819,7 @@ def __init__( class Response(_serialization.Model): """The response to a metrics query. - 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 cost: The integer value representing the relative cost of the query. :vartype cost: int @@ -939,7 +938,7 @@ def __init__( class SubscriptionScopeMetric(_serialization.Model): """The result data of a query. - 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: the metric Id. Required. :vartype id: str @@ -1026,7 +1025,7 @@ def __init__( self.timeseries = timeseries -class SubscriptionScopeMetricDefinition(_serialization.Model): # pylint: disable=too-many-instance-attributes +class SubscriptionScopeMetricDefinition(_serialization.Model): """Metric definition class specifies the metadata for a metric. :ivar is_dimension_required: Flag to indicate whether the dimension is required. @@ -1154,10 +1153,10 @@ def __init__( self.dimensions = dimensions -class SubscriptionScopeMetricDefinitionCollection(_serialization.Model): +class SubscriptionScopeMetricDefinitionCollection(_serialization.Model): # pylint: disable=name-too-long """Represents collection of metric definitions. - 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 value: The values for the metric definitions. Required. :vartype value: list[~azure.mgmt.monitor.v2021_05_01.models.SubscriptionScopeMetricDefinition] @@ -1184,7 +1183,7 @@ def __init__(self, *, value: List["_models.SubscriptionScopeMetricDefinition"], class SubscriptionScopeMetricResponse(_serialization.Model): """The response to a subscription scope metrics query. - 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 cost: The integer value representing the relative cost of the query. :vartype cost: int @@ -1257,9 +1256,7 @@ def __init__( self.value = value -class SubscriptionScopeMetricsRequestBodyParameters( - _serialization.Model -): # pylint: disable=too-many-instance-attributes +class SubscriptionScopeMetricsRequestBodyParameters(_serialization.Model): # pylint: disable=name-too-long """Query parameters can also be specified in the body, specifying the same parameter in both the body and query parameters will result in an error. @@ -1274,13 +1271,13 @@ class SubscriptionScopeMetricsRequestBodyParameters( :vartype aggregation: str :ivar filter: The **$filter** is used to reduce the set of metric data returned.:code:`
`Example::code:`
`Metric contains metadata A, B and C.:code:`
`- - Return all time series of C where A = a1 and B = b1 or b2:code:`
`\ **$filter=A eq ‘a1’ and - B eq ‘b1’ or B eq ‘b2’ and C eq ‘*’**\ :code:`
`- Invalid variant::code:`
`\ **$filter=A - eq ‘a1’ and B eq ‘b1’ and C eq ‘*’ or B = ‘b2’**\ :code:`
`This is invalid because the - logical or operator cannot separate two different metadata names.:code:`
`- Return all time - series where A = a1, B = b1 and C = c1::code:`
`\ **$filter=A eq ‘a1’ and B eq ‘b1’ and C eq - ‘c1’**\ :code:`
`- Return all time series where A = a1:code:`
`\ **$filter=A eq ‘a1’ and - B eq ‘\ *’ and C eq ‘*\ ’**. + Return all time series of C where A = a1 and B = b1 or b2:code:`
`\\ **$filter=A eq ‘a1’ and + B eq ‘b1’ or B eq ‘b2’ and C eq ‘*’**\\ :code:`
`- Invalid variant::code:`
`\\ + **$filter=A eq ‘a1’ and B eq ‘b1’ and C eq ‘*’ or B = ‘b2’**\\ :code:`
`This is invalid + because the logical or operator cannot separate two different metadata names.:code:`
`- + Return all time series where A = a1, B = b1 and C = c1::code:`
`\\ **$filter=A eq ‘a1’ and B + eq ‘b1’ and C eq ‘c1’**\\ :code:`
`- Return all time series where A = a1:code:`
`\\ + **$filter=A eq ‘a1’ and B eq ‘\\ *’ and C eq ‘*\\ ’**. :vartype filter: str :ivar top: The maximum number of records to retrieve. Valid only if $filter is specified. @@ -1354,13 +1351,13 @@ def __init__( :paramtype aggregation: str :keyword filter: The **$filter** is used to reduce the set of metric data returned.:code:`
`Example::code:`
`Metric contains metadata A, B and C.:code:`
`- - Return all time series of C where A = a1 and B = b1 or b2:code:`
`\ **$filter=A eq ‘a1’ and - B eq ‘b1’ or B eq ‘b2’ and C eq ‘*’**\ :code:`
`- Invalid variant::code:`
`\ **$filter=A - eq ‘a1’ and B eq ‘b1’ and C eq ‘*’ or B = ‘b2’**\ :code:`
`This is invalid because the - logical or operator cannot separate two different metadata names.:code:`
`- Return all time - series where A = a1, B = b1 and C = c1::code:`
`\ **$filter=A eq ‘a1’ and B eq ‘b1’ and C eq - ‘c1’**\ :code:`
`- Return all time series where A = a1:code:`
`\ **$filter=A eq ‘a1’ and - B eq ‘\ *’ and C eq ‘*\ ’**. + Return all time series of C where A = a1 and B = b1 or b2:code:`
`\\ **$filter=A eq ‘a1’ and + B eq ‘b1’ or B eq ‘b2’ and C eq ‘*’**\\ :code:`
`- Invalid variant::code:`
`\\ + **$filter=A eq ‘a1’ and B eq ‘b1’ and C eq ‘*’ or B = ‘b2’**\\ :code:`
`This is invalid + because the logical or operator cannot separate two different metadata names.:code:`
`- + Return all time series where A = a1, B = b1 and C = c1::code:`
`\\ **$filter=A eq ‘a1’ and B + eq ‘b1’ and C eq ‘c1’**\\ :code:`
`- Return all time series where A = a1:code:`
`\\ + **$filter=A eq ‘a1’ and B eq ‘\\ *’ and C eq ‘*\\ ’**. :paramtype filter: str :keyword top: The maximum number of records to retrieve. Valid only if $filter is specified. diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/operations/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/operations/__init__.py index ca1fe1731e6b..691e9ca92fbe 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/operations/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/operations/__init__.py @@ -5,13 +5,19 @@ # 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 ._metrics_operations import MetricsOperations -from ._metric_definitions_operations import MetricDefinitionsOperations -from ._operations import Operations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._metrics_operations import MetricsOperations # type: ignore +from ._metric_definitions_operations import MetricDefinitionsOperations # type: ignore +from ._operations import Operations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ @@ -19,5 +25,5 @@ "MetricDefinitionsOperations", "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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/operations/_metric_definitions_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/operations/_metric_definitions_operations.py index 84e1f46e1794..97297f267653 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/operations/_metric_definitions_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/operations/_metric_definitions_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,7 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, Callable, Dict, Iterable, Optional, TypeVar import urllib.parse @@ -19,16 +19,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, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -51,7 +53,7 @@ def build_list_at_subscription_scope_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -78,7 +80,7 @@ def build_list_request(resource_uri: str, *, metricnamespace: Optional[str] = No "resourceUri": _SERIALIZER.url("resource_uri", resource_uri, "str", skip_quote=True), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -109,6 +111,7 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list_at_subscription_scope( @@ -121,7 +124,6 @@ def list_at_subscription_scope( :param metricnamespace: Metric namespace where the metrics you want reside. Default value is None. :type metricnamespace: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either SubscriptionScopeMetricDefinition or the result of cls(response) :rtype: @@ -131,10 +133,10 @@ def list_at_subscription_scope( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-05-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-05-01")) cls: ClsType[_models.SubscriptionScopeMetricDefinitionCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -145,17 +147,15 @@ def list_at_subscription_scope( def prepare_request(next_link=None): if not next_link: - request = build_list_at_subscription_scope_request( + _request = build_list_at_subscription_scope_request( subscription_id=self._config.subscription_id, region=region, metricnamespace=metricnamespace, api_version=api_version, - template_url=self.list_at_subscription_scope.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -166,14 +166,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("SubscriptionScopeMetricDefinitionCollection", pipeline_response) @@ -183,11 +182,11 @@ def extract_data(pipeline_response): return None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -200,10 +199,6 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_at_subscription_scope.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/metricDefinitions" - } - @distributed_trace def list( self, resource_uri: str, metricnamespace: Optional[str] = None, **kwargs: Any @@ -215,7 +210,6 @@ def list( :param metricnamespace: Metric namespace where the metrics you want reside. Default value is None. :type metricnamespace: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either MetricDefinition or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.monitor.v2021_05_01.models.MetricDefinition] :raises ~azure.core.exceptions.HttpResponseError: @@ -223,10 +217,10 @@ def list( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-05-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-05-01")) cls: ClsType[_models.MetricDefinitionCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -237,16 +231,14 @@ def list( def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( resource_uri=resource_uri, metricnamespace=metricnamespace, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -257,14 +249,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("MetricDefinitionCollection", pipeline_response) @@ -274,11 +265,11 @@ def extract_data(pipeline_response): return None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -290,5 +281,3 @@ def get_next(next_link=None): return pipeline_response return ItemPaged(get_next, extract_data) - - list.metadata = {"url": "/{resourceUri}/providers/Microsoft.Insights/metricDefinitions"} diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/operations/_metrics_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/operations/_metrics_operations.py index 939cc1fa73f0..a3be676b67d1 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/operations/_metrics_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/operations/_metrics_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +6,8 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- import datetime +from io import IOBase +import sys from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload from azure.core.exceptions import ( @@ -18,16 +19,18 @@ map_error, ) 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 +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -64,7 +67,7 @@ def build_list_at_subscription_scope_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -128,7 +131,7 @@ def build_list_at_subscription_scope_post_request( # pylint: disable=name-too-l "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -192,7 +195,7 @@ def build_list_request( "resourceUri": _SERIALIZER.url("resource_uri", resource_uri, "str", skip_quote=True), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters if timespan is not None: @@ -243,6 +246,7 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list_at_subscription_scope( @@ -286,13 +290,13 @@ def list_at_subscription_scope( :type orderby: str :param filter: The **$filter** is used to reduce the set of metric data returned.:code:`
`Example::code:`
`Metric contains metadata A, B and C.:code:`
`- - Return all time series of C where A = a1 and B = b1 or b2:code:`
`\ **$filter=A eq ‘a1’ and - B eq ‘b1’ or B eq ‘b2’ and C eq ‘*’**\ :code:`
`- Invalid variant::code:`
`\ **$filter=A - eq ‘a1’ and B eq ‘b1’ and C eq ‘*’ or B = ‘b2’**\ :code:`
`This is invalid because the - logical or operator cannot separate two different metadata names.:code:`
`- Return all time - series where A = a1, B = b1 and C = c1::code:`
`\ **$filter=A eq ‘a1’ and B eq ‘b1’ and C eq - ‘c1’**\ :code:`
`- Return all time series where A = a1:code:`
`\ **$filter=A eq ‘a1’ and - B eq ‘\ *’ and C eq ‘*\ ’**. Default value is None. + Return all time series of C where A = a1 and B = b1 or b2:code:`
`\\ **$filter=A eq ‘a1’ and + B eq ‘b1’ or B eq ‘b2’ and C eq ‘*’**\\ :code:`
`- Invalid variant::code:`
`\\ + **$filter=A eq ‘a1’ and B eq ‘b1’ and C eq ‘*’ or B = ‘b2’**\\ :code:`
`This is invalid + because the logical or operator cannot separate two different metadata names.:code:`
`- + Return all time series where A = a1, B = b1 and C = c1::code:`
`\\ **$filter=A eq ‘a1’ and B + eq ‘b1’ and C eq ‘c1’**\\ :code:`
`- Return all time series where A = a1:code:`
`\\ + **$filter=A eq ‘a1’ and B eq ‘\\ *’ and C eq ‘*\\ ’**. Default value is None. :type filter: str :param result_type: Reduces the set of data collected. The syntax allowed depends on the operation. See the operation's description for details. Known values are: "Data" and @@ -310,12 +314,11 @@ def list_at_subscription_scope( When set to true, an error is returned for invalid filter parameters. Defaults to true. Default value is None. :type validate_dimensions: bool - :keyword callable cls: A custom type or function that will be passed the direct response :return: SubscriptionScopeMetricResponse or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_05_01.models.SubscriptionScopeMetricResponse :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -326,10 +329,10 @@ def list_at_subscription_scope( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-05-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-05-01")) cls: ClsType[_models.SubscriptionScopeMetricResponse] = kwargs.pop("cls", None) - request = build_list_at_subscription_scope_request( + _request = build_list_at_subscription_scope_request( subscription_id=self._config.subscription_id, region=region, timespan=timespan, @@ -344,16 +347,14 @@ def list_at_subscription_scope( auto_adjust_timegrain=auto_adjust_timegrain, validate_dimensions=validate_dimensions, api_version=api_version, - template_url=self.list_at_subscription_scope.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -363,16 +364,12 @@ def list_at_subscription_scope( error = self._deserialize.failsafe_deserialize(_models.ErrorContract, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("SubscriptionScopeMetricResponse", pipeline_response) + deserialized = self._deserialize("SubscriptionScopeMetricResponse", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - list_at_subscription_scope.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/metrics" - } + return deserialized # type: ignore @overload def list_at_subscription_scope_post( @@ -420,13 +417,13 @@ def list_at_subscription_scope_post( :type orderby: str :param filter: The **$filter** is used to reduce the set of metric data returned.:code:`
`Example::code:`
`Metric contains metadata A, B and C.:code:`
`- - Return all time series of C where A = a1 and B = b1 or b2:code:`
`\ **$filter=A eq ‘a1’ and - B eq ‘b1’ or B eq ‘b2’ and C eq ‘*’**\ :code:`
`- Invalid variant::code:`
`\ **$filter=A - eq ‘a1’ and B eq ‘b1’ and C eq ‘*’ or B = ‘b2’**\ :code:`
`This is invalid because the - logical or operator cannot separate two different metadata names.:code:`
`- Return all time - series where A = a1, B = b1 and C = c1::code:`
`\ **$filter=A eq ‘a1’ and B eq ‘b1’ and C eq - ‘c1’**\ :code:`
`- Return all time series where A = a1:code:`
`\ **$filter=A eq ‘a1’ and - B eq ‘\ *’ and C eq ‘*\ ’**. Default value is None. + Return all time series of C where A = a1 and B = b1 or b2:code:`
`\\ **$filter=A eq ‘a1’ and + B eq ‘b1’ or B eq ‘b2’ and C eq ‘*’**\\ :code:`
`- Invalid variant::code:`
`\\ + **$filter=A eq ‘a1’ and B eq ‘b1’ and C eq ‘*’ or B = ‘b2’**\\ :code:`
`This is invalid + because the logical or operator cannot separate two different metadata names.:code:`
`- + Return all time series where A = a1, B = b1 and C = c1::code:`
`\\ **$filter=A eq ‘a1’ and B + eq ‘b1’ and C eq ‘c1’**\\ :code:`
`- Return all time series where A = a1:code:`
`\\ + **$filter=A eq ‘a1’ and B eq ‘\\ *’ and C eq ‘*\\ ’**. Default value is None. :type filter: str :param result_type: Reduces the set of data collected. The syntax allowed depends on the operation. See the operation's description for details. Known values are: "Data" and @@ -450,7 +447,6 @@ def list_at_subscription_scope_post( :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: SubscriptionScopeMetricResponse or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_05_01.models.SubscriptionScopeMetricResponse :raises ~azure.core.exceptions.HttpResponseError: @@ -471,7 +467,7 @@ def list_at_subscription_scope_post( metricnamespace: Optional[str] = None, auto_adjust_timegrain: Optional[bool] = None, validate_dimensions: Optional[bool] = None, - body: Optional[IO] = None, + body: Optional[IO[bytes]] = None, *, content_type: str = "application/json", **kwargs: Any @@ -502,13 +498,13 @@ def list_at_subscription_scope_post( :type orderby: str :param filter: The **$filter** is used to reduce the set of metric data returned.:code:`
`Example::code:`
`Metric contains metadata A, B and C.:code:`
`- - Return all time series of C where A = a1 and B = b1 or b2:code:`
`\ **$filter=A eq ‘a1’ and - B eq ‘b1’ or B eq ‘b2’ and C eq ‘*’**\ :code:`
`- Invalid variant::code:`
`\ **$filter=A - eq ‘a1’ and B eq ‘b1’ and C eq ‘*’ or B = ‘b2’**\ :code:`
`This is invalid because the - logical or operator cannot separate two different metadata names.:code:`
`- Return all time - series where A = a1, B = b1 and C = c1::code:`
`\ **$filter=A eq ‘a1’ and B eq ‘b1’ and C eq - ‘c1’**\ :code:`
`- Return all time series where A = a1:code:`
`\ **$filter=A eq ‘a1’ and - B eq ‘\ *’ and C eq ‘*\ ’**. Default value is None. + Return all time series of C where A = a1 and B = b1 or b2:code:`
`\\ **$filter=A eq ‘a1’ and + B eq ‘b1’ or B eq ‘b2’ and C eq ‘*’**\\ :code:`
`- Invalid variant::code:`
`\\ + **$filter=A eq ‘a1’ and B eq ‘b1’ and C eq ‘*’ or B = ‘b2’**\\ :code:`
`This is invalid + because the logical or operator cannot separate two different metadata names.:code:`
`- + Return all time series where A = a1, B = b1 and C = c1::code:`
`\\ **$filter=A eq ‘a1’ and B + eq ‘b1’ and C eq ‘c1’**\\ :code:`
`- Return all time series where A = a1:code:`
`\\ + **$filter=A eq ‘a1’ and B eq ‘\\ *’ and C eq ‘*\\ ’**. Default value is None. :type filter: str :param result_type: Reduces the set of data collected. The syntax allowed depends on the operation. See the operation's description for details. Known values are: "Data" and @@ -527,11 +523,10 @@ def list_at_subscription_scope_post( value is None. :type validate_dimensions: bool :param body: Parameters serialized in the body. Default value is None. - :type body: IO + :type body: 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: SubscriptionScopeMetricResponse or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_05_01.models.SubscriptionScopeMetricResponse :raises ~azure.core.exceptions.HttpResponseError: @@ -552,7 +547,7 @@ def list_at_subscription_scope_post( metricnamespace: Optional[str] = None, auto_adjust_timegrain: Optional[bool] = None, validate_dimensions: Optional[bool] = None, - body: Optional[Union[_models.SubscriptionScopeMetricsRequestBodyParameters, IO]] = None, + body: Optional[Union[_models.SubscriptionScopeMetricsRequestBodyParameters, IO[bytes]]] = None, **kwargs: Any ) -> _models.SubscriptionScopeMetricResponse: """**Lists the metric data for a subscription**. Parameters can be specified on either query @@ -581,13 +576,13 @@ def list_at_subscription_scope_post( :type orderby: str :param filter: The **$filter** is used to reduce the set of metric data returned.:code:`
`Example::code:`
`Metric contains metadata A, B and C.:code:`
`- - Return all time series of C where A = a1 and B = b1 or b2:code:`
`\ **$filter=A eq ‘a1’ and - B eq ‘b1’ or B eq ‘b2’ and C eq ‘*’**\ :code:`
`- Invalid variant::code:`
`\ **$filter=A - eq ‘a1’ and B eq ‘b1’ and C eq ‘*’ or B = ‘b2’**\ :code:`
`This is invalid because the - logical or operator cannot separate two different metadata names.:code:`
`- Return all time - series where A = a1, B = b1 and C = c1::code:`
`\ **$filter=A eq ‘a1’ and B eq ‘b1’ and C eq - ‘c1’**\ :code:`
`- Return all time series where A = a1:code:`
`\ **$filter=A eq ‘a1’ and - B eq ‘\ *’ and C eq ‘*\ ’**. Default value is None. + Return all time series of C where A = a1 and B = b1 or b2:code:`
`\\ **$filter=A eq ‘a1’ and + B eq ‘b1’ or B eq ‘b2’ and C eq ‘*’**\\ :code:`
`- Invalid variant::code:`
`\\ + **$filter=A eq ‘a1’ and B eq ‘b1’ and C eq ‘*’ or B = ‘b2’**\\ :code:`
`This is invalid + because the logical or operator cannot separate two different metadata names.:code:`
`- + Return all time series where A = a1, B = b1 and C = c1::code:`
`\\ **$filter=A eq ‘a1’ and B + eq ‘b1’ and C eq ‘c1’**\\ :code:`
`- Return all time series where A = a1:code:`
`\\ + **$filter=A eq ‘a1’ and B eq ‘\\ *’ and C eq ‘*\\ ’**. Default value is None. :type filter: str :param result_type: Reduces the set of data collected. The syntax allowed depends on the operation. See the operation's description for details. Known values are: "Data" and @@ -606,18 +601,15 @@ def list_at_subscription_scope_post( value is None. :type validate_dimensions: bool :param body: Parameters serialized in the body. Is either a - SubscriptionScopeMetricsRequestBodyParameters type or a IO type. Default value is None. + SubscriptionScopeMetricsRequestBodyParameters type or a IO[bytes] type. Default value is None. :type body: - ~azure.mgmt.monitor.v2021_05_01.models.SubscriptionScopeMetricsRequestBodyParameters 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 + ~azure.mgmt.monitor.v2021_05_01.models.SubscriptionScopeMetricsRequestBodyParameters or + IO[bytes] :return: SubscriptionScopeMetricResponse or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_05_01.models.SubscriptionScopeMetricResponse :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -628,14 +620,14 @@ def list_at_subscription_scope_post( _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", "2021-05-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-05-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.SubscriptionScopeMetricResponse] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(body, (IO, bytes)): + if isinstance(body, (IOBase, bytes)): _content = body else: if body is not None: @@ -643,7 +635,7 @@ def list_at_subscription_scope_post( else: _json = None - request = build_list_at_subscription_scope_post_request( + _request = build_list_at_subscription_scope_post_request( subscription_id=self._config.subscription_id, region=region, timespan=timespan, @@ -661,16 +653,14 @@ def list_at_subscription_scope_post( content_type=content_type, json=_json, content=_content, - template_url=self.list_at_subscription_scope_post.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -680,16 +670,12 @@ def list_at_subscription_scope_post( error = self._deserialize.failsafe_deserialize(_models.ErrorContract, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("SubscriptionScopeMetricResponse", pipeline_response) + deserialized = self._deserialize("SubscriptionScopeMetricResponse", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - list_at_subscription_scope_post.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/metrics" - } + return deserialized # type: ignore @distributed_trace def list( @@ -733,13 +719,13 @@ def list( :type orderby: str :param filter: The **$filter** is used to reduce the set of metric data returned.:code:`
`Example::code:`
`Metric contains metadata A, B and C.:code:`
`- - Return all time series of C where A = a1 and B = b1 or b2:code:`
`\ **$filter=A eq ‘a1’ and - B eq ‘b1’ or B eq ‘b2’ and C eq ‘*’**\ :code:`
`- Invalid variant::code:`
`\ **$filter=A - eq ‘a1’ and B eq ‘b1’ and C eq ‘*’ or B = ‘b2’**\ :code:`
`This is invalid because the - logical or operator cannot separate two different metadata names.:code:`
`- Return all time - series where A = a1, B = b1 and C = c1::code:`
`\ **$filter=A eq ‘a1’ and B eq ‘b1’ and C eq - ‘c1’**\ :code:`
`- Return all time series where A = a1:code:`
`\ **$filter=A eq ‘a1’ and - B eq ‘\ *’ and C eq ‘*\ ’**. Default value is None. + Return all time series of C where A = a1 and B = b1 or b2:code:`
`\\ **$filter=A eq ‘a1’ and + B eq ‘b1’ or B eq ‘b2’ and C eq ‘*’**\\ :code:`
`- Invalid variant::code:`
`\\ + **$filter=A eq ‘a1’ and B eq ‘b1’ and C eq ‘*’ or B = ‘b2’**\\ :code:`
`This is invalid + because the logical or operator cannot separate two different metadata names.:code:`
`- + Return all time series where A = a1, B = b1 and C = c1::code:`
`\\ **$filter=A eq ‘a1’ and B + eq ‘b1’ and C eq ‘c1’**\\ :code:`
`- Return all time series where A = a1:code:`
`\\ + **$filter=A eq ‘a1’ and B eq ‘\\ *’ and C eq ‘*\\ ’**. Default value is None. :type filter: str :param result_type: Reduces the set of data collected. The syntax allowed depends on the operation. See the operation's description for details. Known values are: "Data" and @@ -757,12 +743,11 @@ def list( When set to true, an error is returned for invalid filter parameters. Defaults to true. Default value is None. :type validate_dimensions: bool - :keyword callable cls: A custom type or function that will be passed the direct response :return: Response or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_05_01.models.Response :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -773,10 +758,10 @@ def list( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-05-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-05-01")) cls: ClsType[_models.Response] = kwargs.pop("cls", None) - request = build_list_request( + _request = build_list_request( resource_uri=resource_uri, timespan=timespan, interval=interval, @@ -790,16 +775,14 @@ def list( auto_adjust_timegrain=auto_adjust_timegrain, validate_dimensions=validate_dimensions, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -809,11 +792,9 @@ def list( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("Response", pipeline_response) + deserialized = self._deserialize("Response", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - list.metadata = {"url": "/{resourceUri}/providers/Microsoft.Insights/metrics"} + return deserialized # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/operations/_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/operations/_operations.py index 256cf97311e8..c6f2c63258f3 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/operations/_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01/operations/_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,7 @@ # 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 ( @@ -17,16 +17,18 @@ map_error, ) 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 +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -71,17 +73,17 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list(self, **kwargs: Any) -> _models.OperationListResult: """Lists all of the available operations from Microsoft.Insights provider. - :keyword callable cls: A custom type or function that will be passed the direct response :return: OperationListResult or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_05_01.models.OperationListResult :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -92,21 +94,19 @@ def list(self, **kwargs: Any) -> _models.OperationListResult: _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-05-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-05-01")) cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) - 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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -116,11 +116,9 @@ def list(self, **kwargs: Any) -> _models.OperationListResult: error = self._deserialize.failsafe_deserialize(_models.ErrorContract, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("OperationListResult", pipeline_response) + deserialized = self._deserialize("OperationListResult", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - list.metadata = {"url": "/providers/Microsoft.Insights/operations"} + return deserialized # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/__init__.py index 2c7733bfd566..42cc62301757 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/__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 ._monitor_management_client import MonitorManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._monitor_management_client import MonitorManagementClient # type: ignore from ._version import VERSION __version__ = VERSION try: from ._patch import __all__ as _patch_all - from ._patch import * # 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__ = [ "MonitorManagementClient", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/_configuration.py index 225ab1692079..e41258b6e9a6 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/_configuration.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/_configuration.py @@ -8,18 +8,16 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy from ._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MonitorManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class MonitorManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for MonitorManagementClient. Note that all parameters used to create this instance are saved as instance @@ -35,7 +33,6 @@ class MonitorManagementClientConfiguration(Configuration): # pylint: disable=to """ def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: - super(MonitorManagementClientConfiguration, self).__init__(**kwargs) api_version: str = kwargs.pop("api_version", "2021-05-01-preview") if credential is None: @@ -48,6 +45,7 @@ def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-monitor/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -56,9 +54,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.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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/_metadata.json b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/_metadata.json index f2b273c6bf72..4cd53570fa52 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/_metadata.json +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/_metadata.json @@ -8,10 +8,10 @@ "host_value": "\"https://management.azure.com\"", "parameterized_host_template": null, "azure_arm": true, - "has_lro_operations": false, + "has_public_lro_operations": false, "client_side_validation": false, - "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"sdkcore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMAutoResourceProviderRegistrationPolicy\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}, \"stdlib\": {\"typing_extensions\": [\"Self\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"sdkcore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"AsyncARMAutoResourceProviderRegistrationPolicy\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}, \"stdlib\": {\"typing_extensions\": [\"Self\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "global_parameters": { "sync": { @@ -101,8 +101,8 @@ "credential_scopes": ["https://management.azure.com/.default"], "credential_call_sync": "ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", "credential_call_async": "AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", - "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "sync_imports": "{\"regular\": {\"sdkcore\": {\"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"regular\": {\"sdkcore\": {\"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "operation_groups": { "autoscale_settings": "AutoscaleSettingsOperations", diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/_monitor_management_client.py index 4330b407ed8c..8b00d235d162 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/_monitor_management_client.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/_monitor_management_client.py @@ -8,9 +8,12 @@ from copy import deepcopy from typing import Any, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient +from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy from . import models as _models from .._serialization import Deserializer, Serializer @@ -25,11 +28,10 @@ ) if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MonitorManagementClient: # pylint: disable=client-accepts-api-version-keyword +class MonitorManagementClient: """Monitor Management Client. :ivar autoscale_settings: AutoscaleSettingsOperations operations @@ -72,32 +74,50 @@ def __init__( self._config = MonitorManagementClientConfiguration( credential=credential, subscription_id=subscription_id, **kwargs ) - self._client: ARMPipelineClient = ARMPipelineClient(base_url=base_url, config=self._config, **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), + 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=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.autoscale_settings = AutoscaleSettingsOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2021-05-01-preview" ) self.predictive_metric = PredictiveMetricOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2021-05-01-preview" ) self.diagnostic_settings = DiagnosticSettingsOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2021-05-01-preview" ) self.diagnostic_settings_category = DiagnosticSettingsCategoryOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2021-05-01-preview" ) self.management_group_diagnostic_settings = ManagementGroupDiagnosticSettingsOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2021-05-01-preview" ) self.subscription_diagnostic_settings = SubscriptionDiagnosticSettingsOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2021-05-01-preview" ) - 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 @@ -117,12 +137,12 @@ 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) -> None: self._client.close() - def __enter__(self) -> "MonitorManagementClient": + def __enter__(self) -> Self: self._client.__enter__() return self diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/_vendor.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/_vendor.py deleted file mode 100644 index bd0df84f5319..000000000000 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/_vendor.py +++ /dev/null @@ -1,30 +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 typing import List, cast - -from azure.core.pipeline.transport import HttpRequest - - -def _convert_request(request, files=None): - data = request.content if not files else None - request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) - if files: - request.set_formdata_body(files) - return request - - -def _format_url_section(template, **kwargs): - components = template.split("/") - while components: - try: - return template.format(**kwargs) - except KeyError as key: - # Need the cast, as for some reasons "split" is typed as list[str | Any] - formatted_components = cast(List[str], template.split("/")) - components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] - template = "/".join(components) diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/_version.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/_version.py index 394ee7c0c03c..e5754a47ce68 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/_version.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "6.0.2" +VERSION = "1.0.0b1" diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/aio/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/aio/__init__.py index 2c151bb41c19..3df30ff42149 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/aio/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/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 ._monitor_management_client import MonitorManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._monitor_management_client import MonitorManagementClient # type: ignore try: from ._patch import __all__ as _patch_all - from ._patch import * # 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__ = [ "MonitorManagementClient", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/aio/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/aio/_configuration.py index 06c4726413bf..ed3d3e4d0a40 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/aio/_configuration.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/aio/_configuration.py @@ -8,18 +8,16 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy from .._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MonitorManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class MonitorManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for MonitorManagementClient. Note that all parameters used to create this instance are saved as instance @@ -35,7 +33,6 @@ class MonitorManagementClientConfiguration(Configuration): # pylint: disable=to """ def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: - super(MonitorManagementClientConfiguration, self).__init__(**kwargs) api_version: str = kwargs.pop("api_version", "2021-05-01-preview") if credential is None: @@ -48,6 +45,7 @@ def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **k self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-monitor/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -56,9 +54,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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/aio/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/aio/_monitor_management_client.py index 13974f530e37..289e60604865 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/aio/_monitor_management_client.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/aio/_monitor_management_client.py @@ -8,9 +8,12 @@ from copy import deepcopy from typing import Any, Awaitable, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient +from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy from .. import models as _models from ..._serialization import Deserializer, Serializer @@ -25,11 +28,10 @@ ) if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MonitorManagementClient: # pylint: disable=client-accepts-api-version-keyword +class MonitorManagementClient: """Monitor Management Client. :ivar autoscale_settings: AutoscaleSettingsOperations operations @@ -72,32 +74,52 @@ def __init__( self._config = MonitorManagementClientConfiguration( credential=credential, subscription_id=subscription_id, **kwargs ) - self._client: AsyncARMPipelineClient = AsyncARMPipelineClient(base_url=base_url, config=self._config, **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=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.autoscale_settings = AutoscaleSettingsOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2021-05-01-preview" ) self.predictive_metric = PredictiveMetricOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2021-05-01-preview" ) self.diagnostic_settings = DiagnosticSettingsOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2021-05-01-preview" ) self.diagnostic_settings_category = DiagnosticSettingsCategoryOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2021-05-01-preview" ) self.management_group_diagnostic_settings = ManagementGroupDiagnosticSettingsOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2021-05-01-preview" ) self.subscription_diagnostic_settings = SubscriptionDiagnosticSettingsOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2021-05-01-preview" ) - 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 @@ -117,12 +139,12 @@ 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) -> "MonitorManagementClient": + async def __aenter__(self) -> Self: await self._client.__aenter__() return self diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/aio/operations/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/aio/operations/__init__.py index 526d8450f6ce..7d4eb02b31c9 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/aio/operations/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/aio/operations/__init__.py @@ -5,16 +5,22 @@ # 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 ._autoscale_settings_operations import AutoscaleSettingsOperations -from ._predictive_metric_operations import PredictiveMetricOperations -from ._diagnostic_settings_operations import DiagnosticSettingsOperations -from ._diagnostic_settings_category_operations import DiagnosticSettingsCategoryOperations -from ._management_group_diagnostic_settings_operations import ManagementGroupDiagnosticSettingsOperations -from ._subscription_diagnostic_settings_operations import SubscriptionDiagnosticSettingsOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._autoscale_settings_operations import AutoscaleSettingsOperations # type: ignore +from ._predictive_metric_operations import PredictiveMetricOperations # type: ignore +from ._diagnostic_settings_operations import DiagnosticSettingsOperations # type: ignore +from ._diagnostic_settings_category_operations import DiagnosticSettingsCategoryOperations # type: ignore +from ._management_group_diagnostic_settings_operations import ManagementGroupDiagnosticSettingsOperations # type: ignore +from ._subscription_diagnostic_settings_operations import SubscriptionDiagnosticSettingsOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ @@ -25,5 +31,5 @@ "ManagementGroupDiagnosticSettingsOperations", "SubscriptionDiagnosticSettingsOperations", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/aio/operations/_autoscale_settings_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/aio/operations/_autoscale_settings_operations.py index 2a8bd6ff5093..7e332449c1a1 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/aio/operations/_autoscale_settings_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/aio/operations/_autoscale_settings_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload import urllib.parse @@ -19,15 +20,13 @@ 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 ...operations._autoscale_settings_operations import ( build_create_or_update_request, build_delete_request, @@ -37,6 +36,10 @@ build_update_request, ) +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -59,17 +62,18 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list_by_resource_group( self, resource_group_name: str, **kwargs: Any ) -> AsyncIterable["_models.AutoscaleSettingResource"]: + # pylint: disable=line-too-long """Lists the autoscale settings for a resource group. :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either AutoscaleSettingResource or the result of cls(response) :rtype: @@ -79,10 +83,12 @@ def list_by_resource_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-05-01-preview") + ) cls: ClsType[_models.AutoscaleSettingResourceCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -93,16 +99,14 @@ 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_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -113,14 +117,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("AutoscaleSettingResourceCollection", pipeline_response) @@ -130,11 +133,11 @@ async def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -147,10 +150,6 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/autoscalesettings" - } - @overload async def create_or_update( self, @@ -173,7 +172,6 @@ async def create_or_update( :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: AutoscaleSettingResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_05_01_preview.models.AutoscaleSettingResource :raises ~azure.core.exceptions.HttpResponseError: @@ -184,7 +182,7 @@ async def create_or_update( self, resource_group_name: str, autoscale_setting_name: str, - parameters: IO, + parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -197,11 +195,10 @@ async def create_or_update( :param autoscale_setting_name: The autoscale setting name. Required. :type autoscale_setting_name: str :param parameters: Parameters supplied to the operation. Required. - :type parameters: IO + :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: AutoscaleSettingResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_05_01_preview.models.AutoscaleSettingResource :raises ~azure.core.exceptions.HttpResponseError: @@ -212,7 +209,7 @@ async def create_or_update( self, resource_group_name: str, autoscale_setting_name: str, - parameters: Union[_models.AutoscaleSettingResource, IO], + parameters: Union[_models.AutoscaleSettingResource, IO[bytes]], **kwargs: Any ) -> _models.AutoscaleSettingResource: """Creates or updates an autoscale setting. @@ -223,17 +220,14 @@ async def create_or_update( :param autoscale_setting_name: The autoscale setting name. Required. :type autoscale_setting_name: str :param parameters: Parameters supplied to the operation. Is either a AutoscaleSettingResource - type or a IO type. Required. - :type parameters: ~azure.mgmt.monitor.v2021_05_01_preview.models.AutoscaleSettingResource 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 + type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.monitor.v2021_05_01_preview.models.AutoscaleSettingResource or + IO[bytes] :return: AutoscaleSettingResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_05_01_preview.models.AutoscaleSettingResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -244,19 +238,21 @@ async def create_or_update( _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", "2021-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-05-01-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.AutoscaleSettingResource] = 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, "AutoscaleSettingResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, autoscale_setting_name=autoscale_setting_name, subscription_id=self._config.subscription_id, @@ -264,16 +260,14 @@ async def create_or_update( 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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -283,25 +277,15 @@ async def create_or_update( error = self._deserialize.failsafe_deserialize(_models.AutoscaleErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if response.status_code == 200: - deserialized = self._deserialize("AutoscaleSettingResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("AutoscaleSettingResource", pipeline_response) + deserialized = self._deserialize("AutoscaleSettingResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/autoscalesettings/{autoscaleSettingName}" - } - @distributed_trace_async - async def delete( # pylint: disable=inconsistent-return-statements - self, resource_group_name: str, autoscale_setting_name: str, **kwargs: Any - ) -> None: + async def delete(self, resource_group_name: str, autoscale_setting_name: str, **kwargs: Any) -> None: """Deletes and autoscale setting. :param resource_group_name: The name of the resource group. The name is case insensitive. @@ -309,12 +293,11 @@ async def delete( # pylint: disable=inconsistent-return-statements :type resource_group_name: str :param autoscale_setting_name: The autoscale setting name. Required. :type autoscale_setting_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, @@ -325,24 +308,24 @@ async def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-05-01-preview") + ) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, autoscale_setting_name=autoscale_setting_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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -353,11 +336,7 @@ async def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/autoscalesettings/{autoscaleSettingName}" - } + return cls(pipeline_response, None, {}) # type: ignore @distributed_trace_async async def get( @@ -370,12 +349,11 @@ async def get( :type resource_group_name: str :param autoscale_setting_name: The autoscale setting name. Required. :type autoscale_setting_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: AutoscaleSettingResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_05_01_preview.models.AutoscaleSettingResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -386,24 +364,24 @@ async def get( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-05-01-preview") + ) cls: ClsType[_models.AutoscaleSettingResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, autoscale_setting_name=autoscale_setting_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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -413,16 +391,12 @@ async def get( error = self._deserialize.failsafe_deserialize(_models.AutoscaleErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("AutoscaleSettingResource", pipeline_response) + deserialized = self._deserialize("AutoscaleSettingResource", 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.Insights/autoscalesettings/{autoscaleSettingName}" - } + return deserialized # type: ignore @overload async def update( @@ -448,7 +422,6 @@ async def update( :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: AutoscaleSettingResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_05_01_preview.models.AutoscaleSettingResource :raises ~azure.core.exceptions.HttpResponseError: @@ -459,7 +432,7 @@ async def update( self, resource_group_name: str, autoscale_setting_name: str, - autoscale_setting_resource: IO, + autoscale_setting_resource: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -473,11 +446,10 @@ async def update( :param autoscale_setting_name: The autoscale setting name. Required. :type autoscale_setting_name: str :param autoscale_setting_resource: Parameters supplied to the operation. Required. - :type autoscale_setting_resource: IO + :type autoscale_setting_resource: 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: AutoscaleSettingResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_05_01_preview.models.AutoscaleSettingResource :raises ~azure.core.exceptions.HttpResponseError: @@ -488,7 +460,7 @@ async def update( self, resource_group_name: str, autoscale_setting_name: str, - autoscale_setting_resource: Union[_models.AutoscaleSettingResourcePatch, IO], + autoscale_setting_resource: Union[_models.AutoscaleSettingResourcePatch, IO[bytes]], **kwargs: Any ) -> _models.AutoscaleSettingResource: """Updates an existing AutoscaleSettingsResource. To update other fields use the CreateOrUpdate @@ -500,18 +472,14 @@ async def update( :param autoscale_setting_name: The autoscale setting name. Required. :type autoscale_setting_name: str :param autoscale_setting_resource: Parameters supplied to the operation. Is either a - AutoscaleSettingResourcePatch type or a IO type. Required. + AutoscaleSettingResourcePatch type or a IO[bytes] type. Required. :type autoscale_setting_resource: - ~azure.mgmt.monitor.v2021_05_01_preview.models.AutoscaleSettingResourcePatch 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 + ~azure.mgmt.monitor.v2021_05_01_preview.models.AutoscaleSettingResourcePatch or IO[bytes] :return: AutoscaleSettingResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_05_01_preview.models.AutoscaleSettingResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -522,19 +490,21 @@ async def update( _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", "2021-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-05-01-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.AutoscaleSettingResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(autoscale_setting_resource, (IO, bytes)): + if isinstance(autoscale_setting_resource, (IOBase, bytes)): _content = autoscale_setting_resource else: _json = self._serialize.body(autoscale_setting_resource, "AutoscaleSettingResourcePatch") - request = build_update_request( + _request = build_update_request( resource_group_name=resource_group_name, autoscale_setting_name=autoscale_setting_name, subscription_id=self._config.subscription_id, @@ -542,16 +512,14 @@ async def update( 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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -561,22 +529,18 @@ async def update( error = self._deserialize.failsafe_deserialize(_models.AutoscaleErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("AutoscaleSettingResource", pipeline_response) + deserialized = self._deserialize("AutoscaleSettingResource", 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.Insights/autoscalesettings/{autoscaleSettingName}" - } + return deserialized # type: ignore @distributed_trace def list_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.AutoscaleSettingResource"]: + # pylint: disable=line-too-long """Lists the autoscale settings for a subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either AutoscaleSettingResource or the result of cls(response) :rtype: @@ -586,10 +550,12 @@ def list_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.Autoscal _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-05-01-preview") + ) cls: ClsType[_models.AutoscaleSettingResourceCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -600,15 +566,13 @@ def list_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.Autoscal def prepare_request(next_link=None): if not next_link: - request = build_list_by_subscription_request( + _request = build_list_by_subscription_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_subscription.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -619,14 +583,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("AutoscaleSettingResourceCollection", pipeline_response) @@ -636,11 +599,11 @@ async def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -652,7 +615,3 @@ async def get_next(next_link=None): return pipeline_response return AsyncItemPaged(get_next, extract_data) - - list_by_subscription.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/autoscalesettings" - } diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/aio/operations/_diagnostic_settings_category_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/aio/operations/_diagnostic_settings_category_operations.py index 87ee26a26935..9d134d889a65 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/aio/operations/_diagnostic_settings_category_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/aio/operations/_diagnostic_settings_category_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,7 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar import urllib.parse @@ -19,17 +19,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.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._diagnostic_settings_category_operations import build_get_request, build_list_request +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -52,6 +54,7 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace_async async def get(self, resource_uri: str, name: str, **kwargs: Any) -> _models.DiagnosticSettingsCategoryResource: @@ -61,12 +64,11 @@ async def get(self, resource_uri: str, name: str, **kwargs: Any) -> _models.Diag :type resource_uri: str :param name: The name of the diagnostic setting. Required. :type name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: DiagnosticSettingsCategoryResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_05_01_preview.models.DiagnosticSettingsCategoryResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -77,23 +79,23 @@ async def get(self, resource_uri: str, name: str, **kwargs: Any) -> _models.Diag _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-05-01-preview") + ) cls: ClsType[_models.DiagnosticSettingsCategoryResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_uri=resource_uri, name=name, api_version=api_version, - template_url=self.get.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -103,22 +105,20 @@ async def get(self, resource_uri: str, name: str, **kwargs: Any) -> _models.Diag error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("DiagnosticSettingsCategoryResource", pipeline_response) + deserialized = self._deserialize("DiagnosticSettingsCategoryResource", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get.metadata = {"url": "/{resourceUri}/providers/Microsoft.Insights/diagnosticSettingsCategories/{name}"} + return deserialized # type: ignore @distributed_trace def list(self, resource_uri: str, **kwargs: Any) -> AsyncIterable["_models.DiagnosticSettingsCategoryResource"]: + # pylint: disable=line-too-long """Lists the diagnostic settings categories for the specified resource. :param resource_uri: The identifier of the resource. Required. :type resource_uri: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either DiagnosticSettingsCategoryResource or the result of cls(response) :rtype: @@ -128,10 +128,12 @@ def list(self, resource_uri: str, **kwargs: Any) -> AsyncIterable["_models.Diagn _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-05-01-preview") + ) cls: ClsType[_models.DiagnosticSettingsCategoryResourceCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -142,15 +144,13 @@ def list(self, resource_uri: str, **kwargs: Any) -> AsyncIterable["_models.Diagn def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( resource_uri=resource_uri, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -161,14 +161,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("DiagnosticSettingsCategoryResourceCollection", pipeline_response) @@ -178,11 +177,11 @@ async def extract_data(pipeline_response): return None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -194,5 +193,3 @@ async def get_next(next_link=None): return pipeline_response return AsyncItemPaged(get_next, extract_data) - - list.metadata = {"url": "/{resourceUri}/providers/Microsoft.Insights/diagnosticSettingsCategories"} diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/aio/operations/_diagnostic_settings_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/aio/operations/_diagnostic_settings_operations.py index 10924aeb4781..49122c1ed69e 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/aio/operations/_diagnostic_settings_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/aio/operations/_diagnostic_settings_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload import urllib.parse @@ -19,15 +20,13 @@ 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 ...operations._diagnostic_settings_operations import ( build_create_or_update_request, build_delete_request, @@ -35,6 +34,10 @@ build_list_request, ) +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -57,6 +60,7 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace_async async def get(self, resource_uri: str, name: str, **kwargs: Any) -> _models.DiagnosticSettingsResource: @@ -66,12 +70,11 @@ async def get(self, resource_uri: str, name: str, **kwargs: Any) -> _models.Diag :type resource_uri: str :param name: The name of the diagnostic setting. Required. :type name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: DiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_05_01_preview.models.DiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -82,23 +85,23 @@ async def get(self, resource_uri: str, name: str, **kwargs: Any) -> _models.Diag _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-05-01-preview") + ) cls: ClsType[_models.DiagnosticSettingsResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_uri=resource_uri, name=name, api_version=api_version, - template_url=self.get.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -108,14 +111,12 @@ async def get(self, resource_uri: str, name: str, **kwargs: Any) -> _models.Diag error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("DiagnosticSettingsResource", pipeline_response) + deserialized = self._deserialize("DiagnosticSettingsResource", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get.metadata = {"url": "/{resourceUri}/providers/Microsoft.Insights/diagnosticSettings/{name}"} + return deserialized # type: ignore @overload async def create_or_update( @@ -138,7 +139,6 @@ async def create_or_update( :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: DiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_05_01_preview.models.DiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: @@ -146,7 +146,13 @@ async def create_or_update( @overload async def create_or_update( - self, resource_uri: str, name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + self, + resource_uri: str, + name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any ) -> _models.DiagnosticSettingsResource: """Creates or updates diagnostic settings for the specified resource. @@ -155,11 +161,10 @@ async def create_or_update( :param name: The name of the diagnostic setting. Required. :type name: str :param parameters: Parameters supplied to the operation. Required. - :type parameters: IO + :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: DiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_05_01_preview.models.DiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: @@ -167,7 +172,11 @@ async def create_or_update( @distributed_trace_async async def create_or_update( - self, resource_uri: str, name: str, parameters: Union[_models.DiagnosticSettingsResource, IO], **kwargs: Any + self, + resource_uri: str, + name: str, + parameters: Union[_models.DiagnosticSettingsResource, IO[bytes]], + **kwargs: Any ) -> _models.DiagnosticSettingsResource: """Creates or updates diagnostic settings for the specified resource. @@ -176,18 +185,14 @@ async def create_or_update( :param name: The name of the diagnostic setting. Required. :type name: str :param parameters: Parameters supplied to the operation. Is either a DiagnosticSettingsResource - type or a IO type. Required. + type or a IO[bytes] type. Required. :type parameters: ~azure.mgmt.monitor.v2021_05_01_preview.models.DiagnosticSettingsResource 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 + IO[bytes] :return: DiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_05_01_preview.models.DiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -198,35 +203,35 @@ async def create_or_update( _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", "2021-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-05-01-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.DiagnosticSettingsResource] = 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, "DiagnosticSettingsResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_uri=resource_uri, name=name, 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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -236,31 +241,26 @@ async def create_or_update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("DiagnosticSettingsResource", pipeline_response) + deserialized = self._deserialize("DiagnosticSettingsResource", 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": "/{resourceUri}/providers/Microsoft.Insights/diagnosticSettings/{name}"} + return deserialized # type: ignore @distributed_trace_async - async def delete( # pylint: disable=inconsistent-return-statements - self, resource_uri: str, name: str, **kwargs: Any - ) -> None: + async def delete(self, resource_uri: str, name: str, **kwargs: Any) -> None: """Deletes existing diagnostic settings for the specified resource. :param resource_uri: The identifier of the resource. Required. :type resource_uri: str :param name: The name of the diagnostic setting. Required. :type 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, @@ -271,23 +271,23 @@ async def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-05-01-preview") + ) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_uri=resource_uri, name=name, api_version=api_version, - template_url=self.delete.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -298,17 +298,15 @@ async def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = {"url": "/{resourceUri}/providers/Microsoft.Insights/diagnosticSettings/{name}"} + return cls(pipeline_response, None, {}) # type: ignore @distributed_trace def list(self, resource_uri: str, **kwargs: Any) -> AsyncIterable["_models.DiagnosticSettingsResource"]: + # pylint: disable=line-too-long """Gets the active diagnostic settings list for the specified resource. :param resource_uri: The identifier of the resource. Required. :type resource_uri: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either DiagnosticSettingsResource or the result of cls(response) :rtype: @@ -318,10 +316,12 @@ def list(self, resource_uri: str, **kwargs: Any) -> AsyncIterable["_models.Diagn _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-05-01-preview") + ) cls: ClsType[_models.DiagnosticSettingsResourceCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -332,15 +332,13 @@ def list(self, resource_uri: str, **kwargs: Any) -> AsyncIterable["_models.Diagn def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( resource_uri=resource_uri, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -351,14 +349,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("DiagnosticSettingsResourceCollection", pipeline_response) @@ -368,11 +365,11 @@ async def extract_data(pipeline_response): return None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -384,5 +381,3 @@ async def get_next(next_link=None): return pipeline_response return AsyncItemPaged(get_next, extract_data) - - list.metadata = {"url": "/{resourceUri}/providers/Microsoft.Insights/diagnosticSettings"} diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/aio/operations/_management_group_diagnostic_settings_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/aio/operations/_management_group_diagnostic_settings_operations.py index 51c02a4408ca..2aba19a62419 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/aio/operations/_management_group_diagnostic_settings_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/aio/operations/_management_group_diagnostic_settings_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload import urllib.parse @@ -19,15 +20,13 @@ 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 ...operations._management_group_diagnostic_settings_operations import ( build_create_or_update_request, build_delete_request, @@ -35,11 +34,15 @@ build_list_request, ) +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class ManagementGroupDiagnosticSettingsOperations: +class ManagementGroupDiagnosticSettingsOperations: # pylint: disable=name-too-long """ .. warning:: **DO NOT** instantiate this class directly. @@ -57,6 +60,7 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace_async async def get( @@ -68,13 +72,12 @@ async def get( :type management_group_id: str :param name: The name of the diagnostic setting. Required. :type name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ManagementGroupDiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_05_01_preview.models.ManagementGroupDiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -85,23 +88,23 @@ async def get( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-05-01-preview") + ) cls: ClsType[_models.ManagementGroupDiagnosticSettingsResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( management_group_id=management_group_id, name=name, api_version=api_version, - template_url=self.get.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -111,16 +114,12 @@ async def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ManagementGroupDiagnosticSettingsResource", pipeline_response) + deserialized = self._deserialize("ManagementGroupDiagnosticSettingsResource", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get.metadata = { - "url": "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Insights/diagnosticSettings/{name}" - } + return deserialized # type: ignore @overload async def create_or_update( @@ -144,7 +143,6 @@ async def create_or_update( :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: ManagementGroupDiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_05_01_preview.models.ManagementGroupDiagnosticSettingsResource @@ -156,7 +154,7 @@ async def create_or_update( self, management_group_id: str, name: str, - parameters: IO, + parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -168,11 +166,10 @@ async def create_or_update( :param name: The name of the diagnostic setting. Required. :type name: str :param parameters: Parameters supplied to the operation. Required. - :type parameters: IO + :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: ManagementGroupDiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_05_01_preview.models.ManagementGroupDiagnosticSettingsResource @@ -184,7 +181,7 @@ async def create_or_update( self, management_group_id: str, name: str, - parameters: Union[_models.ManagementGroupDiagnosticSettingsResource, IO], + parameters: Union[_models.ManagementGroupDiagnosticSettingsResource, IO[bytes]], **kwargs: Any ) -> _models.ManagementGroupDiagnosticSettingsResource: """Creates or updates management group diagnostic settings for the specified resource. @@ -194,19 +191,16 @@ async def create_or_update( :param name: The name of the diagnostic setting. Required. :type name: str :param parameters: Parameters supplied to the operation. Is either a - ManagementGroupDiagnosticSettingsResource type or a IO type. Required. + ManagementGroupDiagnosticSettingsResource type or a IO[bytes] type. Required. :type parameters: - ~azure.mgmt.monitor.v2021_05_01_preview.models.ManagementGroupDiagnosticSettingsResource 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 + ~azure.mgmt.monitor.v2021_05_01_preview.models.ManagementGroupDiagnosticSettingsResource or + IO[bytes] :return: ManagementGroupDiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_05_01_preview.models.ManagementGroupDiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -217,35 +211,35 @@ async def create_or_update( _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", "2021-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-05-01-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ManagementGroupDiagnosticSettingsResource] = 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, "ManagementGroupDiagnosticSettingsResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( management_group_id=management_group_id, name=name, 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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -255,33 +249,26 @@ async def create_or_update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ManagementGroupDiagnosticSettingsResource", pipeline_response) + deserialized = self._deserialize("ManagementGroupDiagnosticSettingsResource", 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": "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Insights/diagnosticSettings/{name}" - } + return deserialized # type: ignore @distributed_trace_async - async def delete( # pylint: disable=inconsistent-return-statements - self, management_group_id: str, name: str, **kwargs: Any - ) -> None: + async def delete(self, management_group_id: str, name: str, **kwargs: Any) -> None: """Deletes existing management group diagnostic settings for the specified resource. :param management_group_id: The management group id. Required. :type management_group_id: str :param name: The name of the diagnostic setting. Required. :type 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, @@ -292,23 +279,23 @@ async def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-05-01-preview") + ) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( management_group_id=management_group_id, name=name, api_version=api_version, - template_url=self.delete.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -319,21 +306,17 @@ async def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Insights/diagnosticSettings/{name}" - } + return cls(pipeline_response, None, {}) # type: ignore @distributed_trace def list( self, management_group_id: str, **kwargs: Any ) -> AsyncIterable["_models.ManagementGroupDiagnosticSettingsResource"]: + # pylint: disable=line-too-long """Gets the active management group diagnostic settings list for the specified management group. :param management_group_id: The management group id. Required. :type management_group_id: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ManagementGroupDiagnosticSettingsResource or the result of cls(response) :rtype: @@ -343,10 +326,12 @@ def list( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-05-01-preview") + ) cls: ClsType[_models.ManagementGroupDiagnosticSettingsResourceCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -357,15 +342,13 @@ def list( def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( management_group_id=management_group_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) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -376,14 +359,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("ManagementGroupDiagnosticSettingsResourceCollection", pipeline_response) @@ -393,11 +375,11 @@ async def extract_data(pipeline_response): return None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -409,7 +391,3 @@ async def get_next(next_link=None): return pipeline_response return AsyncItemPaged(get_next, extract_data) - - list.metadata = { - "url": "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Insights/diagnosticSettings" - } diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/aio/operations/_predictive_metric_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/aio/operations/_predictive_metric_operations.py index 7907cef27da3..9a14c693461c 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/aio/operations/_predictive_metric_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/aio/operations/_predictive_metric_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +6,7 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- import datetime +import sys from typing import Any, Callable, Dict, Optional, TypeVar from azure.core.exceptions import ( @@ -18,16 +18,18 @@ 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_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._predictive_metric_operations import build_get_request +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -50,6 +52,7 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace_async async def get( @@ -83,12 +86,11 @@ async def get( :type metric_name: str :param aggregation: The list of aggregation types (comma separated) to retrieve. Required. :type aggregation: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: PredictiveResponse or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_05_01_preview.models.PredictiveResponse :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -99,10 +101,12 @@ async def get( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-05-01-preview") + ) cls: ClsType[_models.PredictiveResponse] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, autoscale_setting_name=autoscale_setting_name, subscription_id=self._config.subscription_id, @@ -112,16 +116,14 @@ async def get( metric_name=metric_name, aggregation=aggregation, api_version=api_version, - template_url=self.get.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -131,13 +133,9 @@ async def get( error = self._deserialize.failsafe_deserialize(_models.AutoscaleErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("PredictiveResponse", pipeline_response) + deserialized = self._deserialize("PredictiveResponse", 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.Insights/autoscalesettings/{autoscaleSettingName}/predictiveMetrics" - } + return deserialized # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/aio/operations/_subscription_diagnostic_settings_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/aio/operations/_subscription_diagnostic_settings_operations.py index f79a002ba422..fcef190ec385 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/aio/operations/_subscription_diagnostic_settings_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/aio/operations/_subscription_diagnostic_settings_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload import urllib.parse @@ -19,15 +20,13 @@ 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 ...operations._subscription_diagnostic_settings_operations import ( build_create_or_update_request, build_delete_request, @@ -35,6 +34,10 @@ build_list_request, ) +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -57,6 +60,7 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace_async async def get(self, name: str, **kwargs: Any) -> _models.SubscriptionDiagnosticSettingsResource: @@ -64,12 +68,11 @@ async def get(self, name: str, **kwargs: Any) -> _models.SubscriptionDiagnosticS :param name: The name of the diagnostic setting. Required. :type name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: SubscriptionDiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_05_01_preview.models.SubscriptionDiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -80,23 +83,23 @@ async def get(self, name: str, **kwargs: Any) -> _models.SubscriptionDiagnosticS _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-05-01-preview") + ) cls: ClsType[_models.SubscriptionDiagnosticSettingsResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( name=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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -106,14 +109,12 @@ async def get(self, name: str, **kwargs: Any) -> _models.SubscriptionDiagnosticS error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("SubscriptionDiagnosticSettingsResource", pipeline_response) + deserialized = self._deserialize("SubscriptionDiagnosticSettingsResource", 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}/providers/Microsoft.Insights/diagnosticSettings/{name}"} + return deserialized # type: ignore @overload async def create_or_update( @@ -134,7 +135,6 @@ async def create_or_update( :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: SubscriptionDiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_05_01_preview.models.SubscriptionDiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: @@ -142,18 +142,17 @@ async def create_or_update( @overload async def create_or_update( - self, name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + self, name: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any ) -> _models.SubscriptionDiagnosticSettingsResource: """Creates or updates subscription diagnostic settings for the specified resource. :param name: The name of the diagnostic setting. Required. :type name: str :param parameters: Parameters supplied to the operation. Required. - :type parameters: IO + :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: SubscriptionDiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_05_01_preview.models.SubscriptionDiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: @@ -161,25 +160,22 @@ async def create_or_update( @distributed_trace_async async def create_or_update( - self, name: str, parameters: Union[_models.SubscriptionDiagnosticSettingsResource, IO], **kwargs: Any + self, name: str, parameters: Union[_models.SubscriptionDiagnosticSettingsResource, IO[bytes]], **kwargs: Any ) -> _models.SubscriptionDiagnosticSettingsResource: """Creates or updates subscription diagnostic settings for the specified resource. :param name: The name of the diagnostic setting. Required. :type name: str :param parameters: Parameters supplied to the operation. Is either a - SubscriptionDiagnosticSettingsResource type or a IO type. Required. + SubscriptionDiagnosticSettingsResource type or a IO[bytes] type. Required. :type parameters: - ~azure.mgmt.monitor.v2021_05_01_preview.models.SubscriptionDiagnosticSettingsResource 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 + ~azure.mgmt.monitor.v2021_05_01_preview.models.SubscriptionDiagnosticSettingsResource or + IO[bytes] :return: SubscriptionDiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_05_01_preview.models.SubscriptionDiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -190,35 +186,35 @@ async def create_or_update( _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", "2021-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-05-01-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.SubscriptionDiagnosticSettingsResource] = 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, "SubscriptionDiagnosticSettingsResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( name=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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -228,29 +224,24 @@ async def create_or_update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("SubscriptionDiagnosticSettingsResource", pipeline_response) + deserialized = self._deserialize("SubscriptionDiagnosticSettingsResource", 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}/providers/Microsoft.Insights/diagnosticSettings/{name}" - } + return deserialized # type: ignore @distributed_trace_async - async def delete(self, name: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements + async def delete(self, name: str, **kwargs: Any) -> None: """Deletes existing subscription diagnostic settings for the specified resource. :param name: The name of the diagnostic setting. Required. :type 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, @@ -261,23 +252,23 @@ async def delete(self, name: str, **kwargs: Any) -> None: # pylint: disable=inc _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-05-01-preview") + ) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( name=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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -288,15 +279,13 @@ async def delete(self, name: str, **kwargs: Any) -> None: # pylint: disable=inc raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/diagnosticSettings/{name}"} + return cls(pipeline_response, None, {}) # type: ignore @distributed_trace def list(self, **kwargs: Any) -> AsyncIterable["_models.SubscriptionDiagnosticSettingsResource"]: + # pylint: disable=line-too-long """Gets the active subscription diagnostic settings list for the specified subscriptionId. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either SubscriptionDiagnosticSettingsResource or the result of cls(response) :rtype: @@ -306,10 +295,12 @@ def list(self, **kwargs: Any) -> AsyncIterable["_models.SubscriptionDiagnosticSe _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-05-01-preview") + ) cls: ClsType[_models.SubscriptionDiagnosticSettingsResourceCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -320,15 +311,13 @@ def list(self, **kwargs: Any) -> AsyncIterable["_models.SubscriptionDiagnosticSe def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _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) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -339,14 +328,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("SubscriptionDiagnosticSettingsResourceCollection", pipeline_response) @@ -356,11 +344,11 @@ async def extract_data(pipeline_response): return None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -372,5 +360,3 @@ async def get_next(next_link=None): return pipeline_response return AsyncItemPaged(get_next, extract_data) - - list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/diagnosticSettings"} diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/models/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/models/__init__.py index aaaecfe7ecb4..a61409d134f1 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/models/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/models/__init__.py @@ -5,56 +5,67 @@ # 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 AutoscaleErrorResponse -from ._models_py3 import AutoscaleErrorResponseError -from ._models_py3 import AutoscaleNotification -from ._models_py3 import AutoscaleProfile -from ._models_py3 import AutoscaleSettingResource -from ._models_py3 import AutoscaleSettingResourceCollection -from ._models_py3 import AutoscaleSettingResourcePatch -from ._models_py3 import DiagnosticSettingsCategoryResource -from ._models_py3 import DiagnosticSettingsCategoryResourceCollection -from ._models_py3 import DiagnosticSettingsResource -from ._models_py3 import DiagnosticSettingsResourceCollection -from ._models_py3 import EmailNotification -from ._models_py3 import ErrorResponse -from ._models_py3 import LogSettings -from ._models_py3 import ManagementGroupDiagnosticSettingsResource -from ._models_py3 import ManagementGroupDiagnosticSettingsResourceCollection -from ._models_py3 import ManagementGroupLogSettings -from ._models_py3 import MetricSettings -from ._models_py3 import MetricTrigger -from ._models_py3 import PredictiveAutoscalePolicy -from ._models_py3 import PredictiveResponse -from ._models_py3 import PredictiveValue -from ._models_py3 import Recurrence -from ._models_py3 import RecurrentSchedule -from ._models_py3 import Resource -from ._models_py3 import RetentionPolicy -from ._models_py3 import ScaleAction -from ._models_py3 import ScaleCapacity -from ._models_py3 import ScaleRule -from ._models_py3 import ScaleRuleMetricDimension -from ._models_py3 import SubscriptionDiagnosticSettingsResource -from ._models_py3 import SubscriptionDiagnosticSettingsResourceCollection -from ._models_py3 import SubscriptionLogSettings -from ._models_py3 import SystemData -from ._models_py3 import TimeWindow -from ._models_py3 import WebhookNotification +from typing import TYPE_CHECKING -from ._monitor_management_client_enums import CategoryType -from ._monitor_management_client_enums import ComparisonOperationType -from ._monitor_management_client_enums import CreatedByType -from ._monitor_management_client_enums import MetricStatisticType -from ._monitor_management_client_enums import PredictiveAutoscalePolicyScaleMode -from ._monitor_management_client_enums import RecurrenceFrequency -from ._monitor_management_client_enums import ScaleDirection -from ._monitor_management_client_enums import ScaleRuleMetricDimensionOperationType -from ._monitor_management_client_enums import ScaleType -from ._monitor_management_client_enums import TimeAggregationType +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models_py3 import ( # type: ignore + AutoscaleErrorResponse, + AutoscaleErrorResponseError, + AutoscaleNotification, + AutoscaleProfile, + AutoscaleSettingResource, + AutoscaleSettingResourceCollection, + AutoscaleSettingResourcePatch, + DiagnosticSettingsCategoryResource, + DiagnosticSettingsCategoryResourceCollection, + DiagnosticSettingsResource, + DiagnosticSettingsResourceCollection, + EmailNotification, + ErrorResponse, + LogSettings, + ManagementGroupDiagnosticSettingsResource, + ManagementGroupDiagnosticSettingsResourceCollection, + ManagementGroupLogSettings, + MetricSettings, + MetricTrigger, + PredictiveAutoscalePolicy, + PredictiveResponse, + PredictiveValue, + Recurrence, + RecurrentSchedule, + Resource, + RetentionPolicy, + ScaleAction, + ScaleCapacity, + ScaleRule, + ScaleRuleMetricDimension, + SubscriptionDiagnosticSettingsResource, + SubscriptionDiagnosticSettingsResourceCollection, + SubscriptionLogSettings, + SystemData, + TimeWindow, + WebhookNotification, +) + +from ._monitor_management_client_enums import ( # type: ignore + CategoryType, + ComparisonOperationType, + CreatedByType, + MetricStatisticType, + PredictiveAutoscalePolicyScaleMode, + RecurrenceFrequency, + ScaleDirection, + ScaleRuleMetricDimensionOperationType, + ScaleType, + TimeAggregationType, +) from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ @@ -105,5 +116,5 @@ "ScaleType", "TimeAggregationType", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/models/_models_py3.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/models/_models_py3.py index 3ab1eeb67299..29ca58bb214b 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/models/_models_py3.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/models/_models_py3.py @@ -1,5 +1,5 @@ -# coding=utf-8 # 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. @@ -13,7 +13,6 @@ from ... import _serialization if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from .. import models as _models @@ -98,7 +97,7 @@ class AutoscaleNotification(_serialization.Model): 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 operation: the operation associated with the notification and its value must be "scale". Required. Default value is "Scale". @@ -142,7 +141,7 @@ def __init__( class AutoscaleProfile(_serialization.Model): """Autoscale profile. - 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 name of the profile. Required. :vartype name: str @@ -206,12 +205,12 @@ def __init__( self.recurrence = recurrence -class AutoscaleSettingResource(_serialization.Model): # pylint: disable=too-many-instance-attributes +class AutoscaleSettingResource(_serialization.Model): """The autoscale setting 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: Azure resource Id. :vartype id: str @@ -340,7 +339,7 @@ def __init__( class AutoscaleSettingResourceCollection(_serialization.Model): """Represents a collection of autoscale setting resources. - 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 value: the values for the autoscale setting resources. Required. :vartype value: list[~azure.mgmt.monitor.v2021_05_01_preview.models.AutoscaleSettingResource] @@ -470,7 +469,7 @@ class Resource(_serialization.Model): 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}. + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long :vartype id: str :ivar name: The name of the resource. :vartype name: str @@ -505,7 +504,7 @@ class DiagnosticSettingsCategoryResource(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}. + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long :vartype id: str :ivar name: The name of the resource. :vartype name: str @@ -557,7 +556,7 @@ def __init__( self.category_groups = category_groups -class DiagnosticSettingsCategoryResourceCollection(_serialization.Model): +class DiagnosticSettingsCategoryResourceCollection(_serialization.Model): # pylint: disable=name-too-long """Represents a collection of diagnostic setting category resources. :ivar value: The collection of diagnostic settings category resources. @@ -581,13 +580,13 @@ def __init__( self.value = value -class DiagnosticSettingsResource(Resource): # pylint: disable=too-many-instance-attributes +class DiagnosticSettingsResource(Resource): """The diagnostic setting 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}. + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long :vartype id: str :ivar name: The name of the resource. :vartype name: str @@ -613,7 +612,7 @@ class DiagnosticSettingsResource(Resource): # pylint: disable=too-many-instance :vartype logs: list[~azure.mgmt.monitor.v2021_05_01_preview.models.LogSettings] :ivar workspace_id: The full ARM resource ID of the Log Analytics workspace to which you would like to send Diagnostic Logs. Example: - /subscriptions/4b9e8510-67ab-4e9a-95a9-e2f1e570ea9c/resourceGroups/insights-integration/providers/Microsoft.OperationalInsights/workspaces/viruela2. + /subscriptions/4b9e8510-67ab-4e9a-95a9-e2f1e570ea9c/resourceGroups/insights-integration/providers/Microsoft.OperationalInsights/workspaces/viruela2. # pylint: disable=line-too-long :vartype workspace_id: str :ivar marketplace_partner_id: The full ARM resource ID of the Marketplace resource to which you would like to send Diagnostic Logs. @@ -680,7 +679,7 @@ def __init__( :paramtype logs: list[~azure.mgmt.monitor.v2021_05_01_preview.models.LogSettings] :keyword workspace_id: The full ARM resource ID of the Log Analytics workspace to which you would like to send Diagnostic Logs. Example: - /subscriptions/4b9e8510-67ab-4e9a-95a9-e2f1e570ea9c/resourceGroups/insights-integration/providers/Microsoft.OperationalInsights/workspaces/viruela2. + /subscriptions/4b9e8510-67ab-4e9a-95a9-e2f1e570ea9c/resourceGroups/insights-integration/providers/Microsoft.OperationalInsights/workspaces/viruela2. # pylint: disable=line-too-long :paramtype workspace_id: str :keyword marketplace_partner_id: The full ARM resource ID of the Marketplace resource to which you would like to send Diagnostic Logs. @@ -799,7 +798,7 @@ def __init__(self, *, code: Optional[str] = None, message: Optional[str] = None, class LogSettings(_serialization.Model): """Part of MultiTenantDiagnosticSettings. Specifies the settings for a particular log. - 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 category: Name of a Diagnostic Log category for a resource type this setting is applied to. To obtain the list of Diagnostic Log categories for a resource, first perform a GET @@ -856,13 +855,13 @@ def __init__( self.retention_policy = retention_policy -class ManagementGroupDiagnosticSettingsResource(Resource): # pylint: disable=too-many-instance-attributes +class ManagementGroupDiagnosticSettingsResource(Resource): # pylint: disable=name-too-long """The management group diagnostic setting 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}. + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long :vartype id: str :ivar name: The name of the resource. :vartype name: str @@ -886,7 +885,7 @@ class ManagementGroupDiagnosticSettingsResource(Resource): # pylint: disable=to :vartype logs: list[~azure.mgmt.monitor.v2021_05_01_preview.models.ManagementGroupLogSettings] :ivar workspace_id: The full ARM resource ID of the Log Analytics workspace to which you would like to send Diagnostic Logs. Example: - /subscriptions/4b9e8510-67ab-4e9a-95a9-e2f1e570ea9c/resourceGroups/insights-integration/providers/Microsoft.OperationalInsights/workspaces/viruela2. + /subscriptions/4b9e8510-67ab-4e9a-95a9-e2f1e570ea9c/resourceGroups/insights-integration/providers/Microsoft.OperationalInsights/workspaces/viruela2. # pylint: disable=line-too-long :vartype workspace_id: str :ivar marketplace_partner_id: The full ARM resource ID of the Marketplace resource to which you would like to send Diagnostic Logs. @@ -943,7 +942,7 @@ def __init__( list[~azure.mgmt.monitor.v2021_05_01_preview.models.ManagementGroupLogSettings] :keyword workspace_id: The full ARM resource ID of the Log Analytics workspace to which you would like to send Diagnostic Logs. Example: - /subscriptions/4b9e8510-67ab-4e9a-95a9-e2f1e570ea9c/resourceGroups/insights-integration/providers/Microsoft.OperationalInsights/workspaces/viruela2. + /subscriptions/4b9e8510-67ab-4e9a-95a9-e2f1e570ea9c/resourceGroups/insights-integration/providers/Microsoft.OperationalInsights/workspaces/viruela2. # pylint: disable=line-too-long :paramtype workspace_id: str :keyword marketplace_partner_id: The full ARM resource ID of the Marketplace resource to which you would like to send Diagnostic Logs. @@ -960,7 +959,7 @@ def __init__( self.marketplace_partner_id = marketplace_partner_id -class ManagementGroupDiagnosticSettingsResourceCollection(_serialization.Model): +class ManagementGroupDiagnosticSettingsResourceCollection(_serialization.Model): # pylint: disable=name-too-long """Represents a collection of management group diagnostic settings resources. :ivar value: The collection of management group diagnostic settings resources. @@ -987,7 +986,7 @@ def __init__( class ManagementGroupLogSettings(_serialization.Model): """Part of Management Group diagnostic setting. Specifies the settings for a particular log. - 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 category: Name of a Management Group Diagnostic Log category for a resource type this setting is applied to. @@ -1031,7 +1030,7 @@ def __init__( class MetricSettings(_serialization.Model): """Part of MultiTenantDiagnosticSettings. Specifies the settings for a particular metric. - 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 time_grain: the timegrain of the metric in ISO8601 format. :vartype time_grain: ~datetime.timedelta @@ -1084,10 +1083,10 @@ def __init__( self.retention_policy = retention_policy -class MetricTrigger(_serialization.Model): # pylint: disable=too-many-instance-attributes +class MetricTrigger(_serialization.Model): """The trigger that results in a scaling action. - 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 metric_name: the name of the metric that defines what the rule monitors. Required. :vartype metric_name: str @@ -1121,7 +1120,7 @@ class MetricTrigger(_serialization.Model): # pylint: disable=too-many-instance- :ivar threshold: the threshold of the metric that triggers the scale action. Required. :vartype threshold: float :ivar dimensions: List of dimension conditions. For example: - [{"DimensionName":"AppName","Operator":"Equals","Values":["App1"]},{"DimensionName":"Deployment","Operator":"Equals","Values":["default"]}]. + [{"DimensionName":"AppName","Operator":"Equals","Values":["App1"]},{"DimensionName":"Deployment","Operator":"Equals","Values":["default"]}]. # pylint: disable=line-too-long :vartype dimensions: list[~azure.mgmt.monitor.v2021_05_01_preview.models.ScaleRuleMetricDimension] :ivar divide_per_instance: a value indicating whether metric should divide per instance. @@ -1205,7 +1204,7 @@ def __init__( :keyword threshold: the threshold of the metric that triggers the scale action. Required. :paramtype threshold: float :keyword dimensions: List of dimension conditions. For example: - [{"DimensionName":"AppName","Operator":"Equals","Values":["App1"]},{"DimensionName":"Deployment","Operator":"Equals","Values":["default"]}]. + [{"DimensionName":"AppName","Operator":"Equals","Values":["App1"]},{"DimensionName":"Deployment","Operator":"Equals","Values":["default"]}]. # pylint: disable=line-too-long :paramtype dimensions: list[~azure.mgmt.monitor.v2021_05_01_preview.models.ScaleRuleMetricDimension] :keyword divide_per_instance: a value indicating whether metric should divide per instance. @@ -1229,7 +1228,7 @@ def __init__( class PredictiveAutoscalePolicy(_serialization.Model): """The parameters for enabling predictive autoscale. - 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 scale_mode: the predictive autoscale mode. Required. Known values are: "Disabled", "ForecastOnly", and "Enabled". @@ -1334,7 +1333,7 @@ def __init__( class PredictiveValue(_serialization.Model): """Represents a predictive metric value in the given bucket. - 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 time_stamp: the timestamp for the metric value in ISO 8601 format. Required. :vartype time_stamp: ~datetime.datetime @@ -1368,7 +1367,7 @@ class Recurrence(_serialization.Model): """The repeating times at which this profile begins. This element is not used if the FixedDate element is used. - 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 frequency: the recurrence frequency. How often the schedule profile should take effect. This value must be Week, meaning each week will have the same set of profiles. For example, to @@ -1415,7 +1414,7 @@ def __init__( class RecurrentSchedule(_serialization.Model): """The scheduling constraints for when the profile begins. - 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 time_zone: the timezone for the hours of the profile. Some examples of valid time zones are: Dateline Standard Time, UTC-11, Hawaiian Standard Time, Alaskan Standard Time, Pacific @@ -1524,7 +1523,7 @@ def __init__(self, *, time_zone: str, days: List[str], hours: List[int], minutes class RetentionPolicy(_serialization.Model): """Specifies the retention policy for the log. - 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 enabled: a value indicating whether the retention policy is enabled. Required. :vartype enabled: bool @@ -1559,7 +1558,7 @@ def __init__(self, *, enabled: bool, days: int, **kwargs: Any) -> None: class ScaleAction(_serialization.Model): """The parameters for the scaling action. - 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 direction: the scale direction. Whether the scaling action increases or decreases the number of instances. Required. Known values are: "None", "Increase", and "Decrease". @@ -1621,7 +1620,7 @@ def __init__( class ScaleCapacity(_serialization.Model): """The number of instances that can be used during this profile. - 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 minimum: the minimum number of instances for the resource. Required. :vartype minimum: str @@ -1667,7 +1666,7 @@ def __init__(self, *, minimum: str, maximum: str, default: str, **kwargs: Any) - class ScaleRule(_serialization.Model): """A rule that provide the triggers and parameters for the scaling action. - 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 metric_trigger: the trigger that results in a scaling action. Required. :vartype metric_trigger: ~azure.mgmt.monitor.v2021_05_01_preview.models.MetricTrigger @@ -1702,7 +1701,7 @@ def __init__( class ScaleRuleMetricDimension(_serialization.Model): """Specifies an auto scale rule metric dimension. - 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 dimension_name: Name of the dimension. Required. :vartype dimension_name: str @@ -1752,13 +1751,13 @@ def __init__( self.values = values -class SubscriptionDiagnosticSettingsResource(Resource): # pylint: disable=too-many-instance-attributes +class SubscriptionDiagnosticSettingsResource(Resource): """The subscription diagnostic setting 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}. + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long :vartype id: str :ivar name: The name of the resource. :vartype name: str @@ -1782,7 +1781,7 @@ class SubscriptionDiagnosticSettingsResource(Resource): # pylint: disable=too-m :vartype logs: list[~azure.mgmt.monitor.v2021_05_01_preview.models.SubscriptionLogSettings] :ivar workspace_id: The full ARM resource ID of the Log Analytics workspace to which you would like to send Diagnostic Logs. Example: - /subscriptions/4b9e8510-67ab-4e9a-95a9-e2f1e570ea9c/resourceGroups/insights-integration/providers/Microsoft.OperationalInsights/workspaces/viruela2. + /subscriptions/4b9e8510-67ab-4e9a-95a9-e2f1e570ea9c/resourceGroups/insights-integration/providers/Microsoft.OperationalInsights/workspaces/viruela2. # pylint: disable=line-too-long :vartype workspace_id: str :ivar marketplace_partner_id: The full ARM resource ID of the Marketplace resource to which you would like to send Diagnostic Logs. @@ -1838,7 +1837,7 @@ def __init__( :paramtype logs: list[~azure.mgmt.monitor.v2021_05_01_preview.models.SubscriptionLogSettings] :keyword workspace_id: The full ARM resource ID of the Log Analytics workspace to which you would like to send Diagnostic Logs. Example: - /subscriptions/4b9e8510-67ab-4e9a-95a9-e2f1e570ea9c/resourceGroups/insights-integration/providers/Microsoft.OperationalInsights/workspaces/viruela2. + /subscriptions/4b9e8510-67ab-4e9a-95a9-e2f1e570ea9c/resourceGroups/insights-integration/providers/Microsoft.OperationalInsights/workspaces/viruela2. # pylint: disable=line-too-long :paramtype workspace_id: str :keyword marketplace_partner_id: The full ARM resource ID of the Marketplace resource to which you would like to send Diagnostic Logs. @@ -1855,7 +1854,7 @@ def __init__( self.marketplace_partner_id = marketplace_partner_id -class SubscriptionDiagnosticSettingsResourceCollection(_serialization.Model): +class SubscriptionDiagnosticSettingsResourceCollection(_serialization.Model): # pylint: disable=name-too-long """Represents a collection of subscription diagnostic settings resources. :ivar value: The collection of subscription diagnostic settings resources. @@ -1882,7 +1881,7 @@ def __init__( class SubscriptionLogSettings(_serialization.Model): """Part of Subscription diagnostic setting. Specifies the settings for a particular log. - 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 category: Name of a Subscription Diagnostic Log category for a resource type this setting is applied to. @@ -1992,7 +1991,7 @@ def __init__( class TimeWindow(_serialization.Model): """A specific date-time for the profile. - 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 time_zone: the timezone of the start and end times for the profile. Some examples of valid time zones are: Dateline Standard Time, UTC-11, Hawaiian Standard Time, Alaskan Standard diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/operations/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/operations/__init__.py index 526d8450f6ce..7d4eb02b31c9 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/operations/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/operations/__init__.py @@ -5,16 +5,22 @@ # 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 ._autoscale_settings_operations import AutoscaleSettingsOperations -from ._predictive_metric_operations import PredictiveMetricOperations -from ._diagnostic_settings_operations import DiagnosticSettingsOperations -from ._diagnostic_settings_category_operations import DiagnosticSettingsCategoryOperations -from ._management_group_diagnostic_settings_operations import ManagementGroupDiagnosticSettingsOperations -from ._subscription_diagnostic_settings_operations import SubscriptionDiagnosticSettingsOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._autoscale_settings_operations import AutoscaleSettingsOperations # type: ignore +from ._predictive_metric_operations import PredictiveMetricOperations # type: ignore +from ._diagnostic_settings_operations import DiagnosticSettingsOperations # type: ignore +from ._diagnostic_settings_category_operations import DiagnosticSettingsCategoryOperations # type: ignore +from ._management_group_diagnostic_settings_operations import ManagementGroupDiagnosticSettingsOperations # type: ignore +from ._subscription_diagnostic_settings_operations import SubscriptionDiagnosticSettingsOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ @@ -25,5 +31,5 @@ "ManagementGroupDiagnosticSettingsOperations", "SubscriptionDiagnosticSettingsOperations", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/operations/_autoscale_settings_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/operations/_autoscale_settings_operations.py index 58b7c033d782..96f445ab4798 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/operations/_autoscale_settings_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/operations/_autoscale_settings_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload import urllib.parse @@ -19,16 +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, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -55,7 +58,7 @@ def build_list_by_resource_group_request(resource_group_name: str, subscription_ "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -89,7 +92,7 @@ def build_create_or_update_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -124,7 +127,7 @@ def build_delete_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -157,7 +160,7 @@ def build_get_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -191,7 +194,7 @@ def build_update_request( "autoscaleSettingName": _SERIALIZER.url("autoscale_setting_name", autoscale_setting_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -217,7 +220,7 @@ def build_list_by_subscription_request(subscription_id: str, **kwargs: Any) -> H "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -246,6 +249,7 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list_by_resource_group( @@ -256,7 +260,6 @@ def list_by_resource_group( :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either AutoscaleSettingResource or the result of cls(response) :rtype: @@ -266,10 +269,12 @@ def list_by_resource_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-05-01-preview") + ) cls: ClsType[_models.AutoscaleSettingResourceCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -280,16 +285,14 @@ 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_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -300,14 +303,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("AutoscaleSettingResourceCollection", pipeline_response) @@ -317,11 +319,11 @@ def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -334,10 +336,6 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/autoscalesettings" - } - @overload def create_or_update( self, @@ -360,7 +358,6 @@ def create_or_update( :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: AutoscaleSettingResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_05_01_preview.models.AutoscaleSettingResource :raises ~azure.core.exceptions.HttpResponseError: @@ -371,7 +368,7 @@ def create_or_update( self, resource_group_name: str, autoscale_setting_name: str, - parameters: IO, + parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -384,11 +381,10 @@ def create_or_update( :param autoscale_setting_name: The autoscale setting name. Required. :type autoscale_setting_name: str :param parameters: Parameters supplied to the operation. Required. - :type parameters: IO + :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: AutoscaleSettingResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_05_01_preview.models.AutoscaleSettingResource :raises ~azure.core.exceptions.HttpResponseError: @@ -399,7 +395,7 @@ def create_or_update( self, resource_group_name: str, autoscale_setting_name: str, - parameters: Union[_models.AutoscaleSettingResource, IO], + parameters: Union[_models.AutoscaleSettingResource, IO[bytes]], **kwargs: Any ) -> _models.AutoscaleSettingResource: """Creates or updates an autoscale setting. @@ -410,17 +406,14 @@ def create_or_update( :param autoscale_setting_name: The autoscale setting name. Required. :type autoscale_setting_name: str :param parameters: Parameters supplied to the operation. Is either a AutoscaleSettingResource - type or a IO type. Required. - :type parameters: ~azure.mgmt.monitor.v2021_05_01_preview.models.AutoscaleSettingResource 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 + type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.monitor.v2021_05_01_preview.models.AutoscaleSettingResource or + IO[bytes] :return: AutoscaleSettingResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_05_01_preview.models.AutoscaleSettingResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -431,19 +424,21 @@ def create_or_update( _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", "2021-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-05-01-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.AutoscaleSettingResource] = 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, "AutoscaleSettingResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, autoscale_setting_name=autoscale_setting_name, subscription_id=self._config.subscription_id, @@ -451,16 +446,14 @@ def create_or_update( 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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -470,21 +463,13 @@ def create_or_update( error = self._deserialize.failsafe_deserialize(_models.AutoscaleErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if response.status_code == 200: - deserialized = self._deserialize("AutoscaleSettingResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("AutoscaleSettingResource", pipeline_response) + deserialized = self._deserialize("AutoscaleSettingResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/autoscalesettings/{autoscaleSettingName}" - } - @distributed_trace def delete( # pylint: disable=inconsistent-return-statements self, resource_group_name: str, autoscale_setting_name: str, **kwargs: Any @@ -496,12 +481,11 @@ def delete( # pylint: disable=inconsistent-return-statements :type resource_group_name: str :param autoscale_setting_name: The autoscale setting name. Required. :type autoscale_setting_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, @@ -512,24 +496,24 @@ def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-05-01-preview") + ) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, autoscale_setting_name=autoscale_setting_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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -540,11 +524,7 @@ def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/autoscalesettings/{autoscaleSettingName}" - } + return cls(pipeline_response, None, {}) # type: ignore @distributed_trace def get( @@ -557,12 +537,11 @@ def get( :type resource_group_name: str :param autoscale_setting_name: The autoscale setting name. Required. :type autoscale_setting_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: AutoscaleSettingResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_05_01_preview.models.AutoscaleSettingResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -573,24 +552,24 @@ def get( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-05-01-preview") + ) cls: ClsType[_models.AutoscaleSettingResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, autoscale_setting_name=autoscale_setting_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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -600,16 +579,12 @@ def get( error = self._deserialize.failsafe_deserialize(_models.AutoscaleErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("AutoscaleSettingResource", pipeline_response) + deserialized = self._deserialize("AutoscaleSettingResource", 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.Insights/autoscalesettings/{autoscaleSettingName}" - } + return deserialized # type: ignore @overload def update( @@ -635,7 +610,6 @@ def update( :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: AutoscaleSettingResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_05_01_preview.models.AutoscaleSettingResource :raises ~azure.core.exceptions.HttpResponseError: @@ -646,7 +620,7 @@ def update( self, resource_group_name: str, autoscale_setting_name: str, - autoscale_setting_resource: IO, + autoscale_setting_resource: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -660,11 +634,10 @@ def update( :param autoscale_setting_name: The autoscale setting name. Required. :type autoscale_setting_name: str :param autoscale_setting_resource: Parameters supplied to the operation. Required. - :type autoscale_setting_resource: IO + :type autoscale_setting_resource: 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: AutoscaleSettingResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_05_01_preview.models.AutoscaleSettingResource :raises ~azure.core.exceptions.HttpResponseError: @@ -675,7 +648,7 @@ def update( self, resource_group_name: str, autoscale_setting_name: str, - autoscale_setting_resource: Union[_models.AutoscaleSettingResourcePatch, IO], + autoscale_setting_resource: Union[_models.AutoscaleSettingResourcePatch, IO[bytes]], **kwargs: Any ) -> _models.AutoscaleSettingResource: """Updates an existing AutoscaleSettingsResource. To update other fields use the CreateOrUpdate @@ -687,18 +660,14 @@ def update( :param autoscale_setting_name: The autoscale setting name. Required. :type autoscale_setting_name: str :param autoscale_setting_resource: Parameters supplied to the operation. Is either a - AutoscaleSettingResourcePatch type or a IO type. Required. + AutoscaleSettingResourcePatch type or a IO[bytes] type. Required. :type autoscale_setting_resource: - ~azure.mgmt.monitor.v2021_05_01_preview.models.AutoscaleSettingResourcePatch 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 + ~azure.mgmt.monitor.v2021_05_01_preview.models.AutoscaleSettingResourcePatch or IO[bytes] :return: AutoscaleSettingResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_05_01_preview.models.AutoscaleSettingResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -709,19 +678,21 @@ def update( _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", "2021-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-05-01-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.AutoscaleSettingResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(autoscale_setting_resource, (IO, bytes)): + if isinstance(autoscale_setting_resource, (IOBase, bytes)): _content = autoscale_setting_resource else: _json = self._serialize.body(autoscale_setting_resource, "AutoscaleSettingResourcePatch") - request = build_update_request( + _request = build_update_request( resource_group_name=resource_group_name, autoscale_setting_name=autoscale_setting_name, subscription_id=self._config.subscription_id, @@ -729,16 +700,14 @@ def update( 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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -748,22 +717,17 @@ def update( error = self._deserialize.failsafe_deserialize(_models.AutoscaleErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("AutoscaleSettingResource", pipeline_response) + deserialized = self._deserialize("AutoscaleSettingResource", 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.Insights/autoscalesettings/{autoscaleSettingName}" - } + return deserialized # type: ignore @distributed_trace def list_by_subscription(self, **kwargs: Any) -> Iterable["_models.AutoscaleSettingResource"]: """Lists the autoscale settings for a subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either AutoscaleSettingResource or the result of cls(response) :rtype: @@ -773,10 +737,12 @@ def list_by_subscription(self, **kwargs: Any) -> Iterable["_models.AutoscaleSett _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-05-01-preview") + ) cls: ClsType[_models.AutoscaleSettingResourceCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -787,15 +753,13 @@ def list_by_subscription(self, **kwargs: Any) -> Iterable["_models.AutoscaleSett def prepare_request(next_link=None): if not next_link: - request = build_list_by_subscription_request( + _request = build_list_by_subscription_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_subscription.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -806,14 +770,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("AutoscaleSettingResourceCollection", pipeline_response) @@ -823,11 +786,11 @@ def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -839,7 +802,3 @@ def get_next(next_link=None): return pipeline_response return ItemPaged(get_next, extract_data) - - list_by_subscription.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/autoscalesettings" - } diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/operations/_diagnostic_settings_category_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/operations/_diagnostic_settings_category_operations.py index f2b7d0147522..e041a9e3e85b 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/operations/_diagnostic_settings_category_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/operations/_diagnostic_settings_category_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,7 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, Callable, Dict, Iterable, Optional, TypeVar import urllib.parse @@ -19,16 +19,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, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -50,7 +52,7 @@ def build_get_request(resource_uri: str, name: str, **kwargs: Any) -> HttpReques "name": _SERIALIZER.url("name", name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -74,7 +76,7 @@ def build_list_request(resource_uri: str, **kwargs: Any) -> HttpRequest: "resourceUri": _SERIALIZER.url("resource_uri", resource_uri, "str", skip_quote=True), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -103,6 +105,7 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def get(self, resource_uri: str, name: str, **kwargs: Any) -> _models.DiagnosticSettingsCategoryResource: @@ -112,12 +115,11 @@ def get(self, resource_uri: str, name: str, **kwargs: Any) -> _models.Diagnostic :type resource_uri: str :param name: The name of the diagnostic setting. Required. :type name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: DiagnosticSettingsCategoryResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_05_01_preview.models.DiagnosticSettingsCategoryResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -128,23 +130,23 @@ def get(self, resource_uri: str, name: str, **kwargs: Any) -> _models.Diagnostic _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-05-01-preview") + ) cls: ClsType[_models.DiagnosticSettingsCategoryResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_uri=resource_uri, name=name, api_version=api_version, - template_url=self.get.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -154,14 +156,12 @@ def get(self, resource_uri: str, name: str, **kwargs: Any) -> _models.Diagnostic error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("DiagnosticSettingsCategoryResource", pipeline_response) + deserialized = self._deserialize("DiagnosticSettingsCategoryResource", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get.metadata = {"url": "/{resourceUri}/providers/Microsoft.Insights/diagnosticSettingsCategories/{name}"} + return deserialized # type: ignore @distributed_trace def list(self, resource_uri: str, **kwargs: Any) -> Iterable["_models.DiagnosticSettingsCategoryResource"]: @@ -169,7 +169,6 @@ def list(self, resource_uri: str, **kwargs: Any) -> Iterable["_models.Diagnostic :param resource_uri: The identifier of the resource. Required. :type resource_uri: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either DiagnosticSettingsCategoryResource or the result of cls(response) :rtype: @@ -179,10 +178,12 @@ def list(self, resource_uri: str, **kwargs: Any) -> Iterable["_models.Diagnostic _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-05-01-preview") + ) cls: ClsType[_models.DiagnosticSettingsCategoryResourceCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -193,15 +194,13 @@ def list(self, resource_uri: str, **kwargs: Any) -> Iterable["_models.Diagnostic def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( resource_uri=resource_uri, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -212,14 +211,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("DiagnosticSettingsCategoryResourceCollection", pipeline_response) @@ -229,11 +227,11 @@ def extract_data(pipeline_response): return None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -245,5 +243,3 @@ def get_next(next_link=None): return pipeline_response return ItemPaged(get_next, extract_data) - - list.metadata = {"url": "/{resourceUri}/providers/Microsoft.Insights/diagnosticSettingsCategories"} diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/operations/_diagnostic_settings_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/operations/_diagnostic_settings_operations.py index c7e8b738b8fd..4b2f24be0d5c 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/operations/_diagnostic_settings_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/operations/_diagnostic_settings_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload import urllib.parse @@ -19,16 +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, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -50,7 +53,7 @@ def build_get_request(resource_uri: str, name: str, **kwargs: Any) -> HttpReques "name": _SERIALIZER.url("name", name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -76,7 +79,7 @@ def build_create_or_update_request(resource_uri: str, name: str, **kwargs: Any) "name": _SERIALIZER.url("name", name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -103,7 +106,7 @@ def build_delete_request(resource_uri: str, name: str, **kwargs: Any) -> HttpReq "name": _SERIALIZER.url("name", name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -127,7 +130,7 @@ def build_list_request(resource_uri: str, **kwargs: Any) -> HttpRequest: "resourceUri": _SERIALIZER.url("resource_uri", resource_uri, "str", skip_quote=True), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -156,6 +159,7 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def get(self, resource_uri: str, name: str, **kwargs: Any) -> _models.DiagnosticSettingsResource: @@ -165,12 +169,11 @@ def get(self, resource_uri: str, name: str, **kwargs: Any) -> _models.Diagnostic :type resource_uri: str :param name: The name of the diagnostic setting. Required. :type name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: DiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_05_01_preview.models.DiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -181,23 +184,23 @@ def get(self, resource_uri: str, name: str, **kwargs: Any) -> _models.Diagnostic _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-05-01-preview") + ) cls: ClsType[_models.DiagnosticSettingsResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_uri=resource_uri, name=name, api_version=api_version, - template_url=self.get.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -207,14 +210,12 @@ def get(self, resource_uri: str, name: str, **kwargs: Any) -> _models.Diagnostic error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("DiagnosticSettingsResource", pipeline_response) + deserialized = self._deserialize("DiagnosticSettingsResource", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get.metadata = {"url": "/{resourceUri}/providers/Microsoft.Insights/diagnosticSettings/{name}"} + return deserialized # type: ignore @overload def create_or_update( @@ -237,7 +238,6 @@ def create_or_update( :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: DiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_05_01_preview.models.DiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: @@ -245,7 +245,13 @@ def create_or_update( @overload def create_or_update( - self, resource_uri: str, name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + self, + resource_uri: str, + name: str, + parameters: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any ) -> _models.DiagnosticSettingsResource: """Creates or updates diagnostic settings for the specified resource. @@ -254,11 +260,10 @@ def create_or_update( :param name: The name of the diagnostic setting. Required. :type name: str :param parameters: Parameters supplied to the operation. Required. - :type parameters: IO + :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: DiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_05_01_preview.models.DiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: @@ -266,7 +271,11 @@ def create_or_update( @distributed_trace def create_or_update( - self, resource_uri: str, name: str, parameters: Union[_models.DiagnosticSettingsResource, IO], **kwargs: Any + self, + resource_uri: str, + name: str, + parameters: Union[_models.DiagnosticSettingsResource, IO[bytes]], + **kwargs: Any ) -> _models.DiagnosticSettingsResource: """Creates or updates diagnostic settings for the specified resource. @@ -275,18 +284,14 @@ def create_or_update( :param name: The name of the diagnostic setting. Required. :type name: str :param parameters: Parameters supplied to the operation. Is either a DiagnosticSettingsResource - type or a IO type. Required. + type or a IO[bytes] type. Required. :type parameters: ~azure.mgmt.monitor.v2021_05_01_preview.models.DiagnosticSettingsResource 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 + IO[bytes] :return: DiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_05_01_preview.models.DiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -297,35 +302,35 @@ def create_or_update( _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", "2021-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-05-01-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.DiagnosticSettingsResource] = 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, "DiagnosticSettingsResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_uri=resource_uri, name=name, 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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -335,14 +340,12 @@ def create_or_update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("DiagnosticSettingsResource", pipeline_response) + deserialized = self._deserialize("DiagnosticSettingsResource", 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": "/{resourceUri}/providers/Microsoft.Insights/diagnosticSettings/{name}"} + return deserialized # type: ignore @distributed_trace def delete( # pylint: disable=inconsistent-return-statements @@ -354,12 +357,11 @@ def delete( # pylint: disable=inconsistent-return-statements :type resource_uri: str :param name: The name of the diagnostic setting. Required. :type 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, @@ -370,23 +372,23 @@ def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-05-01-preview") + ) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_uri=resource_uri, name=name, api_version=api_version, - template_url=self.delete.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -397,9 +399,7 @@ def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = {"url": "/{resourceUri}/providers/Microsoft.Insights/diagnosticSettings/{name}"} + return cls(pipeline_response, None, {}) # type: ignore @distributed_trace def list(self, resource_uri: str, **kwargs: Any) -> Iterable["_models.DiagnosticSettingsResource"]: @@ -407,7 +407,6 @@ def list(self, resource_uri: str, **kwargs: Any) -> Iterable["_models.Diagnostic :param resource_uri: The identifier of the resource. Required. :type resource_uri: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either DiagnosticSettingsResource or the result of cls(response) :rtype: @@ -417,10 +416,12 @@ def list(self, resource_uri: str, **kwargs: Any) -> Iterable["_models.Diagnostic _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-05-01-preview") + ) cls: ClsType[_models.DiagnosticSettingsResourceCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -431,15 +432,13 @@ def list(self, resource_uri: str, **kwargs: Any) -> Iterable["_models.Diagnostic def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( resource_uri=resource_uri, api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -450,14 +449,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("DiagnosticSettingsResourceCollection", pipeline_response) @@ -467,11 +465,11 @@ def extract_data(pipeline_response): return None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -483,5 +481,3 @@ def get_next(next_link=None): return pipeline_response return ItemPaged(get_next, extract_data) - - list.metadata = {"url": "/{resourceUri}/providers/Microsoft.Insights/diagnosticSettings"} diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/operations/_management_group_diagnostic_settings_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/operations/_management_group_diagnostic_settings_operations.py index 339da6755347..d326043a44b9 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/operations/_management_group_diagnostic_settings_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/operations/_management_group_diagnostic_settings_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload import urllib.parse @@ -19,16 +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, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -53,7 +56,7 @@ def build_get_request(management_group_id: str, name: str, **kwargs: Any) -> Htt "name": _SERIALIZER.url("name", name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -82,7 +85,7 @@ def build_create_or_update_request(management_group_id: str, name: str, **kwargs "name": _SERIALIZER.url("name", name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -112,7 +115,7 @@ def build_delete_request(management_group_id: str, name: str, **kwargs: Any) -> "name": _SERIALIZER.url("name", name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -139,7 +142,7 @@ def build_list_request(management_group_id: str, **kwargs: Any) -> HttpRequest: "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str", skip_quote=True), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -150,7 +153,7 @@ def build_list_request(management_group_id: str, **kwargs: Any) -> HttpRequest: return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -class ManagementGroupDiagnosticSettingsOperations: +class ManagementGroupDiagnosticSettingsOperations: # pylint: disable=name-too-long """ .. warning:: **DO NOT** instantiate this class directly. @@ -168,6 +171,7 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def get( @@ -179,13 +183,12 @@ def get( :type management_group_id: str :param name: The name of the diagnostic setting. Required. :type name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ManagementGroupDiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_05_01_preview.models.ManagementGroupDiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -196,23 +199,23 @@ def get( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-05-01-preview") + ) cls: ClsType[_models.ManagementGroupDiagnosticSettingsResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( management_group_id=management_group_id, name=name, api_version=api_version, - template_url=self.get.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -222,16 +225,12 @@ def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ManagementGroupDiagnosticSettingsResource", pipeline_response) + deserialized = self._deserialize("ManagementGroupDiagnosticSettingsResource", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get.metadata = { - "url": "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Insights/diagnosticSettings/{name}" - } + return deserialized # type: ignore @overload def create_or_update( @@ -255,7 +254,6 @@ def create_or_update( :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: ManagementGroupDiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_05_01_preview.models.ManagementGroupDiagnosticSettingsResource @@ -267,7 +265,7 @@ def create_or_update( self, management_group_id: str, name: str, - parameters: IO, + parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -279,11 +277,10 @@ def create_or_update( :param name: The name of the diagnostic setting. Required. :type name: str :param parameters: Parameters supplied to the operation. Required. - :type parameters: IO + :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: ManagementGroupDiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_05_01_preview.models.ManagementGroupDiagnosticSettingsResource @@ -295,7 +292,7 @@ def create_or_update( self, management_group_id: str, name: str, - parameters: Union[_models.ManagementGroupDiagnosticSettingsResource, IO], + parameters: Union[_models.ManagementGroupDiagnosticSettingsResource, IO[bytes]], **kwargs: Any ) -> _models.ManagementGroupDiagnosticSettingsResource: """Creates or updates management group diagnostic settings for the specified resource. @@ -305,19 +302,16 @@ def create_or_update( :param name: The name of the diagnostic setting. Required. :type name: str :param parameters: Parameters supplied to the operation. Is either a - ManagementGroupDiagnosticSettingsResource type or a IO type. Required. + ManagementGroupDiagnosticSettingsResource type or a IO[bytes] type. Required. :type parameters: - ~azure.mgmt.monitor.v2021_05_01_preview.models.ManagementGroupDiagnosticSettingsResource 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 + ~azure.mgmt.monitor.v2021_05_01_preview.models.ManagementGroupDiagnosticSettingsResource or + IO[bytes] :return: ManagementGroupDiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_05_01_preview.models.ManagementGroupDiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -328,35 +322,35 @@ def create_or_update( _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", "2021-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-05-01-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ManagementGroupDiagnosticSettingsResource] = 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, "ManagementGroupDiagnosticSettingsResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( management_group_id=management_group_id, name=name, 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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -366,16 +360,12 @@ def create_or_update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ManagementGroupDiagnosticSettingsResource", pipeline_response) + deserialized = self._deserialize("ManagementGroupDiagnosticSettingsResource", 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": "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Insights/diagnosticSettings/{name}" - } + return deserialized # type: ignore @distributed_trace def delete( # pylint: disable=inconsistent-return-statements @@ -387,12 +377,11 @@ def delete( # pylint: disable=inconsistent-return-statements :type management_group_id: str :param name: The name of the diagnostic setting. Required. :type 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, @@ -403,23 +392,23 @@ def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-05-01-preview") + ) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( management_group_id=management_group_id, name=name, api_version=api_version, - template_url=self.delete.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -430,21 +419,17 @@ def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Insights/diagnosticSettings/{name}" - } + return cls(pipeline_response, None, {}) # type: ignore @distributed_trace def list( self, management_group_id: str, **kwargs: Any ) -> Iterable["_models.ManagementGroupDiagnosticSettingsResource"]: + # pylint: disable=line-too-long """Gets the active management group diagnostic settings list for the specified management group. :param management_group_id: The management group id. Required. :type management_group_id: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ManagementGroupDiagnosticSettingsResource or the result of cls(response) :rtype: @@ -454,10 +439,12 @@ def list( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-05-01-preview") + ) cls: ClsType[_models.ManagementGroupDiagnosticSettingsResourceCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -468,15 +455,13 @@ def list( def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( management_group_id=management_group_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) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -487,14 +472,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("ManagementGroupDiagnosticSettingsResourceCollection", pipeline_response) @@ -504,11 +488,11 @@ def extract_data(pipeline_response): return None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -520,7 +504,3 @@ def get_next(next_link=None): return pipeline_response return ItemPaged(get_next, extract_data) - - list.metadata = { - "url": "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Insights/diagnosticSettings" - } diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/operations/_predictive_metric_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/operations/_predictive_metric_operations.py index a3f0a967046d..25e45b370dde 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/operations/_predictive_metric_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/operations/_predictive_metric_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +6,7 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- import datetime +import sys from typing import Any, Callable, Dict, Optional, TypeVar from azure.core.exceptions import ( @@ -18,16 +18,18 @@ map_error, ) 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 +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -66,7 +68,7 @@ def build_get_request( "autoscaleSettingName": _SERIALIZER.url("autoscale_setting_name", autoscale_setting_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["timespan"] = _SERIALIZER.query("timespan", timespan, "str") @@ -100,6 +102,7 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def get( @@ -133,12 +136,11 @@ def get( :type metric_name: str :param aggregation: The list of aggregation types (comma separated) to retrieve. Required. :type aggregation: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: PredictiveResponse or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_05_01_preview.models.PredictiveResponse :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -149,10 +151,12 @@ def get( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-05-01-preview") + ) cls: ClsType[_models.PredictiveResponse] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, autoscale_setting_name=autoscale_setting_name, subscription_id=self._config.subscription_id, @@ -162,16 +166,14 @@ def get( metric_name=metric_name, aggregation=aggregation, api_version=api_version, - template_url=self.get.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -181,13 +183,9 @@ def get( error = self._deserialize.failsafe_deserialize(_models.AutoscaleErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("PredictiveResponse", pipeline_response) + deserialized = self._deserialize("PredictiveResponse", 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.Insights/autoscalesettings/{autoscaleSettingName}/predictiveMetrics" - } + return deserialized # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/operations/_subscription_diagnostic_settings_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/operations/_subscription_diagnostic_settings_operations.py index 64d625a3b2f1..646f57397614 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/operations/_subscription_diagnostic_settings_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_05_01_preview/operations/_subscription_diagnostic_settings_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload import urllib.parse @@ -19,16 +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, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -52,7 +55,7 @@ def build_get_request(name: str, subscription_id: str, **kwargs: Any) -> HttpReq "name": _SERIALIZER.url("name", name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -80,7 +83,7 @@ def build_create_or_update_request(name: str, subscription_id: str, **kwargs: An "name": _SERIALIZER.url("name", name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -109,7 +112,7 @@ def build_delete_request(name: str, subscription_id: str, **kwargs: Any) -> Http "name": _SERIALIZER.url("name", name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -133,7 +136,7 @@ def build_list_request(subscription_id: str, **kwargs: Any) -> HttpRequest: "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -162,6 +165,7 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def get(self, name: str, **kwargs: Any) -> _models.SubscriptionDiagnosticSettingsResource: @@ -169,12 +173,11 @@ def get(self, name: str, **kwargs: Any) -> _models.SubscriptionDiagnosticSetting :param name: The name of the diagnostic setting. Required. :type name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: SubscriptionDiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_05_01_preview.models.SubscriptionDiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -185,23 +188,23 @@ def get(self, name: str, **kwargs: Any) -> _models.SubscriptionDiagnosticSetting _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-05-01-preview") + ) cls: ClsType[_models.SubscriptionDiagnosticSettingsResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( name=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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -211,14 +214,12 @@ def get(self, name: str, **kwargs: Any) -> _models.SubscriptionDiagnosticSetting error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("SubscriptionDiagnosticSettingsResource", pipeline_response) + deserialized = self._deserialize("SubscriptionDiagnosticSettingsResource", 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}/providers/Microsoft.Insights/diagnosticSettings/{name}"} + return deserialized # type: ignore @overload def create_or_update( @@ -239,7 +240,6 @@ def create_or_update( :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: SubscriptionDiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_05_01_preview.models.SubscriptionDiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: @@ -247,18 +247,17 @@ def create_or_update( @overload def create_or_update( - self, name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + self, name: str, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any ) -> _models.SubscriptionDiagnosticSettingsResource: """Creates or updates subscription diagnostic settings for the specified resource. :param name: The name of the diagnostic setting. Required. :type name: str :param parameters: Parameters supplied to the operation. Required. - :type parameters: IO + :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: SubscriptionDiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_05_01_preview.models.SubscriptionDiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: @@ -266,25 +265,22 @@ def create_or_update( @distributed_trace def create_or_update( - self, name: str, parameters: Union[_models.SubscriptionDiagnosticSettingsResource, IO], **kwargs: Any + self, name: str, parameters: Union[_models.SubscriptionDiagnosticSettingsResource, IO[bytes]], **kwargs: Any ) -> _models.SubscriptionDiagnosticSettingsResource: """Creates or updates subscription diagnostic settings for the specified resource. :param name: The name of the diagnostic setting. Required. :type name: str :param parameters: Parameters supplied to the operation. Is either a - SubscriptionDiagnosticSettingsResource type or a IO type. Required. + SubscriptionDiagnosticSettingsResource type or a IO[bytes] type. Required. :type parameters: - ~azure.mgmt.monitor.v2021_05_01_preview.models.SubscriptionDiagnosticSettingsResource 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 + ~azure.mgmt.monitor.v2021_05_01_preview.models.SubscriptionDiagnosticSettingsResource or + IO[bytes] :return: SubscriptionDiagnosticSettingsResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_05_01_preview.models.SubscriptionDiagnosticSettingsResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -295,35 +291,35 @@ def create_or_update( _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", "2021-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-05-01-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.SubscriptionDiagnosticSettingsResource] = 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, "SubscriptionDiagnosticSettingsResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( name=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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -333,16 +329,12 @@ def create_or_update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("SubscriptionDiagnosticSettingsResource", pipeline_response) + deserialized = self._deserialize("SubscriptionDiagnosticSettingsResource", 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}/providers/Microsoft.Insights/diagnosticSettings/{name}" - } + return deserialized # type: ignore @distributed_trace def delete(self, name: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements @@ -350,12 +342,11 @@ def delete(self, name: str, **kwargs: Any) -> None: # pylint: disable=inconsist :param name: The name of the diagnostic setting. Required. :type 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, @@ -366,23 +357,23 @@ def delete(self, name: str, **kwargs: Any) -> None: # pylint: disable=inconsist _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-05-01-preview") + ) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( name=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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -393,15 +384,13 @@ def delete(self, name: str, **kwargs: Any) -> None: # pylint: disable=inconsist raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/diagnosticSettings/{name}"} + return cls(pipeline_response, None, {}) # type: ignore @distributed_trace def list(self, **kwargs: Any) -> Iterable["_models.SubscriptionDiagnosticSettingsResource"]: + # pylint: disable=line-too-long """Gets the active subscription diagnostic settings list for the specified subscriptionId. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either SubscriptionDiagnosticSettingsResource or the result of cls(response) :rtype: @@ -411,10 +400,12 @@ def list(self, **kwargs: Any) -> Iterable["_models.SubscriptionDiagnosticSetting _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-05-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-05-01-preview") + ) cls: ClsType[_models.SubscriptionDiagnosticSettingsResourceCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -425,15 +416,13 @@ def list(self, **kwargs: Any) -> Iterable["_models.SubscriptionDiagnosticSetting def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _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) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -444,14 +433,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("SubscriptionDiagnosticSettingsResourceCollection", pipeline_response) @@ -461,11 +449,11 @@ def extract_data(pipeline_response): return None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -477,5 +465,3 @@ def get_next(next_link=None): return pipeline_response return ItemPaged(get_next, extract_data) - - list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/diagnosticSettings"} diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/__init__.py index 2c7733bfd566..42cc62301757 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/__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 ._monitor_management_client import MonitorManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._monitor_management_client import MonitorManagementClient # type: ignore from ._version import VERSION __version__ = VERSION try: from ._patch import __all__ as _patch_all - from ._patch import * # 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__ = [ "MonitorManagementClient", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/_configuration.py index 31e53c133145..e4f8b2c0d517 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/_configuration.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/_configuration.py @@ -8,18 +8,16 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy from ._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MonitorManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class MonitorManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for MonitorManagementClient. Note that all parameters used to create this instance are saved as instance @@ -35,7 +33,6 @@ class MonitorManagementClientConfiguration(Configuration): # pylint: disable=to """ def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: - super(MonitorManagementClientConfiguration, self).__init__(**kwargs) api_version: str = kwargs.pop("api_version", "2021-06-03-preview") if credential is None: @@ -48,6 +45,7 @@ def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-monitor/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -56,9 +54,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.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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/_metadata.json b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/_metadata.json index eb89105a0203..639ccf0b6acc 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/_metadata.json +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/_metadata.json @@ -8,10 +8,10 @@ "host_value": "\"https://management.azure.com\"", "parameterized_host_template": null, "azure_arm": true, - "has_lro_operations": false, + "has_public_lro_operations": false, "client_side_validation": false, - "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"sdkcore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMAutoResourceProviderRegistrationPolicy\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}, \"stdlib\": {\"typing_extensions\": [\"Self\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"sdkcore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"AsyncARMAutoResourceProviderRegistrationPolicy\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}, \"stdlib\": {\"typing_extensions\": [\"Self\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "global_parameters": { "sync": { @@ -101,8 +101,8 @@ "credential_scopes": ["https://management.azure.com/.default"], "credential_call_sync": "ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", "credential_call_async": "AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", - "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "sync_imports": "{\"regular\": {\"sdkcore\": {\"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"regular\": {\"sdkcore\": {\"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "operation_groups": { "azure_monitor_workspaces": "AzureMonitorWorkspacesOperations", diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/_monitor_management_client.py index 609fd0d55392..513d16d1eb2f 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/_monitor_management_client.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/_monitor_management_client.py @@ -8,9 +8,12 @@ from copy import deepcopy from typing import Any, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient +from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy from . import models as _models from .._serialization import Deserializer, Serializer @@ -18,11 +21,10 @@ from .operations import AzureMonitorWorkspacesOperations, MonitorOperationsOperations if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MonitorManagementClient: # pylint: disable=client-accepts-api-version-keyword +class MonitorManagementClient: """Monitor Management Client. :ivar azure_monitor_workspaces: AzureMonitorWorkspacesOperations operations @@ -52,20 +54,38 @@ def __init__( self._config = MonitorManagementClientConfiguration( credential=credential, subscription_id=subscription_id, **kwargs ) - self._client: ARMPipelineClient = ARMPipelineClient(base_url=base_url, config=self._config, **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), + 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=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.azure_monitor_workspaces = AzureMonitorWorkspacesOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2021-06-03-preview" ) self.monitor_operations = MonitorOperationsOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2021-06-03-preview" ) - 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 @@ -85,12 +105,12 @@ 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) -> None: self._client.close() - def __enter__(self) -> "MonitorManagementClient": + def __enter__(self) -> Self: self._client.__enter__() return self diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/_vendor.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/_vendor.py deleted file mode 100644 index bd0df84f5319..000000000000 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/_vendor.py +++ /dev/null @@ -1,30 +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 typing import List, cast - -from azure.core.pipeline.transport import HttpRequest - - -def _convert_request(request, files=None): - data = request.content if not files else None - request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) - if files: - request.set_formdata_body(files) - return request - - -def _format_url_section(template, **kwargs): - components = template.split("/") - while components: - try: - return template.format(**kwargs) - except KeyError as key: - # Need the cast, as for some reasons "split" is typed as list[str | Any] - formatted_components = cast(List[str], template.split("/")) - components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] - template = "/".join(components) diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/_version.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/_version.py index 394ee7c0c03c..e5754a47ce68 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/_version.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "6.0.2" +VERSION = "1.0.0b1" diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/aio/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/aio/__init__.py index 2c151bb41c19..3df30ff42149 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/aio/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/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 ._monitor_management_client import MonitorManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._monitor_management_client import MonitorManagementClient # type: ignore try: from ._patch import __all__ as _patch_all - from ._patch import * # 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__ = [ "MonitorManagementClient", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/aio/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/aio/_configuration.py index 798865c55f15..ae245f837593 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/aio/_configuration.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/aio/_configuration.py @@ -8,18 +8,16 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy from .._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MonitorManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class MonitorManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for MonitorManagementClient. Note that all parameters used to create this instance are saved as instance @@ -35,7 +33,6 @@ class MonitorManagementClientConfiguration(Configuration): # pylint: disable=to """ def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: - super(MonitorManagementClientConfiguration, self).__init__(**kwargs) api_version: str = kwargs.pop("api_version", "2021-06-03-preview") if credential is None: @@ -48,6 +45,7 @@ def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **k self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-monitor/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -56,9 +54,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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/aio/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/aio/_monitor_management_client.py index d510d97f581b..04fb38898a79 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/aio/_monitor_management_client.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/aio/_monitor_management_client.py @@ -8,9 +8,12 @@ from copy import deepcopy from typing import Any, Awaitable, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient +from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy from .. import models as _models from ..._serialization import Deserializer, Serializer @@ -18,11 +21,10 @@ from .operations import AzureMonitorWorkspacesOperations, MonitorOperationsOperations if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MonitorManagementClient: # pylint: disable=client-accepts-api-version-keyword +class MonitorManagementClient: """Monitor Management Client. :ivar azure_monitor_workspaces: AzureMonitorWorkspacesOperations operations @@ -52,20 +54,40 @@ def __init__( self._config = MonitorManagementClientConfiguration( credential=credential, subscription_id=subscription_id, **kwargs ) - self._client: AsyncARMPipelineClient = AsyncARMPipelineClient(base_url=base_url, config=self._config, **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=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.azure_monitor_workspaces = AzureMonitorWorkspacesOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2021-06-03-preview" ) self.monitor_operations = MonitorOperationsOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2021-06-03-preview" ) - 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 @@ -85,12 +107,12 @@ 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) -> "MonitorManagementClient": + async def __aenter__(self) -> Self: await self._client.__aenter__() return self diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/aio/operations/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/aio/operations/__init__.py index cc4f2ca90de6..2d767ded4d32 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/aio/operations/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/aio/operations/__init__.py @@ -5,17 +5,23 @@ # 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 ._azure_monitor_workspaces_operations import AzureMonitorWorkspacesOperations -from ._monitor_operations_operations import MonitorOperationsOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._azure_monitor_workspaces_operations import AzureMonitorWorkspacesOperations # type: ignore +from ._monitor_operations_operations import MonitorOperationsOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ "AzureMonitorWorkspacesOperations", "MonitorOperationsOperations", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/aio/operations/_azure_monitor_workspaces_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/aio/operations/_azure_monitor_workspaces_operations.py index 5fe2ed9588a8..2e5583c4d8b5 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/aio/operations/_azure_monitor_workspaces_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/aio/operations/_azure_monitor_workspaces_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload import urllib.parse @@ -19,15 +20,13 @@ 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 ...operations._azure_monitor_workspaces_operations import ( build_create_request, build_delete_request, @@ -37,6 +36,10 @@ build_update_request, ) +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -59,17 +62,18 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list_by_resource_group( self, resource_group_name: str, **kwargs: Any ) -> AsyncIterable["_models.AzureMonitorWorkspaceResource"]: - """Lists all workspaces in the specified resource group. + # pylint: disable=line-too-long + """Lists all Azure Monitor Workspaces in the specified resource group. :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either AzureMonitorWorkspaceResource or the result of cls(response) :rtype: @@ -79,10 +83,12 @@ def list_by_resource_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-06-03-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-06-03-preview") + ) cls: ClsType[_models.AzureMonitorWorkspaceResourceListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -93,16 +99,14 @@ 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_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -113,14 +117,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("AzureMonitorWorkspaceResourceListResult", pipeline_response) @@ -130,11 +133,11 @@ async def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -147,15 +150,11 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Monitor/accounts" - } - @distributed_trace def list_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.AzureMonitorWorkspaceResource"]: - """Lists all workspaces in the specified subscription. + # pylint: disable=line-too-long + """Lists all Azure Monitor Workspaces in the specified subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either AzureMonitorWorkspaceResource or the result of cls(response) :rtype: @@ -165,10 +164,12 @@ def list_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.AzureMon _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-06-03-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-06-03-preview") + ) cls: ClsType[_models.AzureMonitorWorkspaceResourceListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -179,15 +180,13 @@ def list_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.AzureMon def prepare_request(next_link=None): if not next_link: - request = build_list_by_subscription_request( + _request = build_list_by_subscription_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_subscription.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -198,14 +197,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("AzureMonitorWorkspaceResourceListResult", pipeline_response) @@ -215,11 +213,11 @@ async def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -232,26 +230,23 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_by_subscription.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Monitor/accounts"} - @distributed_trace_async async def get( self, resource_group_name: str, azure_monitor_workspace_name: str, **kwargs: Any ) -> _models.AzureMonitorWorkspaceResource: - """Returns the specific Azure Monitor workspace. + """Returns the specified Azure Monitor Workspace. :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :param azure_monitor_workspace_name: The name of the Azure Monitor workspace. The name is case + :param azure_monitor_workspace_name: The name of the Azure Monitor Workspace. The name is case insensitive. Required. :type azure_monitor_workspace_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: AzureMonitorWorkspaceResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_06_03_preview.models.AzureMonitorWorkspaceResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -262,24 +257,24 @@ async def get( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-06-03-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-06-03-preview") + ) cls: ClsType[_models.AzureMonitorWorkspaceResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, azure_monitor_workspace_name=azure_monitor_workspace_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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -289,16 +284,12 @@ async def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("AzureMonitorWorkspaceResource", pipeline_response) + deserialized = self._deserialize("AzureMonitorWorkspaceResource", 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.Monitor/accounts/{azureMonitorWorkspaceName}" - } + return deserialized # type: ignore @overload async def create( @@ -310,22 +301,21 @@ async def create( content_type: str = "application/json", **kwargs: Any ) -> _models.AzureMonitorWorkspaceResource: - """Create or update a workspace. + """Creates or updates an Azure Monitor Workspace. :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :param azure_monitor_workspace_name: The name of the Azure Monitor workspace. The name is case + :param azure_monitor_workspace_name: The name of the Azure Monitor Workspace. The name is case insensitive. Required. :type azure_monitor_workspace_name: str :param azure_monitor_workspace_properties: Properties that need to be specified to create a new - workspace. Required. + Azure Monitor Workspace. Required. :type azure_monitor_workspace_properties: ~azure.mgmt.monitor.v2021_06_03_preview.models.AzureMonitorWorkspaceResource :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: AzureMonitorWorkspaceResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_06_03_preview.models.AzureMonitorWorkspaceResource :raises ~azure.core.exceptions.HttpResponseError: @@ -336,26 +326,25 @@ async def create( self, resource_group_name: str, azure_monitor_workspace_name: str, - azure_monitor_workspace_properties: IO, + azure_monitor_workspace_properties: IO[bytes], *, content_type: str = "application/json", **kwargs: Any ) -> _models.AzureMonitorWorkspaceResource: - """Create or update a workspace. + """Creates or updates an Azure Monitor Workspace. :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :param azure_monitor_workspace_name: The name of the Azure Monitor workspace. The name is case + :param azure_monitor_workspace_name: The name of the Azure Monitor Workspace. The name is case insensitive. Required. :type azure_monitor_workspace_name: str :param azure_monitor_workspace_properties: Properties that need to be specified to create a new - workspace. Required. - :type azure_monitor_workspace_properties: IO + Azure Monitor Workspace. Required. + :type azure_monitor_workspace_properties: 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: AzureMonitorWorkspaceResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_06_03_preview.models.AzureMonitorWorkspaceResource :raises ~azure.core.exceptions.HttpResponseError: @@ -366,30 +355,27 @@ async def create( self, resource_group_name: str, azure_monitor_workspace_name: str, - azure_monitor_workspace_properties: Union[_models.AzureMonitorWorkspaceResource, IO], + azure_monitor_workspace_properties: Union[_models.AzureMonitorWorkspaceResource, IO[bytes]], **kwargs: Any ) -> _models.AzureMonitorWorkspaceResource: - """Create or update a workspace. + """Creates or updates an Azure Monitor Workspace. :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :param azure_monitor_workspace_name: The name of the Azure Monitor workspace. The name is case + :param azure_monitor_workspace_name: The name of the Azure Monitor Workspace. The name is case insensitive. Required. :type azure_monitor_workspace_name: str :param azure_monitor_workspace_properties: Properties that need to be specified to create a new - workspace. Is either a AzureMonitorWorkspaceResource type or a IO type. Required. + Azure Monitor Workspace. Is either a AzureMonitorWorkspaceResource type or a IO[bytes] type. + Required. :type azure_monitor_workspace_properties: - ~azure.mgmt.monitor.v2021_06_03_preview.models.AzureMonitorWorkspaceResource 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 + ~azure.mgmt.monitor.v2021_06_03_preview.models.AzureMonitorWorkspaceResource or IO[bytes] :return: AzureMonitorWorkspaceResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_06_03_preview.models.AzureMonitorWorkspaceResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -400,19 +386,21 @@ async def create( _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", "2021-06-03-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-06-03-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.AzureMonitorWorkspaceResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(azure_monitor_workspace_properties, (IO, bytes)): + if isinstance(azure_monitor_workspace_properties, (IOBase, bytes)): _content = azure_monitor_workspace_properties else: _json = self._serialize.body(azure_monitor_workspace_properties, "AzureMonitorWorkspaceResource") - request = build_create_request( + _request = build_create_request( resource_group_name=resource_group_name, azure_monitor_workspace_name=azure_monitor_workspace_name, subscription_id=self._config.subscription_id, @@ -420,16 +408,14 @@ async def create( content_type=content_type, json=_json, content=_content, - template_url=self.create.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -439,21 +425,13 @@ async def create( 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("AzureMonitorWorkspaceResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("AzureMonitorWorkspaceResource", pipeline_response) + deserialized = self._deserialize("AzureMonitorWorkspaceResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Monitor/accounts/{azureMonitorWorkspaceName}" - } - @overload async def update( self, @@ -464,12 +442,12 @@ async def update( content_type: str = "application/json", **kwargs: Any ) -> _models.AzureMonitorWorkspaceResource: - """Updates part of a workspace. + """Updates part of an Azure Monitor Workspace. :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :param azure_monitor_workspace_name: The name of the Azure Monitor workspace. The name is case + :param azure_monitor_workspace_name: The name of the Azure Monitor Workspace. The name is case insensitive. Required. :type azure_monitor_workspace_name: str :param azure_monitor_workspace_properties: The payload. Default value is None. @@ -478,7 +456,6 @@ async def update( :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: AzureMonitorWorkspaceResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_06_03_preview.models.AzureMonitorWorkspaceResource :raises ~azure.core.exceptions.HttpResponseError: @@ -489,25 +466,24 @@ async def update( self, resource_group_name: str, azure_monitor_workspace_name: str, - azure_monitor_workspace_properties: Optional[IO] = None, + azure_monitor_workspace_properties: Optional[IO[bytes]] = None, *, content_type: str = "application/json", **kwargs: Any ) -> _models.AzureMonitorWorkspaceResource: - """Updates part of a workspace. + """Updates part of an Azure Monitor Workspace. :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :param azure_monitor_workspace_name: The name of the Azure Monitor workspace. The name is case + :param azure_monitor_workspace_name: The name of the Azure Monitor Workspace. The name is case insensitive. Required. :type azure_monitor_workspace_name: str :param azure_monitor_workspace_properties: The payload. Default value is None. - :type azure_monitor_workspace_properties: IO + :type azure_monitor_workspace_properties: 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: AzureMonitorWorkspaceResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_06_03_preview.models.AzureMonitorWorkspaceResource :raises ~azure.core.exceptions.HttpResponseError: @@ -518,30 +494,29 @@ async def update( self, resource_group_name: str, azure_monitor_workspace_name: str, - azure_monitor_workspace_properties: Optional[Union[_models.AzureMonitorWorkspaceResourceForUpdate, IO]] = None, + azure_monitor_workspace_properties: Optional[ + Union[_models.AzureMonitorWorkspaceResourceForUpdate, IO[bytes]] + ] = None, **kwargs: Any ) -> _models.AzureMonitorWorkspaceResource: - """Updates part of a workspace. + """Updates part of an Azure Monitor Workspace. :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :param azure_monitor_workspace_name: The name of the Azure Monitor workspace. The name is case + :param azure_monitor_workspace_name: The name of the Azure Monitor Workspace. The name is case insensitive. Required. :type azure_monitor_workspace_name: str :param azure_monitor_workspace_properties: The payload. Is either a - AzureMonitorWorkspaceResourceForUpdate type or a IO type. Default value is None. + AzureMonitorWorkspaceResourceForUpdate type or a IO[bytes] type. Default value is None. :type azure_monitor_workspace_properties: - ~azure.mgmt.monitor.v2021_06_03_preview.models.AzureMonitorWorkspaceResourceForUpdate 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 + ~azure.mgmt.monitor.v2021_06_03_preview.models.AzureMonitorWorkspaceResourceForUpdate or + IO[bytes] :return: AzureMonitorWorkspaceResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_06_03_preview.models.AzureMonitorWorkspaceResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -552,14 +527,16 @@ async def update( _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", "2021-06-03-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-06-03-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.AzureMonitorWorkspaceResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(azure_monitor_workspace_properties, (IO, bytes)): + if isinstance(azure_monitor_workspace_properties, (IOBase, bytes)): _content = azure_monitor_workspace_properties else: if azure_monitor_workspace_properties is not None: @@ -569,7 +546,7 @@ async def update( else: _json = None - request = build_update_request( + _request = build_update_request( resource_group_name=resource_group_name, azure_monitor_workspace_name=azure_monitor_workspace_name, subscription_id=self._config.subscription_id, @@ -577,16 +554,14 @@ async def update( 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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -596,35 +571,28 @@ async def update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("AzureMonitorWorkspaceResource", pipeline_response) + deserialized = self._deserialize("AzureMonitorWorkspaceResource", 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.Monitor/accounts/{azureMonitorWorkspaceName}" - } + return deserialized # type: ignore @distributed_trace_async - async def delete( # pylint: disable=inconsistent-return-statements - self, resource_group_name: str, azure_monitor_workspace_name: str, **kwargs: Any - ) -> None: - """Delete a workspace. + async def delete(self, resource_group_name: str, azure_monitor_workspace_name: str, **kwargs: Any) -> None: + """Deletes an Azure Monitor Workspace. :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :param azure_monitor_workspace_name: The name of the Azure Monitor workspace. The name is case + :param azure_monitor_workspace_name: The name of the Azure Monitor Workspace. The name is case insensitive. Required. :type azure_monitor_workspace_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, @@ -635,24 +603,24 @@ async def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-06-03-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-06-03-preview") + ) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, azure_monitor_workspace_name=azure_monitor_workspace_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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -663,8 +631,4 @@ async def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Monitor/accounts/{azureMonitorWorkspaceName}" - } + return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/aio/operations/_monitor_operations_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/aio/operations/_monitor_operations_operations.py index 03014bb531be..d25da3167e8e 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/aio/operations/_monitor_operations_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/aio/operations/_monitor_operations_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,7 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar import urllib.parse @@ -19,16 +19,18 @@ 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 ...operations._monitor_operations_operations import build_list_request +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -51,12 +53,12 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list(self, **kwargs: Any) -> AsyncIterable["_models.Operation"]: """Lists available Operations for this Resource Provider. - :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.monitor.v2021_06_03_preview.models.Operation] @@ -65,10 +67,12 @@ def list(self, **kwargs: Any) -> AsyncIterable["_models.Operation"]: _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-06-03-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-06-03-preview") + ) cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -79,14 +83,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) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -97,14 +99,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _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) @@ -114,11 +115,11 @@ async def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -130,5 +131,3 @@ async def get_next(next_link=None): return pipeline_response return AsyncItemPaged(get_next, extract_data) - - list.metadata = {"url": "/providers/Microsoft.Monitor/operations"} diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/models/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/models/__init__.py index ed34ac23b1f5..0148dc234abd 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/models/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/models/__init__.py @@ -5,32 +5,43 @@ # 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 AzureMonitorWorkspace -from ._models_py3 import AzureMonitorWorkspaceDefaultIngestionSettings -from ._models_py3 import AzureMonitorWorkspaceMetrics -from ._models_py3 import AzureMonitorWorkspaceResource -from ._models_py3 import AzureMonitorWorkspaceResourceForUpdate -from ._models_py3 import AzureMonitorWorkspaceResourceListResult -from ._models_py3 import AzureMonitorWorkspaceResourceProperties -from ._models_py3 import ErrorAdditionalInfo -from ._models_py3 import ErrorDetail -from ._models_py3 import ErrorResponse -from ._models_py3 import IngestionSettings -from ._models_py3 import Metrics -from ._models_py3 import Operation -from ._models_py3 import OperationDisplay -from ._models_py3 import OperationListResult -from ._models_py3 import Resource -from ._models_py3 import SystemData -from ._models_py3 import TrackedResource +from typing import TYPE_CHECKING -from ._monitor_management_client_enums import ActionType -from ._monitor_management_client_enums import CreatedByType -from ._monitor_management_client_enums import Origin -from ._monitor_management_client_enums import ProvisioningState +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models_py3 import ( # type: ignore + AzureMonitorWorkspace, + AzureMonitorWorkspaceDefaultIngestionSettings, + AzureMonitorWorkspaceMetrics, + AzureMonitorWorkspaceResource, + AzureMonitorWorkspaceResourceForUpdate, + AzureMonitorWorkspaceResourceListResult, + AzureMonitorWorkspaceResourceProperties, + ErrorAdditionalInfo, + ErrorDetail, + ErrorResponse, + IngestionSettings, + Metrics, + Operation, + OperationDisplay, + OperationListResult, + Resource, + SystemData, + TrackedResource, +) + +from ._monitor_management_client_enums import ( # type: ignore + ActionType, + CreatedByType, + Origin, + ProvisioningState, +) from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ @@ -57,5 +68,5 @@ "Origin", "ProvisioningState", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/models/_models_py3.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/models/_models_py3.py index 8edc0aec3f9e..5f66eec846e7 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/models/_models_py3.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/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. @@ -13,20 +12,19 @@ from ... import _serialization if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from .. import models as _models class AzureMonitorWorkspace(_serialization.Model): - """Properties of an Azure Monitor workspace. + """Properties of an Azure Monitor Workspace. Variables are only populated by the server, and will be ignored when sending a request. - :ivar account_id: The immutable ID of the Azure Monitor workspace. This property is read-only. + :ivar account_id: The immutable Id of the Azure Monitor Workspace. This property is read-only. :vartype account_id: str - :ivar metrics: Information about metrics for the Azure Monitor workspace. + :ivar metrics: Properties related to the metrics container in the Azure Monitor Workspace. :vartype metrics: ~azure.mgmt.monitor.v2021_06_03_preview.models.AzureMonitorWorkspaceMetrics - :ivar provisioning_state: The provisioning state of the Azure Monitor workspace. Set to + :ivar provisioning_state: The provisioning state of the Azure Monitor Workspace. Set to Succeeded if everything is healthy. Known values are: "Creating", "Succeeded", "Deleting", "Failed", and "Canceled". :vartype provisioning_state: str or @@ -69,10 +67,10 @@ class IngestionSettings(_serialization.Model): Variables are only populated by the server, and will be ignored when sending a request. :ivar data_collection_rule_resource_id: The Azure resource Id of the default data collection - rule for this workspace. + rule for this Azure Monitor Workspace. :vartype data_collection_rule_resource_id: str :ivar data_collection_endpoint_resource_id: The Azure resource Id of the default data - collection endpoint for this workspace. + collection endpoint for this Azure Monitor Workspace. :vartype data_collection_endpoint_resource_id: str """ @@ -93,40 +91,26 @@ def __init__(self, **kwargs: Any) -> None: self.data_collection_endpoint_resource_id = None -class AzureMonitorWorkspaceDefaultIngestionSettings(IngestionSettings): +class AzureMonitorWorkspaceDefaultIngestionSettings(IngestionSettings): # pylint: disable=name-too-long """The Data Collection Rule and Endpoint used for ingestion by default. Variables are only populated by the server, and will be ignored when sending a request. :ivar data_collection_rule_resource_id: The Azure resource Id of the default data collection - rule for this workspace. + rule for this Azure Monitor Workspace. :vartype data_collection_rule_resource_id: str :ivar data_collection_endpoint_resource_id: The Azure resource Id of the default data - collection endpoint for this workspace. + collection endpoint for this Azure Monitor Workspace. :vartype data_collection_endpoint_resource_id: str """ - _validation = { - "data_collection_rule_resource_id": {"readonly": True}, - "data_collection_endpoint_resource_id": {"readonly": True}, - } - - _attribute_map = { - "data_collection_rule_resource_id": {"key": "dataCollectionRuleResourceId", "type": "str"}, - "data_collection_endpoint_resource_id": {"key": "dataCollectionEndpointResourceId", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - class Metrics(_serialization.Model): - """Information about metrics for the workspace. + """Properties related to the metrics container in the Azure Monitor Workspace. Variables are only populated by the server, and will be ignored when sending a request. - :ivar prometheus_query_endpoint: The Prometheus query endpoint for the workspace. + :ivar prometheus_query_endpoint: The Prometheus query endpoint for the Azure Monitor Workspace. :vartype prometheus_query_endpoint: str :ivar internal_id: An internal identifier for the metrics container. Only to be used by the system. @@ -151,31 +135,17 @@ def __init__(self, **kwargs: Any) -> None: class AzureMonitorWorkspaceMetrics(Metrics): - """Information about metrics for the Azure Monitor workspace. + """Properties related to the metrics container in the Azure Monitor Workspace. Variables are only populated by the server, and will be ignored when sending a request. - :ivar prometheus_query_endpoint: The Prometheus query endpoint for the workspace. + :ivar prometheus_query_endpoint: The Prometheus query endpoint for the Azure Monitor Workspace. :vartype prometheus_query_endpoint: str :ivar internal_id: An internal identifier for the metrics container. Only to be used by the system. :vartype internal_id: str """ - _validation = { - "prometheus_query_endpoint": {"readonly": True}, - "internal_id": {"readonly": True}, - } - - _attribute_map = { - "prometheus_query_endpoint": {"key": "prometheusQueryEndpoint", "type": "str"}, - "internal_id": {"key": "internalId", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - class Resource(_serialization.Model): """Common fields that are returned in the response for all Azure Resource Manager resources. @@ -183,7 +153,7 @@ class Resource(_serialization.Model): 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}. + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long :vartype id: str :ivar name: The name of the resource. :vartype name: str @@ -224,10 +194,10 @@ 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: Fully qualified resource ID for the resource. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long :vartype id: str :ivar name: The name of the resource. :vartype name: str @@ -272,15 +242,15 @@ def __init__(self, *, location: str, tags: Optional[Dict[str, str]] = None, **kw self.location = location -class AzureMonitorWorkspaceResource(TrackedResource): # pylint: disable=too-many-instance-attributes +class AzureMonitorWorkspaceResource(TrackedResource): """An Azure Monitor Workspace definition. 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: Fully qualified resource ID for the resource. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long :vartype id: str :ivar name: The name of the resource. :vartype name: str @@ -296,11 +266,11 @@ class AzureMonitorWorkspaceResource(TrackedResource): # pylint: disable=too-man :vartype location: str :ivar etag: Resource entity tag (ETag). :vartype etag: str - :ivar account_id: The immutable ID of the Azure Monitor workspace. This property is read-only. + :ivar account_id: The immutable Id of the Azure Monitor Workspace. This property is read-only. :vartype account_id: str - :ivar metrics: Information about metrics for the Azure Monitor workspace. + :ivar metrics: Properties related to the metrics container in the Azure Monitor Workspace. :vartype metrics: ~azure.mgmt.monitor.v2021_06_03_preview.models.AzureMonitorWorkspaceMetrics - :ivar provisioning_state: The provisioning state of the Azure Monitor workspace. Set to + :ivar provisioning_state: The provisioning state of the Azure Monitor Workspace. Set to Succeeded if everything is healthy. Known values are: "Creating", "Succeeded", "Deleting", "Failed", and "Canceled". :vartype provisioning_state: str or @@ -357,7 +327,7 @@ def __init__(self, *, location: str, tags: Optional[Dict[str, str]] = None, **kw class AzureMonitorWorkspaceResourceForUpdate(_serialization.Model): - """Definition of ARM tracked top level resource properties for update operation. + """Definition of ARM tracked top level resource properties for the Update operation. :ivar tags: Resource tags. :vartype tags: dict[str, str] @@ -379,7 +349,7 @@ def __init__(self, *, tags: Optional[Dict[str, str]] = None, **kwargs: Any) -> N class AzureMonitorWorkspaceResourceListResult(_serialization.Model): """A pageable list of resources. - 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 value: A list of resources. Required. :vartype value: @@ -417,11 +387,11 @@ class AzureMonitorWorkspaceResourceProperties(AzureMonitorWorkspace): Variables are only populated by the server, and will be ignored when sending a request. - :ivar account_id: The immutable ID of the Azure Monitor workspace. This property is read-only. + :ivar account_id: The immutable Id of the Azure Monitor Workspace. This property is read-only. :vartype account_id: str - :ivar metrics: Information about metrics for the Azure Monitor workspace. + :ivar metrics: Properties related to the metrics container in the Azure Monitor Workspace. :vartype metrics: ~azure.mgmt.monitor.v2021_06_03_preview.models.AzureMonitorWorkspaceMetrics - :ivar provisioning_state: The provisioning state of the Azure Monitor workspace. Set to + :ivar provisioning_state: The provisioning state of the Azure Monitor Workspace. Set to Succeeded if everything is healthy. Known values are: "Creating", "Succeeded", "Deleting", "Failed", and "Canceled". :vartype provisioning_state: str or @@ -432,27 +402,6 @@ class AzureMonitorWorkspaceResourceProperties(AzureMonitorWorkspace): ~azure.mgmt.monitor.v2021_06_03_preview.models.AzureMonitorWorkspaceDefaultIngestionSettings """ - _validation = { - "account_id": {"readonly": True}, - "metrics": {"readonly": True}, - "provisioning_state": {"readonly": True}, - "default_ingestion_settings": {"readonly": True}, - } - - _attribute_map = { - "account_id": {"key": "accountId", "type": "str"}, - "metrics": {"key": "metrics", "type": "AzureMonitorWorkspaceMetrics"}, - "provisioning_state": {"key": "provisioningState", "type": "str"}, - "default_ingestion_settings": { - "key": "defaultIngestionSettings", - "type": "AzureMonitorWorkspaceDefaultIngestionSettings", - }, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - class ErrorAdditionalInfo(_serialization.Model): """The resource management error additional info. diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/models/_monitor_management_client_enums.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/models/_monitor_management_client_enums.py index c24d09a181f8..697fa4a0146a 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/models/_monitor_management_client_enums.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/models/_monitor_management_client_enums.py @@ -36,7 +36,7 @@ class Origin(str, Enum, metaclass=CaseInsensitiveEnumMeta): class ProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The provisioning state of the Azure Monitor workspace. Set to Succeeded if everything is + """The provisioning state of the Azure Monitor Workspace. Set to Succeeded if everything is healthy. """ diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/operations/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/operations/__init__.py index cc4f2ca90de6..2d767ded4d32 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/operations/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/operations/__init__.py @@ -5,17 +5,23 @@ # 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 ._azure_monitor_workspaces_operations import AzureMonitorWorkspacesOperations -from ._monitor_operations_operations import MonitorOperationsOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._azure_monitor_workspaces_operations import AzureMonitorWorkspacesOperations # type: ignore +from ._monitor_operations_operations import MonitorOperationsOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ "AzureMonitorWorkspacesOperations", "MonitorOperationsOperations", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/operations/_azure_monitor_workspaces_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/operations/_azure_monitor_workspaces_operations.py index 945e7e38b668..68bb8d6e98eb 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/operations/_azure_monitor_workspaces_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/operations/_azure_monitor_workspaces_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload import urllib.parse @@ -19,16 +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, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -55,7 +58,7 @@ def build_list_by_resource_group_request(resource_group_name: str, subscription_ ), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -79,7 +82,7 @@ def build_list_by_subscription_request(subscription_id: str, **kwargs: Any) -> H "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -114,7 +117,7 @@ def build_get_request( ), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -150,7 +153,7 @@ def build_create_request( ), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -188,7 +191,7 @@ def build_update_request( ), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -225,7 +228,7 @@ def build_delete_request( ), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -254,17 +257,17 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list_by_resource_group( self, resource_group_name: str, **kwargs: Any ) -> Iterable["_models.AzureMonitorWorkspaceResource"]: - """Lists all workspaces in the specified resource group. + """Lists all Azure Monitor Workspaces in the specified resource group. :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either AzureMonitorWorkspaceResource or the result of cls(response) :rtype: @@ -274,10 +277,12 @@ def list_by_resource_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-06-03-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-06-03-preview") + ) cls: ClsType[_models.AzureMonitorWorkspaceResourceListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -288,16 +293,14 @@ 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_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -308,14 +311,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("AzureMonitorWorkspaceResourceListResult", pipeline_response) @@ -325,11 +327,11 @@ def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -342,15 +344,10 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Monitor/accounts" - } - @distributed_trace def list_by_subscription(self, **kwargs: Any) -> Iterable["_models.AzureMonitorWorkspaceResource"]: - """Lists all workspaces in the specified subscription. + """Lists all Azure Monitor Workspaces in the specified subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either AzureMonitorWorkspaceResource or the result of cls(response) :rtype: @@ -360,10 +357,12 @@ def list_by_subscription(self, **kwargs: Any) -> Iterable["_models.AzureMonitorW _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-06-03-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-06-03-preview") + ) cls: ClsType[_models.AzureMonitorWorkspaceResourceListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -374,15 +373,13 @@ def list_by_subscription(self, **kwargs: Any) -> Iterable["_models.AzureMonitorW def prepare_request(next_link=None): if not next_link: - request = build_list_by_subscription_request( + _request = build_list_by_subscription_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_subscription.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -393,14 +390,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("AzureMonitorWorkspaceResourceListResult", pipeline_response) @@ -410,11 +406,11 @@ def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -427,26 +423,23 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_by_subscription.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.Monitor/accounts"} - @distributed_trace def get( self, resource_group_name: str, azure_monitor_workspace_name: str, **kwargs: Any ) -> _models.AzureMonitorWorkspaceResource: - """Returns the specific Azure Monitor workspace. + """Returns the specified Azure Monitor Workspace. :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :param azure_monitor_workspace_name: The name of the Azure Monitor workspace. The name is case + :param azure_monitor_workspace_name: The name of the Azure Monitor Workspace. The name is case insensitive. Required. :type azure_monitor_workspace_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: AzureMonitorWorkspaceResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_06_03_preview.models.AzureMonitorWorkspaceResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -457,24 +450,24 @@ def get( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-06-03-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-06-03-preview") + ) cls: ClsType[_models.AzureMonitorWorkspaceResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, azure_monitor_workspace_name=azure_monitor_workspace_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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -484,16 +477,12 @@ def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("AzureMonitorWorkspaceResource", pipeline_response) + deserialized = self._deserialize("AzureMonitorWorkspaceResource", 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.Monitor/accounts/{azureMonitorWorkspaceName}" - } + return deserialized # type: ignore @overload def create( @@ -505,22 +494,21 @@ def create( content_type: str = "application/json", **kwargs: Any ) -> _models.AzureMonitorWorkspaceResource: - """Create or update a workspace. + """Creates or updates an Azure Monitor Workspace. :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :param azure_monitor_workspace_name: The name of the Azure Monitor workspace. The name is case + :param azure_monitor_workspace_name: The name of the Azure Monitor Workspace. The name is case insensitive. Required. :type azure_monitor_workspace_name: str :param azure_monitor_workspace_properties: Properties that need to be specified to create a new - workspace. Required. + Azure Monitor Workspace. Required. :type azure_monitor_workspace_properties: ~azure.mgmt.monitor.v2021_06_03_preview.models.AzureMonitorWorkspaceResource :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: AzureMonitorWorkspaceResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_06_03_preview.models.AzureMonitorWorkspaceResource :raises ~azure.core.exceptions.HttpResponseError: @@ -531,26 +519,25 @@ def create( self, resource_group_name: str, azure_monitor_workspace_name: str, - azure_monitor_workspace_properties: IO, + azure_monitor_workspace_properties: IO[bytes], *, content_type: str = "application/json", **kwargs: Any ) -> _models.AzureMonitorWorkspaceResource: - """Create or update a workspace. + """Creates or updates an Azure Monitor Workspace. :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :param azure_monitor_workspace_name: The name of the Azure Monitor workspace. The name is case + :param azure_monitor_workspace_name: The name of the Azure Monitor Workspace. The name is case insensitive. Required. :type azure_monitor_workspace_name: str :param azure_monitor_workspace_properties: Properties that need to be specified to create a new - workspace. Required. - :type azure_monitor_workspace_properties: IO + Azure Monitor Workspace. Required. + :type azure_monitor_workspace_properties: 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: AzureMonitorWorkspaceResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_06_03_preview.models.AzureMonitorWorkspaceResource :raises ~azure.core.exceptions.HttpResponseError: @@ -561,30 +548,27 @@ def create( self, resource_group_name: str, azure_monitor_workspace_name: str, - azure_monitor_workspace_properties: Union[_models.AzureMonitorWorkspaceResource, IO], + azure_monitor_workspace_properties: Union[_models.AzureMonitorWorkspaceResource, IO[bytes]], **kwargs: Any ) -> _models.AzureMonitorWorkspaceResource: - """Create or update a workspace. + """Creates or updates an Azure Monitor Workspace. :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :param azure_monitor_workspace_name: The name of the Azure Monitor workspace. The name is case + :param azure_monitor_workspace_name: The name of the Azure Monitor Workspace. The name is case insensitive. Required. :type azure_monitor_workspace_name: str :param azure_monitor_workspace_properties: Properties that need to be specified to create a new - workspace. Is either a AzureMonitorWorkspaceResource type or a IO type. Required. + Azure Monitor Workspace. Is either a AzureMonitorWorkspaceResource type or a IO[bytes] type. + Required. :type azure_monitor_workspace_properties: - ~azure.mgmt.monitor.v2021_06_03_preview.models.AzureMonitorWorkspaceResource 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 + ~azure.mgmt.monitor.v2021_06_03_preview.models.AzureMonitorWorkspaceResource or IO[bytes] :return: AzureMonitorWorkspaceResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_06_03_preview.models.AzureMonitorWorkspaceResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -595,19 +579,21 @@ def create( _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", "2021-06-03-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-06-03-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.AzureMonitorWorkspaceResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(azure_monitor_workspace_properties, (IO, bytes)): + if isinstance(azure_monitor_workspace_properties, (IOBase, bytes)): _content = azure_monitor_workspace_properties else: _json = self._serialize.body(azure_monitor_workspace_properties, "AzureMonitorWorkspaceResource") - request = build_create_request( + _request = build_create_request( resource_group_name=resource_group_name, azure_monitor_workspace_name=azure_monitor_workspace_name, subscription_id=self._config.subscription_id, @@ -615,16 +601,14 @@ def create( content_type=content_type, json=_json, content=_content, - template_url=self.create.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -634,21 +618,13 @@ def create( 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("AzureMonitorWorkspaceResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("AzureMonitorWorkspaceResource", pipeline_response) + deserialized = self._deserialize("AzureMonitorWorkspaceResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Monitor/accounts/{azureMonitorWorkspaceName}" - } - @overload def update( self, @@ -659,12 +635,12 @@ def update( content_type: str = "application/json", **kwargs: Any ) -> _models.AzureMonitorWorkspaceResource: - """Updates part of a workspace. + """Updates part of an Azure Monitor Workspace. :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :param azure_monitor_workspace_name: The name of the Azure Monitor workspace. The name is case + :param azure_monitor_workspace_name: The name of the Azure Monitor Workspace. The name is case insensitive. Required. :type azure_monitor_workspace_name: str :param azure_monitor_workspace_properties: The payload. Default value is None. @@ -673,7 +649,6 @@ def update( :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: AzureMonitorWorkspaceResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_06_03_preview.models.AzureMonitorWorkspaceResource :raises ~azure.core.exceptions.HttpResponseError: @@ -684,25 +659,24 @@ def update( self, resource_group_name: str, azure_monitor_workspace_name: str, - azure_monitor_workspace_properties: Optional[IO] = None, + azure_monitor_workspace_properties: Optional[IO[bytes]] = None, *, content_type: str = "application/json", **kwargs: Any ) -> _models.AzureMonitorWorkspaceResource: - """Updates part of a workspace. + """Updates part of an Azure Monitor Workspace. :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :param azure_monitor_workspace_name: The name of the Azure Monitor workspace. The name is case + :param azure_monitor_workspace_name: The name of the Azure Monitor Workspace. The name is case insensitive. Required. :type azure_monitor_workspace_name: str :param azure_monitor_workspace_properties: The payload. Default value is None. - :type azure_monitor_workspace_properties: IO + :type azure_monitor_workspace_properties: 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: AzureMonitorWorkspaceResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_06_03_preview.models.AzureMonitorWorkspaceResource :raises ~azure.core.exceptions.HttpResponseError: @@ -713,30 +687,29 @@ def update( self, resource_group_name: str, azure_monitor_workspace_name: str, - azure_monitor_workspace_properties: Optional[Union[_models.AzureMonitorWorkspaceResourceForUpdate, IO]] = None, + azure_monitor_workspace_properties: Optional[ + Union[_models.AzureMonitorWorkspaceResourceForUpdate, IO[bytes]] + ] = None, **kwargs: Any ) -> _models.AzureMonitorWorkspaceResource: - """Updates part of a workspace. + """Updates part of an Azure Monitor Workspace. :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :param azure_monitor_workspace_name: The name of the Azure Monitor workspace. The name is case + :param azure_monitor_workspace_name: The name of the Azure Monitor Workspace. The name is case insensitive. Required. :type azure_monitor_workspace_name: str :param azure_monitor_workspace_properties: The payload. Is either a - AzureMonitorWorkspaceResourceForUpdate type or a IO type. Default value is None. + AzureMonitorWorkspaceResourceForUpdate type or a IO[bytes] type. Default value is None. :type azure_monitor_workspace_properties: - ~azure.mgmt.monitor.v2021_06_03_preview.models.AzureMonitorWorkspaceResourceForUpdate 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 + ~azure.mgmt.monitor.v2021_06_03_preview.models.AzureMonitorWorkspaceResourceForUpdate or + IO[bytes] :return: AzureMonitorWorkspaceResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_06_03_preview.models.AzureMonitorWorkspaceResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -747,14 +720,16 @@ def update( _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", "2021-06-03-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-06-03-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.AzureMonitorWorkspaceResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(azure_monitor_workspace_properties, (IO, bytes)): + if isinstance(azure_monitor_workspace_properties, (IOBase, bytes)): _content = azure_monitor_workspace_properties else: if azure_monitor_workspace_properties is not None: @@ -764,7 +739,7 @@ def update( else: _json = None - request = build_update_request( + _request = build_update_request( resource_group_name=resource_group_name, azure_monitor_workspace_name=azure_monitor_workspace_name, subscription_id=self._config.subscription_id, @@ -772,16 +747,14 @@ def update( 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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -791,35 +764,30 @@ def update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("AzureMonitorWorkspaceResource", pipeline_response) + deserialized = self._deserialize("AzureMonitorWorkspaceResource", 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.Monitor/accounts/{azureMonitorWorkspaceName}" - } + return deserialized # type: ignore @distributed_trace def delete( # pylint: disable=inconsistent-return-statements self, resource_group_name: str, azure_monitor_workspace_name: str, **kwargs: Any ) -> None: - """Delete a workspace. + """Deletes an Azure Monitor Workspace. :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :param azure_monitor_workspace_name: The name of the Azure Monitor workspace. The name is case + :param azure_monitor_workspace_name: The name of the Azure Monitor Workspace. The name is case insensitive. Required. :type azure_monitor_workspace_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, @@ -830,24 +798,24 @@ def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-06-03-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-06-03-preview") + ) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, azure_monitor_workspace_name=azure_monitor_workspace_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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -858,8 +826,4 @@ def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Monitor/accounts/{azureMonitorWorkspaceName}" - } + return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/operations/_monitor_operations_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/operations/_monitor_operations_operations.py index f91fec9a1f9e..6172405c4be1 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/operations/_monitor_operations_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_06_03_preview/operations/_monitor_operations_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,7 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import sys from typing import Any, Callable, Dict, Iterable, Optional, TypeVar import urllib.parse @@ -19,16 +19,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 +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -73,12 +75,12 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list(self, **kwargs: Any) -> Iterable["_models.Operation"]: """Lists available Operations for this Resource Provider. - :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.monitor.v2021_06_03_preview.models.Operation] :raises ~azure.core.exceptions.HttpResponseError: @@ -86,10 +88,12 @@ def list(self, **kwargs: Any) -> Iterable["_models.Operation"]: _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-06-03-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-06-03-preview") + ) cls: ClsType[_models.OperationListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -100,14 +104,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) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -118,14 +120,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("OperationListResult", pipeline_response) @@ -135,11 +136,11 @@ def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -151,5 +152,3 @@ def get_next(next_link=None): return pipeline_response return ItemPaged(get_next, extract_data) - - list.metadata = {"url": "/providers/Microsoft.Monitor/operations"} diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/__init__.py index 2c7733bfd566..42cc62301757 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/__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 ._monitor_management_client import MonitorManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._monitor_management_client import MonitorManagementClient # type: ignore from ._version import VERSION __version__ = VERSION try: from ._patch import __all__ as _patch_all - from ._patch import * # 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__ = [ "MonitorManagementClient", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/_configuration.py index 746cd69c06e9..00b757d861c4 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/_configuration.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/_configuration.py @@ -8,18 +8,16 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy from ._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MonitorManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class MonitorManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for MonitorManagementClient. Note that all parameters used to create this instance are saved as instance @@ -35,7 +33,6 @@ class MonitorManagementClientConfiguration(Configuration): # pylint: disable=to """ def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: - super(MonitorManagementClientConfiguration, self).__init__(**kwargs) api_version: str = kwargs.pop("api_version", "2021-07-01-preview") if credential is None: @@ -48,6 +45,7 @@ def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-monitor/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -56,9 +54,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.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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/_metadata.json b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/_metadata.json index 9c78561f0f7e..395b899b6d14 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/_metadata.json +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/_metadata.json @@ -8,10 +8,10 @@ "host_value": "\"https://management.azure.com\"", "parameterized_host_template": null, "azure_arm": true, - "has_lro_operations": true, + "has_public_lro_operations": true, "client_side_validation": false, - "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"sdkcore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMAutoResourceProviderRegistrationPolicy\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}, \"stdlib\": {\"typing_extensions\": [\"Self\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"sdkcore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"AsyncARMAutoResourceProviderRegistrationPolicy\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}, \"stdlib\": {\"typing_extensions\": [\"Self\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "global_parameters": { "sync": { @@ -101,8 +101,8 @@ "credential_scopes": ["https://management.azure.com/.default"], "credential_call_sync": "ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", "credential_call_async": "AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", - "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "sync_imports": "{\"regular\": {\"sdkcore\": {\"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"regular\": {\"sdkcore\": {\"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "operation_groups": { "private_link_scopes": "PrivateLinkScopesOperations", diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/_monitor_management_client.py index e443fc8f494f..d43650c8e946 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/_monitor_management_client.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/_monitor_management_client.py @@ -8,9 +8,12 @@ from copy import deepcopy from typing import Any, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient +from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy from . import models as _models from .._serialization import Deserializer, Serializer @@ -24,11 +27,10 @@ ) if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MonitorManagementClient: # pylint: disable=client-accepts-api-version-keyword +class MonitorManagementClient: """Monitor Management Client. :ivar private_link_scopes: PrivateLinkScopesOperations operations @@ -69,29 +71,47 @@ def __init__( self._config = MonitorManagementClientConfiguration( credential=credential, subscription_id=subscription_id, **kwargs ) - self._client: ARMPipelineClient = ARMPipelineClient(base_url=base_url, config=self._config, **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), + 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=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.private_link_scopes = PrivateLinkScopesOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2021-07-01-preview" ) self.private_link_scope_operation_status = PrivateLinkScopeOperationStatusOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2021-07-01-preview" ) self.private_link_resources = PrivateLinkResourcesOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2021-07-01-preview" ) self.private_endpoint_connections = PrivateEndpointConnectionsOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2021-07-01-preview" ) self.private_link_scoped_resources = PrivateLinkScopedResourcesOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2021-07-01-preview" ) - 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 @@ -111,12 +131,12 @@ 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) -> None: self._client.close() - def __enter__(self) -> "MonitorManagementClient": + def __enter__(self) -> Self: self._client.__enter__() return self diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/_vendor.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/_vendor.py deleted file mode 100644 index bd0df84f5319..000000000000 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/_vendor.py +++ /dev/null @@ -1,30 +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 typing import List, cast - -from azure.core.pipeline.transport import HttpRequest - - -def _convert_request(request, files=None): - data = request.content if not files else None - request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) - if files: - request.set_formdata_body(files) - return request - - -def _format_url_section(template, **kwargs): - components = template.split("/") - while components: - try: - return template.format(**kwargs) - except KeyError as key: - # Need the cast, as for some reasons "split" is typed as list[str | Any] - formatted_components = cast(List[str], template.split("/")) - components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] - template = "/".join(components) diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/_version.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/_version.py index 394ee7c0c03c..e5754a47ce68 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/_version.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "6.0.2" +VERSION = "1.0.0b1" diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/aio/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/aio/__init__.py index 2c151bb41c19..3df30ff42149 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/aio/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/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 ._monitor_management_client import MonitorManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._monitor_management_client import MonitorManagementClient # type: ignore try: from ._patch import __all__ as _patch_all - from ._patch import * # 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__ = [ "MonitorManagementClient", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/aio/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/aio/_configuration.py index e8bedc02dd43..f3503c319503 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/aio/_configuration.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/aio/_configuration.py @@ -8,18 +8,16 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy from .._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MonitorManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class MonitorManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for MonitorManagementClient. Note that all parameters used to create this instance are saved as instance @@ -35,7 +33,6 @@ class MonitorManagementClientConfiguration(Configuration): # pylint: disable=to """ def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: - super(MonitorManagementClientConfiguration, self).__init__(**kwargs) api_version: str = kwargs.pop("api_version", "2021-07-01-preview") if credential is None: @@ -48,6 +45,7 @@ def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **k self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-monitor/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -56,9 +54,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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/aio/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/aio/_monitor_management_client.py index 6480f4066fba..da9bce8b2e0a 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/aio/_monitor_management_client.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/aio/_monitor_management_client.py @@ -8,9 +8,12 @@ from copy import deepcopy from typing import Any, Awaitable, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient +from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy from .. import models as _models from ..._serialization import Deserializer, Serializer @@ -24,11 +27,10 @@ ) if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MonitorManagementClient: # pylint: disable=client-accepts-api-version-keyword +class MonitorManagementClient: """Monitor Management Client. :ivar private_link_scopes: PrivateLinkScopesOperations operations @@ -69,29 +71,49 @@ def __init__( self._config = MonitorManagementClientConfiguration( credential=credential, subscription_id=subscription_id, **kwargs ) - self._client: AsyncARMPipelineClient = AsyncARMPipelineClient(base_url=base_url, config=self._config, **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=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.private_link_scopes = PrivateLinkScopesOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2021-07-01-preview" ) self.private_link_scope_operation_status = PrivateLinkScopeOperationStatusOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2021-07-01-preview" ) self.private_link_resources = PrivateLinkResourcesOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2021-07-01-preview" ) self.private_endpoint_connections = PrivateEndpointConnectionsOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2021-07-01-preview" ) self.private_link_scoped_resources = PrivateLinkScopedResourcesOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2021-07-01-preview" ) - 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 @@ -111,12 +133,12 @@ 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) -> "MonitorManagementClient": + async def __aenter__(self) -> Self: await self._client.__aenter__() return self diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/aio/operations/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/aio/operations/__init__.py index 1f7c00746a8d..f529c5b732f2 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/aio/operations/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/aio/operations/__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 ._private_link_scopes_operations import PrivateLinkScopesOperations -from ._private_link_scope_operation_status_operations import PrivateLinkScopeOperationStatusOperations -from ._private_link_resources_operations import PrivateLinkResourcesOperations -from ._private_endpoint_connections_operations import PrivateEndpointConnectionsOperations -from ._private_link_scoped_resources_operations import PrivateLinkScopedResourcesOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._private_link_scopes_operations import PrivateLinkScopesOperations # type: ignore +from ._private_link_scope_operation_status_operations import PrivateLinkScopeOperationStatusOperations # type: ignore +from ._private_link_resources_operations import PrivateLinkResourcesOperations # type: ignore +from ._private_endpoint_connections_operations import PrivateEndpointConnectionsOperations # type: ignore +from ._private_link_scoped_resources_operations import PrivateLinkScopedResourcesOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ @@ -23,5 +29,5 @@ "PrivateEndpointConnectionsOperations", "PrivateLinkScopedResourcesOperations", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/aio/operations/_private_endpoint_connections_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/aio/operations/_private_endpoint_connections_operations.py index 6e2eb36a258f..4f49b9b25b9b 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/aio/operations/_private_endpoint_connections_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/aio/operations/_private_endpoint_connections_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,7 +5,9 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload +from io import IOBase +import sys +from typing import Any, AsyncIterator, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload from azure.core.exceptions import ( ClientAuthenticationError, @@ -14,19 +15,19 @@ 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_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, @@ -34,6 +35,10 @@ build_list_by_private_link_scope_request, ) +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -56,6 +61,7 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace_async async def get( @@ -70,12 +76,11 @@ async def get( :type scope_name: str :param private_endpoint_connection_name: The name of the private endpoint connection. Required. :type private_endpoint_connection_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: PrivateEndpointConnection or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_07_01_preview.models.PrivateEndpointConnection :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -86,25 +91,25 @@ async def get( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-07-01-preview") + ) cls: ClsType[_models.PrivateEndpointConnection] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, scope_name=scope_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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -114,26 +119,22 @@ async def get( error = self._deserialize.failsafe_deserialize(_models.DefaultErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) + deserialized = self._deserialize("PrivateEndpointConnection", 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.Insights/privateLinkScopes/{scopeName}/privateEndpointConnections/{privateEndpointConnectionName}" - } + return deserialized # type: ignore async def _create_or_update_initial( self, resource_group_name: str, scope_name: str, private_endpoint_connection_name: str, - parameters: Union[_models.PrivateEndpointConnection, IO], + parameters: Union[_models.PrivateEndpointConnection, IO[bytes]], **kwargs: Any - ) -> Optional[_models.PrivateEndpointConnection]: - error_map = { + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -144,19 +145,21 @@ async def _create_or_update_initial( _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", "2021-07-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-07-01-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Optional[_models.PrivateEndpointConnection]] = kwargs.pop("cls", None) + cls: ClsType[AsyncIterator[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, "PrivateEndpointConnection") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, scope_name=scope_name, private_endpoint_connection_name=private_endpoint_connection_name, @@ -165,37 +168,34 @@ async def _create_or_update_initial( 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) + _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: + 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.DefaultErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = None - if response.status_code == 200: - deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - _create_or_update_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/privateLinkScopes/{scopeName}/privateEndpointConnections/{privateEndpointConnectionName}" - } + return deserialized # type: ignore @overload async def begin_create_or_update( @@ -222,14 +222,6 @@ async def begin_create_or_update( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of AsyncLROPoller that returns either PrivateEndpointConnection or the result of cls(response) :rtype: @@ -243,7 +235,7 @@ async def begin_create_or_update( resource_group_name: str, scope_name: str, private_endpoint_connection_name: str, - parameters: IO, + parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -258,18 +250,10 @@ async def begin_create_or_update( :param private_endpoint_connection_name: The name of the private endpoint connection. Required. :type private_endpoint_connection_name: str :param parameters: Required. - :type parameters: IO + :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 PrivateEndpointConnection or the result of cls(response) :rtype: @@ -283,7 +267,7 @@ async def begin_create_or_update( resource_group_name: str, scope_name: str, private_endpoint_connection_name: str, - parameters: Union[_models.PrivateEndpointConnection, IO], + parameters: Union[_models.PrivateEndpointConnection, IO[bytes]], **kwargs: Any ) -> AsyncLROPoller[_models.PrivateEndpointConnection]: """Approve or reject a private endpoint connection with a given name. @@ -295,20 +279,9 @@ async def begin_create_or_update( :type scope_name: str :param private_endpoint_connection_name: The name of the private endpoint connection. Required. :type private_endpoint_connection_name: str - :param parameters: Is either a PrivateEndpointConnection type or a IO type. Required. + :param parameters: Is either a PrivateEndpointConnection type or a IO[bytes] type. Required. :type parameters: ~azure.mgmt.monitor.v2021_07_01_preview.models.PrivateEndpointConnection or - IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. + IO[bytes] :return: An instance of AsyncLROPoller that returns either PrivateEndpointConnection or the result of cls(response) :rtype: @@ -318,7 +291,9 @@ async def begin_create_or_update( _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", "2021-07-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-07-01-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.PrivateEndpointConnection] = kwargs.pop("cls", None) polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) @@ -337,12 +312,13 @@ async def begin_create_or_update( 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("PrivateEndpointConnection", pipeline_response) + deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: @@ -352,22 +328,20 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return AsyncLROPoller.from_continuation_token( + return AsyncLROPoller[_models.PrivateEndpointConnection].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/privateLinkScopes/{scopeName}/privateEndpointConnections/{privateEndpointConnectionName}" - } + return AsyncLROPoller[_models.PrivateEndpointConnection]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) - async def _delete_initial( # pylint: disable=inconsistent-return-statements + async def _delete_initial( self, resource_group_name: str, scope_name: str, private_endpoint_connection_name: str, **kwargs: Any - ) -> None: - error_map = { + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -378,40 +352,45 @@ async def _delete_initial( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) - cls: ClsType[None] = kwargs.pop("cls", None) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-07-01-preview") + ) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, scope_name=scope_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) + _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _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.DefaultErrorResponse, 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_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/privateLinkScopes/{scopeName}/privateEndpointConnections/{privateEndpointConnectionName}" - } + return deserialized # type: ignore @distributed_trace_async async def begin_delete( @@ -426,14 +405,6 @@ async def begin_delete( :type scope_name: str :param private_endpoint_connection_name: The name of the private endpoint connection. Required. :type private_endpoint_connection_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for - this operation to not poll, or pass in your own initialized polling object for a personal - polling strategy. - :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: @@ -441,13 +412,15 @@ async def begin_delete( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-07-01-preview") + ) cls: ClsType[None] = kwargs.pop("cls", None) polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: - raw_result = await self._delete_initial( # type: ignore + raw_result = await self._delete_initial( resource_group_name=resource_group_name, scope_name=scope_name, private_endpoint_connection_name=private_endpoint_connection_name, @@ -457,11 +430,12 @@ async def begin_delete( 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, {}) + return cls(pipeline_response, None, {}) # type: ignore if polling is True: polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) @@ -470,17 +444,13 @@ def get_long_running_output(pipeline_response): # pylint: disable=inconsistent- else: polling_method = polling if cont_token: - return AsyncLROPoller.from_continuation_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(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/privateLinkScopes/{scopeName}/privateEndpointConnections/{privateEndpointConnectionName}" - } + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore @distributed_trace_async async def list_by_private_link_scope( @@ -493,12 +463,11 @@ async def list_by_private_link_scope( :type resource_group_name: str :param scope_name: The name of the Azure Monitor PrivateLinkScope resource. Required. :type scope_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: PrivateEndpointConnectionListResult or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_07_01_preview.models.PrivateEndpointConnectionListResult :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -509,24 +478,24 @@ async def list_by_private_link_scope( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-07-01-preview") + ) cls: ClsType[_models.PrivateEndpointConnectionListResult] = kwargs.pop("cls", None) - request = build_list_by_private_link_scope_request( + _request = build_list_by_private_link_scope_request( resource_group_name=resource_group_name, scope_name=scope_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_private_link_scope.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -536,13 +505,9 @@ async def list_by_private_link_scope( error = self._deserialize.failsafe_deserialize(_models.DefaultErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("PrivateEndpointConnectionListResult", pipeline_response) + deserialized = self._deserialize("PrivateEndpointConnectionListResult", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - list_by_private_link_scope.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/privateLinkScopes/{scopeName}/privateEndpointConnections" - } + return deserialized # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/aio/operations/_private_link_resources_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/aio/operations/_private_link_resources_operations.py index a5d13a354e31..09be16874d14 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/aio/operations/_private_link_resources_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/aio/operations/_private_link_resources_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,7 @@ # 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 ( @@ -17,16 +17,18 @@ 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_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_by_private_link_scope_request +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -49,6 +51,7 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace_async async def list_by_private_link_scope( @@ -61,12 +64,11 @@ async def list_by_private_link_scope( :type resource_group_name: str :param scope_name: The name of the Azure Monitor PrivateLinkScope resource. Required. :type scope_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: PrivateLinkResourceListResult or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_07_01_preview.models.PrivateLinkResourceListResult :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -77,24 +79,24 @@ async def list_by_private_link_scope( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-07-01-preview") + ) cls: ClsType[_models.PrivateLinkResourceListResult] = kwargs.pop("cls", None) - request = build_list_by_private_link_scope_request( + _request = build_list_by_private_link_scope_request( resource_group_name=resource_group_name, scope_name=scope_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_private_link_scope.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -104,16 +106,12 @@ async def list_by_private_link_scope( error = self._deserialize.failsafe_deserialize(_models.DefaultErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("PrivateLinkResourceListResult", pipeline_response) + deserialized = self._deserialize("PrivateLinkResourceListResult", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - list_by_private_link_scope.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/privateLinkScopes/{scopeName}/privateLinkResources" - } + return deserialized # type: ignore @distributed_trace_async async def get( @@ -128,12 +126,11 @@ async def get( :type scope_name: str :param group_name: The name of the private link resource. Required. :type group_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.monitor.v2021_07_01_preview.models.PrivateLinkResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -144,25 +141,25 @@ async def get( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-07-01-preview") + ) cls: ClsType[_models.PrivateLinkResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, scope_name=scope_name, group_name=group_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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -172,13 +169,9 @@ async def get( error = self._deserialize.failsafe_deserialize(_models.DefaultErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("PrivateLinkResource", pipeline_response) + deserialized = self._deserialize("PrivateLinkResource", 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.Insights/privateLinkScopes/{scopeName}/privateLinkResources/{groupName}" - } + return deserialized # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/aio/operations/_private_link_scope_operation_status_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/aio/operations/_private_link_scope_operation_status_operations.py index 6c09e972797f..dde38c89eff8 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/aio/operations/_private_link_scope_operation_status_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/aio/operations/_private_link_scope_operation_status_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,7 @@ # 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 ( @@ -17,21 +17,23 @@ 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_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_scope_operation_status_operations import build_get_request +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class PrivateLinkScopeOperationStatusOperations: +class PrivateLinkScopeOperationStatusOperations: # pylint: disable=name-too-long """ .. warning:: **DO NOT** instantiate this class directly. @@ -49,6 +51,7 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace_async async def get(self, async_operation_id: str, resource_group_name: str, **kwargs: Any) -> _models.OperationStatus: @@ -60,12 +63,11 @@ async def get(self, async_operation_id: str, resource_group_name: str, **kwargs: :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: OperationStatus or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_07_01_preview.models.OperationStatus :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -76,24 +78,24 @@ async def get(self, async_operation_id: str, resource_group_name: str, **kwargs: _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-07-01-preview") + ) cls: ClsType[_models.OperationStatus] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( async_operation_id=async_operation_id, resource_group_name=resource_group_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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -103,13 +105,9 @@ async def get(self, async_operation_id: str, resource_group_name: str, **kwargs: error = self._deserialize.failsafe_deserialize(_models.DefaultErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("OperationStatus", pipeline_response) + deserialized = self._deserialize("OperationStatus", 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.insights/privateLinkScopeOperationStatuses/{asyncOperationId}" - } + return deserialized # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/aio/operations/_private_link_scoped_resources_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/aio/operations/_private_link_scoped_resources_operations.py index 12fe7bf5c75c..e7e650a4fbbb 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/aio/operations/_private_link_scoped_resources_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/aio/operations/_private_link_scoped_resources_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,7 +5,9 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload +from io import IOBase +import sys +from typing import Any, AsyncIterable, AsyncIterator, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList @@ -16,12 +17,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 @@ -29,7 +31,6 @@ from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models -from ..._vendor import _convert_request from ...operations._private_link_scoped_resources_operations import ( build_create_or_update_request, build_delete_request, @@ -37,6 +38,10 @@ build_list_by_private_link_scope_request, ) +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -59,6 +64,7 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace_async async def get(self, resource_group_name: str, scope_name: str, name: str, **kwargs: Any) -> _models.ScopedResource: @@ -71,12 +77,11 @@ async def get(self, resource_group_name: str, scope_name: str, name: str, **kwar :type scope_name: str :param name: The name of the scoped resource object. Required. :type name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ScopedResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_07_01_preview.models.ScopedResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -87,25 +92,25 @@ async def get(self, resource_group_name: str, scope_name: str, name: str, **kwar _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-07-01-preview") + ) cls: ClsType[_models.ScopedResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, scope_name=scope_name, name=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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -115,26 +120,22 @@ async def get(self, resource_group_name: str, scope_name: str, name: str, **kwar error = self._deserialize.failsafe_deserialize(_models.DefaultErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ScopedResource", pipeline_response) + deserialized = self._deserialize("ScopedResource", 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.Insights/privateLinkScopes/{scopeName}/scopedResources/{name}" - } + return deserialized # type: ignore async def _create_or_update_initial( self, resource_group_name: str, scope_name: str, name: str, - parameters: Union[_models.ScopedResource, IO], + parameters: Union[_models.ScopedResource, IO[bytes]], **kwargs: Any - ) -> Optional[_models.ScopedResource]: - error_map = { + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -145,19 +146,21 @@ async def _create_or_update_initial( _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", "2021-07-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-07-01-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Optional[_models.ScopedResource]] = kwargs.pop("cls", None) + cls: ClsType[AsyncIterator[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, "ScopedResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, scope_name=scope_name, name=name, @@ -166,40 +169,34 @@ async def _create_or_update_initial( 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) + _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 201, 202]: + 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.DefaultErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = None - if response.status_code == 200: - deserialized = self._deserialize("ScopedResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("ScopedResource", 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 - - _create_or_update_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/privateLinkScopes/{scopeName}/scopedResources/{name}" - } + return deserialized # type: ignore @overload async def begin_create_or_update( @@ -226,14 +223,6 @@ async def begin_create_or_update( :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 ScopedResource or the result of cls(response) :rtype: @@ -247,7 +236,7 @@ async def begin_create_or_update( resource_group_name: str, scope_name: str, name: str, - parameters: IO, + parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -262,18 +251,10 @@ async def begin_create_or_update( :param name: The name of the scoped resource object. Required. :type name: str :param parameters: Required. - :type parameters: IO + :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 ScopedResource or the result of cls(response) :rtype: @@ -287,7 +268,7 @@ async def begin_create_or_update( resource_group_name: str, scope_name: str, name: str, - parameters: Union[_models.ScopedResource, IO], + parameters: Union[_models.ScopedResource, IO[bytes]], **kwargs: Any ) -> AsyncLROPoller[_models.ScopedResource]: """Approve or reject a private endpoint connection with a given name. @@ -299,19 +280,8 @@ async def begin_create_or_update( :type scope_name: str :param name: The name of the scoped resource object. Required. :type name: str - :param parameters: Is either a ScopedResource type or a IO type. Required. - :type parameters: ~azure.mgmt.monitor.v2021_07_01_preview.models.ScopedResource 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. + :param parameters: Is either a ScopedResource type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.monitor.v2021_07_01_preview.models.ScopedResource or IO[bytes] :return: An instance of AsyncLROPoller that returns either ScopedResource or the result of cls(response) :rtype: @@ -321,7 +291,9 @@ async def begin_create_or_update( _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", "2021-07-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-07-01-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ScopedResource] = kwargs.pop("cls", None) polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) @@ -340,12 +312,13 @@ async def begin_create_or_update( 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("ScopedResource", pipeline_response) + deserialized = self._deserialize("ScopedResource", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: @@ -355,22 +328,20 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return AsyncLROPoller.from_continuation_token( + return AsyncLROPoller[_models.ScopedResource].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/privateLinkScopes/{scopeName}/scopedResources/{name}" - } + return AsyncLROPoller[_models.ScopedResource]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) - async def _delete_initial( # pylint: disable=inconsistent-return-statements + async def _delete_initial( self, resource_group_name: str, scope_name: str, name: str, **kwargs: Any - ) -> None: - error_map = { + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -381,40 +352,45 @@ async def _delete_initial( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) - cls: ClsType[None] = kwargs.pop("cls", None) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-07-01-preview") + ) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, scope_name=scope_name, name=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) + _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _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.DefaultErrorResponse, 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_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/privateLinkScopes/{scopeName}/scopedResources/{name}" - } + return deserialized # type: ignore @distributed_trace_async async def begin_delete( @@ -429,14 +405,6 @@ async def begin_delete( :type scope_name: str :param name: The name of the scoped resource object. Required. :type 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: @@ -444,13 +412,15 @@ async def begin_delete( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-07-01-preview") + ) cls: ClsType[None] = kwargs.pop("cls", None) polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: - raw_result = await self._delete_initial( # type: ignore + raw_result = await self._delete_initial( resource_group_name=resource_group_name, scope_name=scope_name, name=name, @@ -460,11 +430,12 @@ async def begin_delete( 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, {}) + return cls(pipeline_response, None, {}) # type: ignore if polling is True: polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) @@ -473,17 +444,13 @@ def get_long_running_output(pipeline_response): # pylint: disable=inconsistent- else: polling_method = polling if cont_token: - return AsyncLROPoller.from_continuation_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(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/privateLinkScopes/{scopeName}/scopedResources/{name}" - } + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore @distributed_trace def list_by_private_link_scope( @@ -496,7 +463,6 @@ def list_by_private_link_scope( :type resource_group_name: str :param scope_name: The name of the Azure Monitor PrivateLinkScope resource. Required. :type scope_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ScopedResource or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.monitor.v2021_07_01_preview.models.ScopedResource] @@ -505,10 +471,12 @@ def list_by_private_link_scope( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-07-01-preview") + ) cls: ClsType[_models.ScopedResourceListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -519,17 +487,15 @@ def list_by_private_link_scope( def prepare_request(next_link=None): if not next_link: - request = build_list_by_private_link_scope_request( + _request = build_list_by_private_link_scope_request( resource_group_name=resource_group_name, scope_name=scope_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_private_link_scope.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -540,14 +506,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("ScopedResourceListResult", pipeline_response) @@ -557,11 +522,11 @@ async def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -573,7 +538,3 @@ async def get_next(next_link=None): return pipeline_response return AsyncItemPaged(get_next, extract_data) - - list_by_private_link_scope.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/privateLinkScopes/{scopeName}/scopedResources" - } diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/aio/operations/_private_link_scopes_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/aio/operations/_private_link_scopes_operations.py index 298dbf7c95d7..cf394db56adc 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/aio/operations/_private_link_scopes_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/aio/operations/_private_link_scopes_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,7 +5,9 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload +from io import IOBase +import sys +from typing import Any, AsyncIterable, AsyncIterator, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList @@ -16,12 +17,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 @@ -29,7 +31,6 @@ from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models -from ..._vendor import _convert_request from ...operations._private_link_scopes_operations import ( build_create_or_update_request, build_delete_request, @@ -39,6 +40,10 @@ build_update_tags_request, ) +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -61,12 +66,13 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list(self, **kwargs: Any) -> AsyncIterable["_models.AzureMonitorPrivateLinkScope"]: + # pylint: disable=line-too-long """Gets a list of all Azure Monitor PrivateLinkScopes within a subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either AzureMonitorPrivateLinkScope or the result of cls(response) :rtype: @@ -76,10 +82,12 @@ def list(self, **kwargs: Any) -> AsyncIterable["_models.AzureMonitorPrivateLinkS _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-07-01-preview") + ) cls: ClsType[_models.AzureMonitorPrivateLinkScopeListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -90,15 +98,13 @@ def list(self, **kwargs: Any) -> AsyncIterable["_models.AzureMonitorPrivateLinkS def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _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) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -109,14 +115,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("AzureMonitorPrivateLinkScopeListResult", pipeline_response) @@ -126,11 +131,11 @@ async def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -143,18 +148,16 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/microsoft.insights/privateLinkScopes"} - @distributed_trace def list_by_resource_group( self, resource_group_name: str, **kwargs: Any ) -> AsyncIterable["_models.AzureMonitorPrivateLinkScope"]: + # pylint: disable=line-too-long """Gets a list of Azure Monitor PrivateLinkScopes within a resource group. :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either AzureMonitorPrivateLinkScope or the result of cls(response) :rtype: @@ -164,10 +167,12 @@ def list_by_resource_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-07-01-preview") + ) cls: ClsType[_models.AzureMonitorPrivateLinkScopeListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -178,16 +183,14 @@ 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_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -198,14 +201,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("AzureMonitorPrivateLinkScopeListResult", pipeline_response) @@ -215,11 +217,11 @@ async def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -232,14 +234,8 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/privateLinkScopes" - } - - async def _delete_initial( # pylint: disable=inconsistent-return-statements - self, resource_group_name: str, scope_name: str, **kwargs: Any - ) -> None: - error_map = { + async def _delete_initial(self, resource_group_name: str, scope_name: str, **kwargs: Any) -> AsyncIterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -250,39 +246,44 @@ async def _delete_initial( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) - cls: ClsType[None] = kwargs.pop("cls", None) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-07-01-preview") + ) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, scope_name=scope_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) + _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _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.DefaultErrorResponse, 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_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/privateLinkScopes/{scopeName}" - } + return deserialized # type: ignore @distributed_trace_async async def begin_delete(self, resource_group_name: str, scope_name: str, **kwargs: Any) -> AsyncLROPoller[None]: @@ -293,14 +294,6 @@ async def begin_delete(self, resource_group_name: str, scope_name: str, **kwargs :type resource_group_name: str :param scope_name: The name of the Azure Monitor PrivateLinkScope resource. Required. :type scope_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: @@ -308,13 +301,15 @@ async def begin_delete(self, resource_group_name: str, scope_name: str, **kwargs _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-07-01-preview") + ) cls: ClsType[None] = kwargs.pop("cls", None) polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: - raw_result = await self._delete_initial( # type: ignore + raw_result = await self._delete_initial( resource_group_name=resource_group_name, scope_name=scope_name, api_version=api_version, @@ -323,11 +318,12 @@ async def begin_delete(self, resource_group_name: str, scope_name: str, **kwargs 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, {}) + return cls(pipeline_response, None, {}) # type: ignore if polling is True: polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) @@ -336,17 +332,13 @@ def get_long_running_output(pipeline_response): # pylint: disable=inconsistent- else: polling_method = polling if cont_token: - return AsyncLROPoller.from_continuation_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(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/privateLinkScopes/{scopeName}" - } + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore @distributed_trace_async async def get( @@ -359,12 +351,11 @@ async def get( :type resource_group_name: str :param scope_name: The name of the Azure Monitor PrivateLinkScope resource. Required. :type scope_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: AzureMonitorPrivateLinkScope or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_07_01_preview.models.AzureMonitorPrivateLinkScope :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -375,24 +366,24 @@ async def get( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-07-01-preview") + ) cls: ClsType[_models.AzureMonitorPrivateLinkScope] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, scope_name=scope_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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -402,16 +393,12 @@ async def get( error = self._deserialize.failsafe_deserialize(_models.DefaultErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("AzureMonitorPrivateLinkScope", pipeline_response) + deserialized = self._deserialize("AzureMonitorPrivateLinkScope", 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.insights/privateLinkScopes/{scopeName}" - } + return deserialized # type: ignore @overload async def create_or_update( @@ -438,7 +425,6 @@ async def create_or_update( :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: AzureMonitorPrivateLinkScope or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_07_01_preview.models.AzureMonitorPrivateLinkScope :raises ~azure.core.exceptions.HttpResponseError: @@ -449,7 +435,7 @@ async def create_or_update( self, resource_group_name: str, scope_name: str, - azure_monitor_private_link_scope_payload: IO, + azure_monitor_private_link_scope_payload: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -464,11 +450,10 @@ async def create_or_update( :type scope_name: str :param azure_monitor_private_link_scope_payload: Properties that need to be specified to create or update a Azure Monitor PrivateLinkScope. Required. - :type azure_monitor_private_link_scope_payload: IO + :type azure_monitor_private_link_scope_payload: 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: AzureMonitorPrivateLinkScope or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_07_01_preview.models.AzureMonitorPrivateLinkScope :raises ~azure.core.exceptions.HttpResponseError: @@ -479,7 +464,7 @@ async def create_or_update( self, resource_group_name: str, scope_name: str, - azure_monitor_private_link_scope_payload: Union[_models.AzureMonitorPrivateLinkScope, IO], + azure_monitor_private_link_scope_payload: Union[_models.AzureMonitorPrivateLinkScope, IO[bytes]], **kwargs: Any ) -> _models.AzureMonitorPrivateLinkScope: """Creates (or updates) a Azure Monitor PrivateLinkScope. Note: You cannot specify a different @@ -492,18 +477,14 @@ async def create_or_update( :type scope_name: str :param azure_monitor_private_link_scope_payload: Properties that need to be specified to create or update a Azure Monitor PrivateLinkScope. Is either a AzureMonitorPrivateLinkScope type or a - IO type. Required. + IO[bytes] type. Required. :type azure_monitor_private_link_scope_payload: - ~azure.mgmt.monitor.v2021_07_01_preview.models.AzureMonitorPrivateLinkScope 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 + ~azure.mgmt.monitor.v2021_07_01_preview.models.AzureMonitorPrivateLinkScope or IO[bytes] :return: AzureMonitorPrivateLinkScope or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_07_01_preview.models.AzureMonitorPrivateLinkScope :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -514,19 +495,21 @@ async def create_or_update( _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", "2021-07-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-07-01-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.AzureMonitorPrivateLinkScope] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(azure_monitor_private_link_scope_payload, (IO, bytes)): + if isinstance(azure_monitor_private_link_scope_payload, (IOBase, bytes)): _content = azure_monitor_private_link_scope_payload else: _json = self._serialize.body(azure_monitor_private_link_scope_payload, "AzureMonitorPrivateLinkScope") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, scope_name=scope_name, subscription_id=self._config.subscription_id, @@ -534,16 +517,14 @@ async def create_or_update( 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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -553,21 +534,13 @@ async def create_or_update( error = self._deserialize.failsafe_deserialize(_models.DefaultErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if response.status_code == 200: - deserialized = self._deserialize("AzureMonitorPrivateLinkScope", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("AzureMonitorPrivateLinkScope", pipeline_response) + deserialized = self._deserialize("AzureMonitorPrivateLinkScope", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/privateLinkScopes/{scopeName}" - } - @overload async def update_tags( self, @@ -592,7 +565,6 @@ async def update_tags( :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: AzureMonitorPrivateLinkScope or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_07_01_preview.models.AzureMonitorPrivateLinkScope :raises ~azure.core.exceptions.HttpResponseError: @@ -603,7 +575,7 @@ async def update_tags( self, resource_group_name: str, scope_name: str, - private_link_scope_tags: IO, + private_link_scope_tags: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -618,11 +590,10 @@ async def update_tags( :type scope_name: str :param private_link_scope_tags: Updated tag information to set into the PrivateLinkScope instance. Required. - :type private_link_scope_tags: IO + :type private_link_scope_tags: 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: AzureMonitorPrivateLinkScope or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_07_01_preview.models.AzureMonitorPrivateLinkScope :raises ~azure.core.exceptions.HttpResponseError: @@ -633,7 +604,7 @@ async def update_tags( self, resource_group_name: str, scope_name: str, - private_link_scope_tags: Union[_models.TagsResource, IO], + private_link_scope_tags: Union[_models.TagsResource, IO[bytes]], **kwargs: Any ) -> _models.AzureMonitorPrivateLinkScope: """Updates an existing PrivateLinkScope's tags. To update other fields use the CreateOrUpdate @@ -645,18 +616,14 @@ async def update_tags( :param scope_name: The name of the Azure Monitor PrivateLinkScope resource. Required. :type scope_name: str :param private_link_scope_tags: Updated tag information to set into the PrivateLinkScope - instance. Is either a TagsResource type or a IO type. Required. + instance. Is either a TagsResource type or a IO[bytes] type. Required. :type private_link_scope_tags: ~azure.mgmt.monitor.v2021_07_01_preview.models.TagsResource 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 + IO[bytes] :return: AzureMonitorPrivateLinkScope or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_07_01_preview.models.AzureMonitorPrivateLinkScope :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -667,19 +634,21 @@ async def update_tags( _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", "2021-07-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-07-01-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.AzureMonitorPrivateLinkScope] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(private_link_scope_tags, (IO, bytes)): + if isinstance(private_link_scope_tags, (IOBase, bytes)): _content = private_link_scope_tags else: _json = self._serialize.body(private_link_scope_tags, "TagsResource") - request = build_update_tags_request( + _request = build_update_tags_request( resource_group_name=resource_group_name, scope_name=scope_name, subscription_id=self._config.subscription_id, @@ -687,16 +656,14 @@ async def update_tags( content_type=content_type, json=_json, content=_content, - template_url=self.update_tags.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -706,13 +673,9 @@ async def update_tags( error = self._deserialize.failsafe_deserialize(_models.DefaultErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("AzureMonitorPrivateLinkScope", pipeline_response) + deserialized = self._deserialize("AzureMonitorPrivateLinkScope", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - update_tags.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/privateLinkScopes/{scopeName}" - } + return deserialized # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/models/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/models/__init__.py index c4ffb9589907..81e92360e85b 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/models/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/models/__init__.py @@ -5,35 +5,46 @@ # 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 AccessModeSettings -from ._models_py3 import AccessModeSettingsExclusion -from ._models_py3 import AzureMonitorPrivateLinkScope -from ._models_py3 import AzureMonitorPrivateLinkScopeListResult -from ._models_py3 import DefaultErrorResponse -from ._models_py3 import ErrorAdditionalInfo -from ._models_py3 import ErrorDetail -from ._models_py3 import OperationStatus -from ._models_py3 import PrivateEndpoint -from ._models_py3 import PrivateEndpointConnection -from ._models_py3 import PrivateEndpointConnectionListResult -from ._models_py3 import PrivateLinkResource -from ._models_py3 import PrivateLinkResourceListResult -from ._models_py3 import PrivateLinkServiceConnectionState -from ._models_py3 import ProxyResource -from ._models_py3 import Resource -from ._models_py3 import ScopedResource -from ._models_py3 import ScopedResourceListResult -from ._models_py3 import SystemData -from ._models_py3 import TagsResource -from ._models_py3 import TrackedResource +from typing import TYPE_CHECKING -from ._monitor_management_client_enums import AccessMode -from ._monitor_management_client_enums import CreatedByType -from ._monitor_management_client_enums import PrivateEndpointConnectionProvisioningState -from ._monitor_management_client_enums import PrivateEndpointServiceConnectionStatus +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models_py3 import ( # type: ignore + AccessModeSettings, + AccessModeSettingsExclusion, + AzureMonitorPrivateLinkScope, + AzureMonitorPrivateLinkScopeListResult, + DefaultErrorResponse, + ErrorAdditionalInfo, + ErrorDetail, + OperationStatus, + PrivateEndpoint, + PrivateEndpointConnection, + PrivateEndpointConnectionListResult, + PrivateLinkResource, + PrivateLinkResourceListResult, + PrivateLinkServiceConnectionState, + ProxyResource, + Resource, + ScopedResource, + ScopedResourceListResult, + SystemData, + TagsResource, + TrackedResource, +) + +from ._monitor_management_client_enums import ( # type: ignore + AccessMode, + CreatedByType, + PrivateEndpointConnectionProvisioningState, + PrivateEndpointServiceConnectionStatus, +) from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ @@ -63,5 +74,5 @@ "PrivateEndpointConnectionProvisioningState", "PrivateEndpointServiceConnectionStatus", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/models/_models_py3.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/models/_models_py3.py index 9ab87ce13af6..5a04d1cf8449 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/models/_models_py3.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/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. @@ -13,14 +12,13 @@ from ... import _serialization if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from .. import models as _models class AccessModeSettings(_serialization.Model): """Properties that define the scope private link mode settings. - 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 query_access_mode: Specifies the default access mode of queries through associated private endpoints in scope. If not specified default value is 'Open'. You can override this @@ -136,7 +134,7 @@ class Resource(_serialization.Model): 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}. + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long :vartype id: str :ivar name: The name of the resource. :vartype name: str @@ -171,10 +169,10 @@ 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: Fully qualified resource ID for the resource. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long :vartype id: str :ivar name: The name of the resource. :vartype name: str @@ -219,10 +217,10 @@ class AzureMonitorPrivateLinkScope(TrackedResource): 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: Fully qualified resource ID for the resource. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long :vartype id: str :ivar name: The name of the resource. :vartype name: str @@ -300,7 +298,7 @@ def __init__( class AzureMonitorPrivateLinkScopeListResult(_serialization.Model): """Describes the list of Azure Monitor PrivateLinkScope resources. - 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 value: List of Azure Monitor PrivateLinkScope definitions. Required. :vartype value: @@ -517,7 +515,7 @@ class PrivateEndpointConnection(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}. + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long :vartype id: str :ivar name: The name of the resource. :vartype name: str @@ -603,7 +601,7 @@ class PrivateLinkResource(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}. + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long :vartype id: str :ivar name: The name of the resource. :vartype name: str @@ -719,7 +717,7 @@ class ProxyResource(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}. + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long :vartype id: str :ivar name: The name of the resource. :vartype name: str @@ -728,22 +726,6 @@ class ProxyResource(Resource): :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: Any) -> None: - """ """ - super().__init__(**kwargs) - class ScopedResource(ProxyResource): """A private link scoped resource. @@ -751,7 +733,7 @@ class ScopedResource(ProxyResource): 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}. + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long :vartype id: str :ivar name: The name of the resource. :vartype name: str diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/operations/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/operations/__init__.py index 1f7c00746a8d..f529c5b732f2 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/operations/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/operations/__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 ._private_link_scopes_operations import PrivateLinkScopesOperations -from ._private_link_scope_operation_status_operations import PrivateLinkScopeOperationStatusOperations -from ._private_link_resources_operations import PrivateLinkResourcesOperations -from ._private_endpoint_connections_operations import PrivateEndpointConnectionsOperations -from ._private_link_scoped_resources_operations import PrivateLinkScopedResourcesOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._private_link_scopes_operations import PrivateLinkScopesOperations # type: ignore +from ._private_link_scope_operation_status_operations import PrivateLinkScopeOperationStatusOperations # type: ignore +from ._private_link_resources_operations import PrivateLinkResourcesOperations # type: ignore +from ._private_endpoint_connections_operations import PrivateEndpointConnectionsOperations # type: ignore +from ._private_link_scoped_resources_operations import PrivateLinkScopedResourcesOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ @@ -23,5 +29,5 @@ "PrivateEndpointConnectionsOperations", "PrivateLinkScopedResourcesOperations", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/operations/_private_endpoint_connections_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/operations/_private_endpoint_connections_operations.py index bf43481d3794..eed534644c27 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/operations/_private_endpoint_connections_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/operations/_private_endpoint_connections_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,7 +5,9 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload +from io import IOBase +import sys +from typing import Any, Callable, Dict, IO, Iterator, Optional, TypeVar, Union, cast, overload from azure.core.exceptions import ( ClientAuthenticationError, @@ -14,12 +15,13 @@ ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod -from azure.core.rest import HttpRequest +from azure.core.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 @@ -27,8 +29,11 @@ from .. import models as _models from ..._serialization import Serializer -from .._vendor import _convert_request, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -65,7 +70,7 @@ def build_get_request( ), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -106,7 +111,7 @@ def build_create_or_update_request( ), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -148,7 +153,7 @@ def build_delete_request( ), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -181,7 +186,7 @@ def build_list_by_private_link_scope_request( "scopeName": _SERIALIZER.url("scope_name", scope_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -210,6 +215,7 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def get( @@ -224,12 +230,11 @@ def get( :type scope_name: str :param private_endpoint_connection_name: The name of the private endpoint connection. Required. :type private_endpoint_connection_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: PrivateEndpointConnection or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_07_01_preview.models.PrivateEndpointConnection :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -240,25 +245,25 @@ def get( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-07-01-preview") + ) cls: ClsType[_models.PrivateEndpointConnection] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, scope_name=scope_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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -268,26 +273,22 @@ def get( error = self._deserialize.failsafe_deserialize(_models.DefaultErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) + deserialized = self._deserialize("PrivateEndpointConnection", 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.Insights/privateLinkScopes/{scopeName}/privateEndpointConnections/{privateEndpointConnectionName}" - } + return deserialized # type: ignore def _create_or_update_initial( self, resource_group_name: str, scope_name: str, private_endpoint_connection_name: str, - parameters: Union[_models.PrivateEndpointConnection, IO], + parameters: Union[_models.PrivateEndpointConnection, IO[bytes]], **kwargs: Any - ) -> Optional[_models.PrivateEndpointConnection]: - error_map = { + ) -> Iterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -298,19 +299,21 @@ def _create_or_update_initial( _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", "2021-07-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-07-01-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Optional[_models.PrivateEndpointConnection]] = kwargs.pop("cls", 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, "PrivateEndpointConnection") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, scope_name=scope_name, private_endpoint_connection_name=private_endpoint_connection_name, @@ -319,37 +322,34 @@ def _create_or_update_initial( 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) + _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: + 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.DefaultErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = None - if response.status_code == 200: - deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - _create_or_update_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/privateLinkScopes/{scopeName}/privateEndpointConnections/{privateEndpointConnectionName}" - } + return deserialized # type: ignore @overload def begin_create_or_update( @@ -376,14 +376,6 @@ def begin_create_or_update( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of LROPoller that returns either PrivateEndpointConnection or the result of cls(response) :rtype: @@ -397,7 +389,7 @@ def begin_create_or_update( resource_group_name: str, scope_name: str, private_endpoint_connection_name: str, - parameters: IO, + parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -412,18 +404,10 @@ def begin_create_or_update( :param private_endpoint_connection_name: The name of the private endpoint connection. Required. :type private_endpoint_connection_name: str :param parameters: Required. - :type parameters: IO + :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 PrivateEndpointConnection or the result of cls(response) :rtype: @@ -437,7 +421,7 @@ def begin_create_or_update( resource_group_name: str, scope_name: str, private_endpoint_connection_name: str, - parameters: Union[_models.PrivateEndpointConnection, IO], + parameters: Union[_models.PrivateEndpointConnection, IO[bytes]], **kwargs: Any ) -> LROPoller[_models.PrivateEndpointConnection]: """Approve or reject a private endpoint connection with a given name. @@ -449,20 +433,9 @@ def begin_create_or_update( :type scope_name: str :param private_endpoint_connection_name: The name of the private endpoint connection. Required. :type private_endpoint_connection_name: str - :param parameters: Is either a PrivateEndpointConnection type or a IO type. Required. + :param parameters: Is either a PrivateEndpointConnection type or a IO[bytes] type. Required. :type parameters: ~azure.mgmt.monitor.v2021_07_01_preview.models.PrivateEndpointConnection or - IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. + IO[bytes] :return: An instance of LROPoller that returns either PrivateEndpointConnection or the result of cls(response) :rtype: @@ -472,7 +445,9 @@ def begin_create_or_update( _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", "2021-07-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-07-01-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.PrivateEndpointConnection] = kwargs.pop("cls", None) polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) @@ -491,12 +466,13 @@ def begin_create_or_update( 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("PrivateEndpointConnection", pipeline_response) + deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: @@ -506,22 +482,20 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return LROPoller.from_continuation_token( + return LROPoller[_models.PrivateEndpointConnection].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/privateLinkScopes/{scopeName}/privateEndpointConnections/{privateEndpointConnectionName}" - } + return LROPoller[_models.PrivateEndpointConnection]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) - def _delete_initial( # pylint: disable=inconsistent-return-statements + def _delete_initial( self, resource_group_name: str, scope_name: str, private_endpoint_connection_name: str, **kwargs: Any - ) -> None: - error_map = { + ) -> Iterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -532,40 +506,45 @@ def _delete_initial( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) - cls: ClsType[None] = kwargs.pop("cls", None) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-07-01-preview") + ) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, scope_name=scope_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) + _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response 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.DefaultErrorResponse, 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_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/privateLinkScopes/{scopeName}/privateEndpointConnections/{privateEndpointConnectionName}" - } + return deserialized # type: ignore @distributed_trace def begin_delete( @@ -580,14 +559,6 @@ def begin_delete( :type scope_name: str :param private_endpoint_connection_name: The name of the private endpoint connection. Required. :type private_endpoint_connection_name: str - :keyword callable cls: A custom type or function that will be passed the direct response - :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this - operation to not poll, or pass in your own initialized polling object for a personal polling - strategy. - :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: @@ -595,13 +566,15 @@ def begin_delete( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-07-01-preview") + ) cls: ClsType[None] = kwargs.pop("cls", None) polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: - raw_result = self._delete_initial( # type: ignore + raw_result = self._delete_initial( resource_group_name=resource_group_name, scope_name=scope_name, private_endpoint_connection_name=private_endpoint_connection_name, @@ -611,11 +584,12 @@ def begin_delete( params=_params, **kwargs ) + 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, {}) + return cls(pipeline_response, None, {}) # type: ignore if polling is True: polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) @@ -624,17 +598,13 @@ def get_long_running_output(pipeline_response): # pylint: disable=inconsistent- else: polling_method = polling if cont_token: - return LROPoller.from_continuation_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(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/privateLinkScopes/{scopeName}/privateEndpointConnections/{privateEndpointConnectionName}" - } + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore @distributed_trace def list_by_private_link_scope( @@ -647,12 +617,11 @@ def list_by_private_link_scope( :type resource_group_name: str :param scope_name: The name of the Azure Monitor PrivateLinkScope resource. Required. :type scope_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: PrivateEndpointConnectionListResult or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_07_01_preview.models.PrivateEndpointConnectionListResult :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -663,24 +632,24 @@ def list_by_private_link_scope( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-07-01-preview") + ) cls: ClsType[_models.PrivateEndpointConnectionListResult] = kwargs.pop("cls", None) - request = build_list_by_private_link_scope_request( + _request = build_list_by_private_link_scope_request( resource_group_name=resource_group_name, scope_name=scope_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_private_link_scope.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -690,13 +659,9 @@ def list_by_private_link_scope( error = self._deserialize.failsafe_deserialize(_models.DefaultErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("PrivateEndpointConnectionListResult", pipeline_response) + deserialized = self._deserialize("PrivateEndpointConnectionListResult", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - list_by_private_link_scope.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/privateLinkScopes/{scopeName}/privateEndpointConnections" - } + return deserialized # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/operations/_private_link_resources_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/operations/_private_link_resources_operations.py index 834b2647e84c..0d0bd6a23565 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/operations/_private_link_resources_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/operations/_private_link_resources_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,7 @@ # 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 ( @@ -17,16 +17,18 @@ map_error, ) 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 +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -56,7 +58,7 @@ def build_list_by_private_link_scope_request( "scopeName": _SERIALIZER.url("scope_name", scope_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -90,7 +92,7 @@ def build_get_request( "groupName": _SERIALIZER.url("group_name", group_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -119,6 +121,7 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list_by_private_link_scope( @@ -131,12 +134,11 @@ def list_by_private_link_scope( :type resource_group_name: str :param scope_name: The name of the Azure Monitor PrivateLinkScope resource. Required. :type scope_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: PrivateLinkResourceListResult or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_07_01_preview.models.PrivateLinkResourceListResult :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -147,24 +149,24 @@ def list_by_private_link_scope( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-07-01-preview") + ) cls: ClsType[_models.PrivateLinkResourceListResult] = kwargs.pop("cls", None) - request = build_list_by_private_link_scope_request( + _request = build_list_by_private_link_scope_request( resource_group_name=resource_group_name, scope_name=scope_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_private_link_scope.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -174,16 +176,12 @@ def list_by_private_link_scope( error = self._deserialize.failsafe_deserialize(_models.DefaultErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("PrivateLinkResourceListResult", pipeline_response) + deserialized = self._deserialize("PrivateLinkResourceListResult", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - list_by_private_link_scope.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/privateLinkScopes/{scopeName}/privateLinkResources" - } + return deserialized # type: ignore @distributed_trace def get( @@ -198,12 +196,11 @@ def get( :type scope_name: str :param group_name: The name of the private link resource. Required. :type group_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.monitor.v2021_07_01_preview.models.PrivateLinkResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -214,25 +211,25 @@ def get( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-07-01-preview") + ) cls: ClsType[_models.PrivateLinkResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, scope_name=scope_name, group_name=group_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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -242,13 +239,9 @@ def get( error = self._deserialize.failsafe_deserialize(_models.DefaultErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("PrivateLinkResource", pipeline_response) + deserialized = self._deserialize("PrivateLinkResource", 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.Insights/privateLinkScopes/{scopeName}/privateLinkResources/{groupName}" - } + return deserialized # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/operations/_private_link_scope_operation_status_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/operations/_private_link_scope_operation_status_operations.py index 8954342765be..7c6a2a93bf6d 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/operations/_private_link_scope_operation_status_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/operations/_private_link_scope_operation_status_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,7 @@ # 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 ( @@ -17,16 +17,18 @@ map_error, ) 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 +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -56,7 +58,7 @@ def build_get_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -67,7 +69,7 @@ def build_get_request( return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -class PrivateLinkScopeOperationStatusOperations: +class PrivateLinkScopeOperationStatusOperations: # pylint: disable=name-too-long """ .. warning:: **DO NOT** instantiate this class directly. @@ -85,6 +87,7 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def get(self, async_operation_id: str, resource_group_name: str, **kwargs: Any) -> _models.OperationStatus: @@ -96,12 +99,11 @@ def get(self, async_operation_id: str, resource_group_name: str, **kwargs: Any) :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: OperationStatus or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_07_01_preview.models.OperationStatus :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -112,24 +114,24 @@ def get(self, async_operation_id: str, resource_group_name: str, **kwargs: Any) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-07-01-preview") + ) cls: ClsType[_models.OperationStatus] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( async_operation_id=async_operation_id, resource_group_name=resource_group_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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -139,13 +141,9 @@ def get(self, async_operation_id: str, resource_group_name: str, **kwargs: Any) error = self._deserialize.failsafe_deserialize(_models.DefaultErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("OperationStatus", pipeline_response) + deserialized = self._deserialize("OperationStatus", 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.insights/privateLinkScopeOperationStatuses/{asyncOperationId}" - } + return deserialized # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/operations/_private_link_scoped_resources_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/operations/_private_link_scoped_resources_operations.py index f970d2f14190..f7152e74d1dc 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/operations/_private_link_scoped_resources_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/operations/_private_link_scoped_resources_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,7 +5,9 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload +from io import IOBase +import sys +from typing import Any, Callable, Dict, IO, Iterable, Iterator, Optional, TypeVar, Union, cast, overload import urllib.parse from azure.core.exceptions import ( @@ -15,13 +16,14 @@ 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 @@ -29,8 +31,11 @@ from .. import models as _models from ..._serialization import Serializer -from .._vendor import _convert_request, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -61,7 +66,7 @@ def build_get_request( "name": _SERIALIZER.url("name", name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -96,7 +101,7 @@ def build_create_or_update_request( "name": _SERIALIZER.url("name", name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -132,7 +137,7 @@ def build_delete_request( "name": _SERIALIZER.url("name", name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -165,7 +170,7 @@ def build_list_by_private_link_scope_request( "scopeName": _SERIALIZER.url("scope_name", scope_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -194,6 +199,7 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def get(self, resource_group_name: str, scope_name: str, name: str, **kwargs: Any) -> _models.ScopedResource: @@ -206,12 +212,11 @@ def get(self, resource_group_name: str, scope_name: str, name: str, **kwargs: An :type scope_name: str :param name: The name of the scoped resource object. Required. :type name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ScopedResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_07_01_preview.models.ScopedResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -222,25 +227,25 @@ def get(self, resource_group_name: str, scope_name: str, name: str, **kwargs: An _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-07-01-preview") + ) cls: ClsType[_models.ScopedResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, scope_name=scope_name, name=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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -250,26 +255,22 @@ def get(self, resource_group_name: str, scope_name: str, name: str, **kwargs: An error = self._deserialize.failsafe_deserialize(_models.DefaultErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ScopedResource", pipeline_response) + deserialized = self._deserialize("ScopedResource", 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.Insights/privateLinkScopes/{scopeName}/scopedResources/{name}" - } + return deserialized # type: ignore def _create_or_update_initial( self, resource_group_name: str, scope_name: str, name: str, - parameters: Union[_models.ScopedResource, IO], + parameters: Union[_models.ScopedResource, IO[bytes]], **kwargs: Any - ) -> Optional[_models.ScopedResource]: - error_map = { + ) -> Iterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -280,19 +281,21 @@ def _create_or_update_initial( _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", "2021-07-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-07-01-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Optional[_models.ScopedResource]] = kwargs.pop("cls", 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, "ScopedResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, scope_name=scope_name, name=name, @@ -301,40 +304,34 @@ def _create_or_update_initial( 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) + _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 201, 202]: + 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.DefaultErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = None - if response.status_code == 200: - deserialized = self._deserialize("ScopedResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("ScopedResource", 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 - - _create_or_update_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/privateLinkScopes/{scopeName}/scopedResources/{name}" - } + return deserialized # type: ignore @overload def begin_create_or_update( @@ -361,14 +358,6 @@ def begin_create_or_update( :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 ScopedResource or the result of cls(response) :rtype: @@ -382,7 +371,7 @@ def begin_create_or_update( resource_group_name: str, scope_name: str, name: str, - parameters: IO, + parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -397,18 +386,10 @@ def begin_create_or_update( :param name: The name of the scoped resource object. Required. :type name: str :param parameters: Required. - :type parameters: IO + :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 ScopedResource or the result of cls(response) :rtype: @@ -422,7 +403,7 @@ def begin_create_or_update( resource_group_name: str, scope_name: str, name: str, - parameters: Union[_models.ScopedResource, IO], + parameters: Union[_models.ScopedResource, IO[bytes]], **kwargs: Any ) -> LROPoller[_models.ScopedResource]: """Approve or reject a private endpoint connection with a given name. @@ -434,19 +415,8 @@ def begin_create_or_update( :type scope_name: str :param name: The name of the scoped resource object. Required. :type name: str - :param parameters: Is either a ScopedResource type or a IO type. Required. - :type parameters: ~azure.mgmt.monitor.v2021_07_01_preview.models.ScopedResource 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. + :param parameters: Is either a ScopedResource type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.monitor.v2021_07_01_preview.models.ScopedResource or IO[bytes] :return: An instance of LROPoller that returns either ScopedResource or the result of cls(response) :rtype: @@ -456,7 +426,9 @@ def begin_create_or_update( _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", "2021-07-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-07-01-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ScopedResource] = kwargs.pop("cls", None) polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) @@ -475,12 +447,13 @@ def begin_create_or_update( 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("ScopedResource", pipeline_response) + deserialized = self._deserialize("ScopedResource", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: @@ -490,22 +463,18 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return LROPoller.from_continuation_token( + return LROPoller[_models.ScopedResource].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/privateLinkScopes/{scopeName}/scopedResources/{name}" - } + return LROPoller[_models.ScopedResource]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) - def _delete_initial( # pylint: disable=inconsistent-return-statements - self, resource_group_name: str, scope_name: str, name: str, **kwargs: Any - ) -> None: - error_map = { + def _delete_initial(self, resource_group_name: str, scope_name: str, name: str, **kwargs: Any) -> Iterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -516,40 +485,45 @@ def _delete_initial( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) - cls: ClsType[None] = kwargs.pop("cls", None) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-07-01-preview") + ) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, scope_name=scope_name, name=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) + _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response 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.DefaultErrorResponse, 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_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/privateLinkScopes/{scopeName}/scopedResources/{name}" - } + return deserialized # type: ignore @distributed_trace def begin_delete(self, resource_group_name: str, scope_name: str, name: str, **kwargs: Any) -> LROPoller[None]: @@ -562,14 +536,6 @@ def begin_delete(self, resource_group_name: str, scope_name: str, name: str, **k :type scope_name: str :param name: The name of the scoped resource object. Required. :type 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: @@ -577,13 +543,15 @@ def begin_delete(self, resource_group_name: str, scope_name: str, name: str, **k _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-07-01-preview") + ) cls: ClsType[None] = kwargs.pop("cls", None) polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: - raw_result = self._delete_initial( # type: ignore + raw_result = self._delete_initial( resource_group_name=resource_group_name, scope_name=scope_name, name=name, @@ -593,11 +561,12 @@ def begin_delete(self, resource_group_name: str, scope_name: str, name: str, **k params=_params, **kwargs ) + 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, {}) + return cls(pipeline_response, None, {}) # type: ignore if polling is True: polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) @@ -606,17 +575,13 @@ def get_long_running_output(pipeline_response): # pylint: disable=inconsistent- else: polling_method = polling if cont_token: - return LROPoller.from_continuation_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(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/privateLinkScopes/{scopeName}/scopedResources/{name}" - } + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore @distributed_trace def list_by_private_link_scope( @@ -629,7 +594,6 @@ def list_by_private_link_scope( :type resource_group_name: str :param scope_name: The name of the Azure Monitor PrivateLinkScope resource. Required. :type scope_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ScopedResource or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.monitor.v2021_07_01_preview.models.ScopedResource] @@ -638,10 +602,12 @@ def list_by_private_link_scope( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-07-01-preview") + ) cls: ClsType[_models.ScopedResourceListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -652,17 +618,15 @@ def list_by_private_link_scope( def prepare_request(next_link=None): if not next_link: - request = build_list_by_private_link_scope_request( + _request = build_list_by_private_link_scope_request( resource_group_name=resource_group_name, scope_name=scope_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_private_link_scope.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -673,14 +637,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("ScopedResourceListResult", pipeline_response) @@ -690,11 +653,11 @@ def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -706,7 +669,3 @@ def get_next(next_link=None): return pipeline_response return ItemPaged(get_next, extract_data) - - list_by_private_link_scope.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/privateLinkScopes/{scopeName}/scopedResources" - } diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/operations/_private_link_scopes_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/operations/_private_link_scopes_operations.py index 04fb65892d85..7131f8cdc06d 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/operations/_private_link_scopes_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_07_01_preview/operations/_private_link_scopes_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,7 +5,9 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload +from io import IOBase +import sys +from typing import Any, Callable, Dict, IO, Iterable, Iterator, Optional, TypeVar, Union, cast, overload import urllib.parse from azure.core.exceptions import ( @@ -15,13 +16,14 @@ 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 @@ -29,8 +31,11 @@ from .. import models as _models from ..._serialization import Serializer -from .._vendor import _convert_request, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -51,7 +56,7 @@ def build_list_request(subscription_id: str, **kwargs: Any) -> HttpRequest: "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -81,7 +86,7 @@ def build_list_by_resource_group_request(resource_group_name: str, subscription_ "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -112,7 +117,7 @@ def build_delete_request(resource_group_name: str, scope_name: str, subscription "scopeName": _SERIALIZER.url("scope_name", scope_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -143,7 +148,7 @@ def build_get_request(resource_group_name: str, scope_name: str, subscription_id "scopeName": _SERIALIZER.url("scope_name", scope_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -177,7 +182,7 @@ def build_create_or_update_request( "scopeName": _SERIALIZER.url("scope_name", scope_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -213,7 +218,7 @@ def build_update_tags_request( "scopeName": _SERIALIZER.url("scope_name", scope_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -244,12 +249,12 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list(self, **kwargs: Any) -> Iterable["_models.AzureMonitorPrivateLinkScope"]: """Gets a list of all Azure Monitor PrivateLinkScopes within a subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either AzureMonitorPrivateLinkScope or the result of cls(response) :rtype: @@ -259,10 +264,12 @@ def list(self, **kwargs: Any) -> Iterable["_models.AzureMonitorPrivateLinkScope" _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-07-01-preview") + ) cls: ClsType[_models.AzureMonitorPrivateLinkScopeListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -273,15 +280,13 @@ def list(self, **kwargs: Any) -> Iterable["_models.AzureMonitorPrivateLinkScope" def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _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) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -292,14 +297,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("AzureMonitorPrivateLinkScopeListResult", pipeline_response) @@ -309,11 +313,11 @@ def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -326,8 +330,6 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/microsoft.insights/privateLinkScopes"} - @distributed_trace def list_by_resource_group( self, resource_group_name: str, **kwargs: Any @@ -337,7 +339,6 @@ def list_by_resource_group( :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either AzureMonitorPrivateLinkScope or the result of cls(response) :rtype: @@ -347,10 +348,12 @@ def list_by_resource_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-07-01-preview") + ) cls: ClsType[_models.AzureMonitorPrivateLinkScopeListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -361,16 +364,14 @@ 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_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -381,14 +382,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("AzureMonitorPrivateLinkScopeListResult", pipeline_response) @@ -398,11 +398,11 @@ def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -415,14 +415,8 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/privateLinkScopes" - } - - def _delete_initial( # pylint: disable=inconsistent-return-statements - self, resource_group_name: str, scope_name: str, **kwargs: Any - ) -> None: - error_map = { + def _delete_initial(self, resource_group_name: str, scope_name: str, **kwargs: Any) -> Iterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -433,39 +427,44 @@ def _delete_initial( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) - cls: ClsType[None] = kwargs.pop("cls", None) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-07-01-preview") + ) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, scope_name=scope_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) + _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response 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.DefaultErrorResponse, 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_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/privateLinkScopes/{scopeName}" - } + return deserialized # type: ignore @distributed_trace def begin_delete(self, resource_group_name: str, scope_name: str, **kwargs: Any) -> LROPoller[None]: @@ -476,14 +475,6 @@ def begin_delete(self, resource_group_name: str, scope_name: str, **kwargs: Any) :type resource_group_name: str :param scope_name: The name of the Azure Monitor PrivateLinkScope resource. Required. :type scope_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: @@ -491,13 +482,15 @@ def begin_delete(self, resource_group_name: str, scope_name: str, **kwargs: Any) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-07-01-preview") + ) cls: ClsType[None] = kwargs.pop("cls", None) polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) cont_token: Optional[str] = kwargs.pop("continuation_token", None) if cont_token is None: - raw_result = self._delete_initial( # type: ignore + raw_result = self._delete_initial( resource_group_name=resource_group_name, scope_name=scope_name, api_version=api_version, @@ -506,11 +499,12 @@ def begin_delete(self, resource_group_name: str, scope_name: str, **kwargs: Any) params=_params, **kwargs ) + 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, {}) + return cls(pipeline_response, None, {}) # type: ignore if polling is True: polling_method: PollingMethod = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) @@ -519,17 +513,13 @@ def get_long_running_output(pipeline_response): # pylint: disable=inconsistent- else: polling_method = polling if cont_token: - return LROPoller.from_continuation_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(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/privateLinkScopes/{scopeName}" - } + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore @distributed_trace def get(self, resource_group_name: str, scope_name: str, **kwargs: Any) -> _models.AzureMonitorPrivateLinkScope: @@ -540,12 +530,11 @@ def get(self, resource_group_name: str, scope_name: str, **kwargs: Any) -> _mode :type resource_group_name: str :param scope_name: The name of the Azure Monitor PrivateLinkScope resource. Required. :type scope_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: AzureMonitorPrivateLinkScope or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_07_01_preview.models.AzureMonitorPrivateLinkScope :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -556,24 +545,24 @@ def get(self, resource_group_name: str, scope_name: str, **kwargs: Any) -> _mode _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-07-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-07-01-preview") + ) cls: ClsType[_models.AzureMonitorPrivateLinkScope] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, scope_name=scope_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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -583,16 +572,12 @@ def get(self, resource_group_name: str, scope_name: str, **kwargs: Any) -> _mode error = self._deserialize.failsafe_deserialize(_models.DefaultErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("AzureMonitorPrivateLinkScope", pipeline_response) + deserialized = self._deserialize("AzureMonitorPrivateLinkScope", 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.insights/privateLinkScopes/{scopeName}" - } + return deserialized # type: ignore @overload def create_or_update( @@ -619,7 +604,6 @@ def create_or_update( :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: AzureMonitorPrivateLinkScope or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_07_01_preview.models.AzureMonitorPrivateLinkScope :raises ~azure.core.exceptions.HttpResponseError: @@ -630,7 +614,7 @@ def create_or_update( self, resource_group_name: str, scope_name: str, - azure_monitor_private_link_scope_payload: IO, + azure_monitor_private_link_scope_payload: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -645,11 +629,10 @@ def create_or_update( :type scope_name: str :param azure_monitor_private_link_scope_payload: Properties that need to be specified to create or update a Azure Monitor PrivateLinkScope. Required. - :type azure_monitor_private_link_scope_payload: IO + :type azure_monitor_private_link_scope_payload: 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: AzureMonitorPrivateLinkScope or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_07_01_preview.models.AzureMonitorPrivateLinkScope :raises ~azure.core.exceptions.HttpResponseError: @@ -660,7 +643,7 @@ def create_or_update( self, resource_group_name: str, scope_name: str, - azure_monitor_private_link_scope_payload: Union[_models.AzureMonitorPrivateLinkScope, IO], + azure_monitor_private_link_scope_payload: Union[_models.AzureMonitorPrivateLinkScope, IO[bytes]], **kwargs: Any ) -> _models.AzureMonitorPrivateLinkScope: """Creates (or updates) a Azure Monitor PrivateLinkScope. Note: You cannot specify a different @@ -673,18 +656,14 @@ def create_or_update( :type scope_name: str :param azure_monitor_private_link_scope_payload: Properties that need to be specified to create or update a Azure Monitor PrivateLinkScope. Is either a AzureMonitorPrivateLinkScope type or a - IO type. Required. + IO[bytes] type. Required. :type azure_monitor_private_link_scope_payload: - ~azure.mgmt.monitor.v2021_07_01_preview.models.AzureMonitorPrivateLinkScope 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 + ~azure.mgmt.monitor.v2021_07_01_preview.models.AzureMonitorPrivateLinkScope or IO[bytes] :return: AzureMonitorPrivateLinkScope or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_07_01_preview.models.AzureMonitorPrivateLinkScope :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -695,19 +674,21 @@ def create_or_update( _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", "2021-07-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-07-01-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.AzureMonitorPrivateLinkScope] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(azure_monitor_private_link_scope_payload, (IO, bytes)): + if isinstance(azure_monitor_private_link_scope_payload, (IOBase, bytes)): _content = azure_monitor_private_link_scope_payload else: _json = self._serialize.body(azure_monitor_private_link_scope_payload, "AzureMonitorPrivateLinkScope") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, scope_name=scope_name, subscription_id=self._config.subscription_id, @@ -715,16 +696,14 @@ def create_or_update( 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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -734,21 +713,13 @@ def create_or_update( error = self._deserialize.failsafe_deserialize(_models.DefaultErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if response.status_code == 200: - deserialized = self._deserialize("AzureMonitorPrivateLinkScope", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("AzureMonitorPrivateLinkScope", pipeline_response) + deserialized = self._deserialize("AzureMonitorPrivateLinkScope", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/privateLinkScopes/{scopeName}" - } - @overload def update_tags( self, @@ -773,7 +744,6 @@ def update_tags( :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: AzureMonitorPrivateLinkScope or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_07_01_preview.models.AzureMonitorPrivateLinkScope :raises ~azure.core.exceptions.HttpResponseError: @@ -784,7 +754,7 @@ def update_tags( self, resource_group_name: str, scope_name: str, - private_link_scope_tags: IO, + private_link_scope_tags: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -799,11 +769,10 @@ def update_tags( :type scope_name: str :param private_link_scope_tags: Updated tag information to set into the PrivateLinkScope instance. Required. - :type private_link_scope_tags: IO + :type private_link_scope_tags: 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: AzureMonitorPrivateLinkScope or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_07_01_preview.models.AzureMonitorPrivateLinkScope :raises ~azure.core.exceptions.HttpResponseError: @@ -814,7 +783,7 @@ def update_tags( self, resource_group_name: str, scope_name: str, - private_link_scope_tags: Union[_models.TagsResource, IO], + private_link_scope_tags: Union[_models.TagsResource, IO[bytes]], **kwargs: Any ) -> _models.AzureMonitorPrivateLinkScope: """Updates an existing PrivateLinkScope's tags. To update other fields use the CreateOrUpdate @@ -826,18 +795,14 @@ def update_tags( :param scope_name: The name of the Azure Monitor PrivateLinkScope resource. Required. :type scope_name: str :param private_link_scope_tags: Updated tag information to set into the PrivateLinkScope - instance. Is either a TagsResource type or a IO type. Required. + instance. Is either a TagsResource type or a IO[bytes] type. Required. :type private_link_scope_tags: ~azure.mgmt.monitor.v2021_07_01_preview.models.TagsResource 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 + IO[bytes] :return: AzureMonitorPrivateLinkScope or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_07_01_preview.models.AzureMonitorPrivateLinkScope :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -848,19 +813,21 @@ def update_tags( _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", "2021-07-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-07-01-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.AzureMonitorPrivateLinkScope] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(private_link_scope_tags, (IO, bytes)): + if isinstance(private_link_scope_tags, (IOBase, bytes)): _content = private_link_scope_tags else: _json = self._serialize.body(private_link_scope_tags, "TagsResource") - request = build_update_tags_request( + _request = build_update_tags_request( resource_group_name=resource_group_name, scope_name=scope_name, subscription_id=self._config.subscription_id, @@ -868,16 +835,14 @@ def update_tags( content_type=content_type, json=_json, content=_content, - template_url=self.update_tags.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -887,13 +852,9 @@ def update_tags( error = self._deserialize.failsafe_deserialize(_models.DefaultErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("AzureMonitorPrivateLinkScope", pipeline_response) + deserialized = self._deserialize("AzureMonitorPrivateLinkScope", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - update_tags.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/privateLinkScopes/{scopeName}" - } + return deserialized # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_09_01/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_09_01/__init__.py index 2c7733bfd566..42cc62301757 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_09_01/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_09_01/__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 ._monitor_management_client import MonitorManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._monitor_management_client import MonitorManagementClient # type: ignore from ._version import VERSION __version__ = VERSION try: from ._patch import __all__ as _patch_all - from ._patch import * # 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__ = [ "MonitorManagementClient", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_09_01/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_09_01/_configuration.py index cacdad67be60..64d9cc99456d 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_09_01/_configuration.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_09_01/_configuration.py @@ -8,18 +8,16 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy from ._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MonitorManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class MonitorManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for MonitorManagementClient. Note that all parameters used to create this instance are saved as instance @@ -35,7 +33,6 @@ class MonitorManagementClientConfiguration(Configuration): # pylint: disable=to """ def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: - super(MonitorManagementClientConfiguration, self).__init__(**kwargs) api_version: str = kwargs.pop("api_version", "2021-09-01") if credential is None: @@ -48,6 +45,7 @@ def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-monitor/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -56,9 +54,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.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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_09_01/_metadata.json b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_09_01/_metadata.json index 58ac7be972a9..c96a4e3f6fae 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_09_01/_metadata.json +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_09_01/_metadata.json @@ -8,10 +8,10 @@ "host_value": "\"https://management.azure.com\"", "parameterized_host_template": null, "azure_arm": true, - "has_lro_operations": true, + "has_public_lro_operations": true, "client_side_validation": false, - "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"sdkcore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMAutoResourceProviderRegistrationPolicy\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}, \"stdlib\": {\"typing_extensions\": [\"Self\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"sdkcore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"AsyncARMAutoResourceProviderRegistrationPolicy\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}, \"stdlib\": {\"typing_extensions\": [\"Self\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "global_parameters": { "sync": { @@ -101,8 +101,8 @@ "credential_scopes": ["https://management.azure.com/.default"], "credential_call_sync": "ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", "credential_call_async": "AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", - "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "sync_imports": "{\"regular\": {\"sdkcore\": {\"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"regular\": {\"sdkcore\": {\"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "operation_groups": { "action_groups": "ActionGroupsOperations" diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_09_01/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_09_01/_monitor_management_client.py index 2ef72036c28a..22f3c15891e3 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_09_01/_monitor_management_client.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_09_01/_monitor_management_client.py @@ -8,9 +8,12 @@ from copy import deepcopy from typing import Any, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient +from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy from . import models as _models from .._serialization import Deserializer, Serializer @@ -18,11 +21,10 @@ from .operations import ActionGroupsOperations if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MonitorManagementClient: # pylint: disable=client-accepts-api-version-keyword +class MonitorManagementClient: """Monitor Management Client. :ivar action_groups: ActionGroupsOperations operations @@ -50,15 +52,35 @@ def __init__( self._config = MonitorManagementClientConfiguration( credential=credential, subscription_id=subscription_id, **kwargs ) - self._client: ARMPipelineClient = ARMPipelineClient(base_url=base_url, config=self._config, **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), + 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=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.action_groups = ActionGroupsOperations(self._client, self._config, self._serialize, self._deserialize) + self.action_groups = ActionGroupsOperations( + self._client, self._config, self._serialize, self._deserialize, "2021-09-01" + ) - 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 @@ -78,12 +100,12 @@ 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) -> None: self._client.close() - def __enter__(self) -> "MonitorManagementClient": + def __enter__(self) -> Self: self._client.__enter__() return self diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_09_01/_vendor.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_09_01/_vendor.py deleted file mode 100644 index bd0df84f5319..000000000000 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_09_01/_vendor.py +++ /dev/null @@ -1,30 +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 typing import List, cast - -from azure.core.pipeline.transport import HttpRequest - - -def _convert_request(request, files=None): - data = request.content if not files else None - request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) - if files: - request.set_formdata_body(files) - return request - - -def _format_url_section(template, **kwargs): - components = template.split("/") - while components: - try: - return template.format(**kwargs) - except KeyError as key: - # Need the cast, as for some reasons "split" is typed as list[str | Any] - formatted_components = cast(List[str], template.split("/")) - components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] - template = "/".join(components) diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_09_01/_version.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_09_01/_version.py index 394ee7c0c03c..e5754a47ce68 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_09_01/_version.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_09_01/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "6.0.2" +VERSION = "1.0.0b1" diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_09_01/aio/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_09_01/aio/__init__.py index 2c151bb41c19..3df30ff42149 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_09_01/aio/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_09_01/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 ._monitor_management_client import MonitorManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._monitor_management_client import MonitorManagementClient # type: ignore try: from ._patch import __all__ as _patch_all - from ._patch import * # 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__ = [ "MonitorManagementClient", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_09_01/aio/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_09_01/aio/_configuration.py index cbebb0cdaa7c..6a9cfa060d70 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_09_01/aio/_configuration.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_09_01/aio/_configuration.py @@ -8,18 +8,16 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy from .._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MonitorManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class MonitorManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for MonitorManagementClient. Note that all parameters used to create this instance are saved as instance @@ -35,7 +33,6 @@ class MonitorManagementClientConfiguration(Configuration): # pylint: disable=to """ def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: - super(MonitorManagementClientConfiguration, self).__init__(**kwargs) api_version: str = kwargs.pop("api_version", "2021-09-01") if credential is None: @@ -48,6 +45,7 @@ def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **k self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-monitor/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -56,9 +54,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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_09_01/aio/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_09_01/aio/_monitor_management_client.py index 91cba56ea223..de556df6f0e1 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_09_01/aio/_monitor_management_client.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_09_01/aio/_monitor_management_client.py @@ -8,9 +8,12 @@ from copy import deepcopy from typing import Any, Awaitable, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient +from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy from .. import models as _models from ..._serialization import Deserializer, Serializer @@ -18,11 +21,10 @@ from .operations import ActionGroupsOperations if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MonitorManagementClient: # pylint: disable=client-accepts-api-version-keyword +class MonitorManagementClient: """Monitor Management Client. :ivar action_groups: ActionGroupsOperations operations @@ -50,15 +52,37 @@ def __init__( self._config = MonitorManagementClientConfiguration( credential=credential, subscription_id=subscription_id, **kwargs ) - self._client: AsyncARMPipelineClient = AsyncARMPipelineClient(base_url=base_url, config=self._config, **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=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.action_groups = ActionGroupsOperations(self._client, self._config, self._serialize, self._deserialize) + self.action_groups = ActionGroupsOperations( + self._client, self._config, self._serialize, self._deserialize, "2021-09-01" + ) - 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 @@ -78,12 +102,12 @@ 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) -> "MonitorManagementClient": + async def __aenter__(self) -> Self: await self._client.__aenter__() return self diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_09_01/aio/operations/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_09_01/aio/operations/__init__.py index 05f0527dc979..410e631e0472 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_09_01/aio/operations/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_09_01/aio/operations/__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 ._action_groups_operations import ActionGroupsOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._action_groups_operations import ActionGroupsOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ "ActionGroupsOperations", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_09_01/aio/operations/_action_groups_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_09_01/aio/operations/_action_groups_operations.py index a25f3a940aeb..ca4a759bfd76 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_09_01/aio/operations/_action_groups_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_09_01/aio/operations/_action_groups_operations.py @@ -6,7 +6,9 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload +from io import IOBase +import sys +from typing import Any, AsyncIterable, AsyncIterator, Callable, Dict, IO, Optional, Type, TypeVar, Union, cast, overload import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList @@ -16,12 +18,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 @@ -29,7 +32,6 @@ from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models -from ..._vendor import _convert_request from ...operations._action_groups_operations import ( build_create_notifications_at_action_group_resource_level_request, build_create_notifications_at_resource_group_level_request, @@ -46,6 +48,10 @@ build_update_request, ) +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -68,6 +74,7 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @overload async def create_or_update( @@ -91,7 +98,6 @@ async def create_or_update( :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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_09_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -102,7 +108,7 @@ async def create_or_update( self, resource_group_name: str, action_group_name: str, - action_group: IO, + action_group: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -115,11 +121,10 @@ async def create_or_update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group: The action group to create or use for the update. Required. - :type action_group: IO + :type action_group: 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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_09_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -130,7 +135,7 @@ async def create_or_update( self, resource_group_name: str, action_group_name: str, - action_group: Union[_models.ActionGroupResource, IO], + action_group: Union[_models.ActionGroupResource, IO[bytes]], **kwargs: Any ) -> _models.ActionGroupResource: """Create a new action group or update an existing one. @@ -141,17 +146,13 @@ async def create_or_update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group: The action group to create or use for the update. Is either a - ActionGroupResource type or a IO type. Required. - :type action_group: ~azure.mgmt.monitor.v2021_09_01.models.ActionGroupResource 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 + ActionGroupResource type or a IO[bytes] type. Required. + :type action_group: ~azure.mgmt.monitor.v2021_09_01.models.ActionGroupResource or IO[bytes] :return: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_09_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -162,19 +163,19 @@ async def create_or_update( _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", "2021-09-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-09-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ActionGroupResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(action_group, (IO, bytes)): + if isinstance(action_group, (IOBase, bytes)): _content = action_group else: _json = self._serialize.body(action_group, "ActionGroupResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, action_group_name=action_group_name, subscription_id=self._config.subscription_id, @@ -182,16 +183,14 @@ async def create_or_update( 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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -201,21 +200,13 @@ async def create_or_update( 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("ActionGroupResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("ActionGroupResource", pipeline_response) + deserialized = self._deserialize("ActionGroupResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/actionGroups/{actionGroupName}" - } - @distributed_trace_async async def get(self, resource_group_name: str, action_group_name: str, **kwargs: Any) -> _models.ActionGroupResource: """Get an action group. @@ -225,12 +216,11 @@ async def get(self, resource_group_name: str, action_group_name: str, **kwargs: :type resource_group_name: str :param action_group_name: The name of the action group. Required. :type action_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_09_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -241,24 +231,22 @@ async def get(self, resource_group_name: str, action_group_name: str, **kwargs: _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-09-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-09-01")) cls: ClsType[_models.ActionGroupResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, action_group_name=action_group_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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -268,21 +256,15 @@ async def get(self, resource_group_name: str, action_group_name: str, **kwargs: error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ActionGroupResource", pipeline_response) + deserialized = self._deserialize("ActionGroupResource", 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.Insights/actionGroups/{actionGroupName}" - } + return deserialized # type: ignore @distributed_trace_async - async def delete( # pylint: disable=inconsistent-return-statements - self, resource_group_name: str, action_group_name: str, **kwargs: Any - ) -> None: + async def delete(self, resource_group_name: str, action_group_name: str, **kwargs: Any) -> None: """Delete an action group. :param resource_group_name: The name of the resource group. The name is case insensitive. @@ -290,12 +272,11 @@ async def delete( # pylint: disable=inconsistent-return-statements :type resource_group_name: str :param action_group_name: The name of the action group. Required. :type action_group_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, @@ -306,24 +287,22 @@ async def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-09-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-09-01")) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, action_group_name=action_group_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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -334,11 +313,7 @@ async def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/actionGroups/{actionGroupName}" - } + return cls(pipeline_response, None, {}) # type: ignore @overload async def update( @@ -362,7 +337,6 @@ async def update( :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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_09_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -373,7 +347,7 @@ async def update( self, resource_group_name: str, action_group_name: str, - action_group_patch: IO, + action_group_patch: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -386,11 +360,10 @@ async def update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group_patch: Parameters supplied to the operation. Required. - :type action_group_patch: IO + :type action_group_patch: 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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_09_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -401,7 +374,7 @@ async def update( self, resource_group_name: str, action_group_name: str, - action_group_patch: Union[_models.ActionGroupPatchBody, IO], + action_group_patch: Union[_models.ActionGroupPatchBody, IO[bytes]], **kwargs: Any ) -> _models.ActionGroupResource: """Updates an existing action group's tags. To update other fields use the CreateOrUpdate method. @@ -412,17 +385,14 @@ async def update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group_patch: Parameters supplied to the operation. Is either a - ActionGroupPatchBody type or a IO type. Required. - :type action_group_patch: ~azure.mgmt.monitor.v2021_09_01.models.ActionGroupPatchBody 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 + ActionGroupPatchBody type or a IO[bytes] type. Required. + :type action_group_patch: ~azure.mgmt.monitor.v2021_09_01.models.ActionGroupPatchBody or + IO[bytes] :return: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_09_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -433,19 +403,19 @@ async def update( _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", "2021-09-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-09-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ActionGroupResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(action_group_patch, (IO, bytes)): + if isinstance(action_group_patch, (IOBase, bytes)): _content = action_group_patch else: _json = self._serialize.body(action_group_patch, "ActionGroupPatchBody") - request = build_update_request( + _request = build_update_request( resource_group_name=resource_group_name, action_group_name=action_group_name, subscription_id=self._config.subscription_id, @@ -453,16 +423,14 @@ async def update( 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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -472,21 +440,17 @@ async def update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ActionGroupResource", pipeline_response) + deserialized = self._deserialize("ActionGroupResource", 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.Insights/actionGroups/{actionGroupName}" - } + return deserialized # type: ignore async def _post_test_notifications_initial( - self, notification_request: Union[_models.NotificationRequestBody, IO], **kwargs: Any - ) -> Optional[_models.TestNotificationDetailsResponse]: - error_map = { + self, notification_request: Union[_models.NotificationRequestBody, IO[bytes]], **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -497,59 +461,56 @@ async def _post_test_notifications_initial( _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", "2021-09-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-09-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Optional[_models.TestNotificationDetailsResponse]] = kwargs.pop("cls", None) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(notification_request, (IO, bytes)): + if isinstance(notification_request, (IOBase, bytes)): _content = notification_request else: _json = self._serialize.body(notification_request, "NotificationRequestBody") - request = build_post_test_notifications_request( + _request = build_post_test_notifications_request( subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, content=_content, - template_url=self._post_test_notifications_initial.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: + 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 = None response_headers = {} - if response.status_code == 200: - deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response) - if response.status_code == 202: response_headers["location"] = self._deserialize("str", response.headers.get("location")) - if cls: - return cls(pipeline_response, deserialized, response_headers) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - return deserialized + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore - _post_test_notifications_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/createNotifications" - } + return deserialized # type: ignore @overload async def begin_post_test_notifications( @@ -567,14 +528,6 @@ async def begin_post_test_notifications( :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 TestNotificationDetailsResponse or the result of cls(response) :rtype: @@ -584,24 +537,16 @@ async def begin_post_test_notifications( @overload async def begin_post_test_notifications( - self, notification_request: IO, *, content_type: str = "application/json", **kwargs: Any + self, notification_request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.TestNotificationDetailsResponse]: """Send test notifications to a set of provided receivers. :param notification_request: The notification request body which includes the contact details. Required. - :type notification_request: IO + :type notification_request: 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 TestNotificationDetailsResponse or the result of cls(response) :rtype: @@ -611,25 +556,14 @@ async def begin_post_test_notifications( @distributed_trace_async async def begin_post_test_notifications( - self, notification_request: Union[_models.NotificationRequestBody, IO], **kwargs: Any + self, notification_request: Union[_models.NotificationRequestBody, IO[bytes]], **kwargs: Any ) -> AsyncLROPoller[_models.TestNotificationDetailsResponse]: """Send test notifications to a set of provided receivers. :param notification_request: The notification request body which includes the contact details. - Is either a NotificationRequestBody type or a IO type. Required. + Is either a NotificationRequestBody type or a IO[bytes] type. Required. :type notification_request: ~azure.mgmt.monitor.v2021_09_01.models.NotificationRequestBody 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. + IO[bytes] :return: An instance of AsyncLROPoller that returns either TestNotificationDetailsResponse or the result of cls(response) :rtype: @@ -639,7 +573,7 @@ async def begin_post_test_notifications( _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", "2021-09-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-09-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.TestNotificationDetailsResponse] = kwargs.pop("cls", None) polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) @@ -655,12 +589,13 @@ async def begin_post_test_notifications( 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("TestNotificationDetailsResponse", pipeline_response) + deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: @@ -672,22 +607,23 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return AsyncLROPoller.from_continuation_token( + return AsyncLROPoller[_models.TestNotificationDetailsResponse].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_post_test_notifications.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/createNotifications" - } + return AsyncLROPoller[_models.TestNotificationDetailsResponse]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) async def _create_notifications_at_resource_group_level_initial( # pylint: disable=name-too-long - self, resource_group_name: str, notification_request: Union[_models.NotificationRequestBody, IO], **kwargs: Any - ) -> Optional[_models.TestNotificationDetailsResponse]: - error_map = { + self, + resource_group_name: str, + notification_request: Union[_models.NotificationRequestBody, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -698,60 +634,57 @@ async def _create_notifications_at_resource_group_level_initial( # pylint: disa _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", "2021-09-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-09-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Optional[_models.TestNotificationDetailsResponse]] = kwargs.pop("cls", None) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(notification_request, (IO, bytes)): + if isinstance(notification_request, (IOBase, bytes)): _content = notification_request else: _json = self._serialize.body(notification_request, "NotificationRequestBody") - request = build_create_notifications_at_resource_group_level_request( + _request = build_create_notifications_at_resource_group_level_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, content=_content, - template_url=self._create_notifications_at_resource_group_level_initial.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: + 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 = None response_headers = {} - if response.status_code == 200: - deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response) - if response.status_code == 202: response_headers["location"] = self._deserialize("str", response.headers.get("location")) - if cls: - return cls(pipeline_response, deserialized, response_headers) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - return deserialized + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore - _create_notifications_at_resource_group_level_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/createNotifications" - } + return deserialized # type: ignore @overload async def begin_create_notifications_at_resource_group_level( # pylint: disable=name-too-long @@ -773,14 +706,6 @@ async def begin_create_notifications_at_resource_group_level( # pylint: disable :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 TestNotificationDetailsResponse or the result of cls(response) :rtype: @@ -792,7 +717,7 @@ async def begin_create_notifications_at_resource_group_level( # pylint: disable async def begin_create_notifications_at_resource_group_level( # pylint: disable=name-too-long self, resource_group_name: str, - notification_request: IO, + notification_request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -804,18 +729,10 @@ async def begin_create_notifications_at_resource_group_level( # pylint: disable :type resource_group_name: str :param notification_request: The notification request body which includes the contact details. Required. - :type notification_request: IO + :type notification_request: 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 TestNotificationDetailsResponse or the result of cls(response) :rtype: @@ -825,7 +742,10 @@ async def begin_create_notifications_at_resource_group_level( # pylint: disable @distributed_trace_async async def begin_create_notifications_at_resource_group_level( # pylint: disable=name-too-long - self, resource_group_name: str, notification_request: Union[_models.NotificationRequestBody, IO], **kwargs: Any + self, + resource_group_name: str, + notification_request: Union[_models.NotificationRequestBody, IO[bytes]], + **kwargs: Any ) -> AsyncLROPoller[_models.TestNotificationDetailsResponse]: """Send test notifications to a set of provided receivers. @@ -833,20 +753,9 @@ async def begin_create_notifications_at_resource_group_level( # pylint: disable Required. :type resource_group_name: str :param notification_request: The notification request body which includes the contact details. - Is either a NotificationRequestBody type or a IO type. Required. + Is either a NotificationRequestBody type or a IO[bytes] type. Required. :type notification_request: ~azure.mgmt.monitor.v2021_09_01.models.NotificationRequestBody 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. + IO[bytes] :return: An instance of AsyncLROPoller that returns either TestNotificationDetailsResponse or the result of cls(response) :rtype: @@ -856,7 +765,7 @@ async def begin_create_notifications_at_resource_group_level( # pylint: disable _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", "2021-09-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-09-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.TestNotificationDetailsResponse] = kwargs.pop("cls", None) polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) @@ -873,12 +782,13 @@ async def begin_create_notifications_at_resource_group_level( # pylint: disable 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("TestNotificationDetailsResponse", pipeline_response) + deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: @@ -890,26 +800,24 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return AsyncLROPoller.from_continuation_token( + return AsyncLROPoller[_models.TestNotificationDetailsResponse].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_create_notifications_at_resource_group_level.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/createNotifications" - } + return AsyncLROPoller[_models.TestNotificationDetailsResponse]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) async def _create_notifications_at_action_group_resource_level_initial( # pylint: disable=name-too-long self, resource_group_name: str, action_group_name: str, - notification_request: Union[_models.NotificationRequestBody, IO], + notification_request: Union[_models.NotificationRequestBody, IO[bytes]], **kwargs: Any - ) -> Optional[_models.TestNotificationDetailsResponse]: - error_map = { + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -920,19 +828,19 @@ async def _create_notifications_at_action_group_resource_level_initial( # pylin _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", "2021-09-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-09-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Optional[_models.TestNotificationDetailsResponse]] = kwargs.pop("cls", None) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(notification_request, (IO, bytes)): + if isinstance(notification_request, (IOBase, bytes)): _content = notification_request else: _json = self._serialize.body(notification_request, "NotificationRequestBody") - request = build_create_notifications_at_action_group_resource_level_request( + _request = build_create_notifications_at_action_group_resource_level_request( resource_group_name=resource_group_name, action_group_name=action_group_name, subscription_id=self._config.subscription_id, @@ -940,41 +848,38 @@ async def _create_notifications_at_action_group_resource_level_initial( # pylin content_type=content_type, json=_json, content=_content, - template_url=self._create_notifications_at_action_group_resource_level_initial.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: + 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 = None response_headers = {} - if response.status_code == 200: - deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response) - if response.status_code == 202: response_headers["location"] = self._deserialize("str", response.headers.get("location")) - if cls: - return cls(pipeline_response, deserialized, response_headers) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - return deserialized + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore - _create_notifications_at_action_group_resource_level_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/actionGroups/{actionGroupName}/createNotifications" - } + return deserialized # type: ignore @overload async def begin_create_notifications_at_action_group_resource_level( # pylint: disable=name-too-long @@ -999,14 +904,6 @@ async def begin_create_notifications_at_action_group_resource_level( # pylint: :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 TestNotificationDetailsResponse or the result of cls(response) :rtype: @@ -1019,7 +916,7 @@ async def begin_create_notifications_at_action_group_resource_level( # pylint: self, resource_group_name: str, action_group_name: str, - notification_request: IO, + notification_request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -1033,18 +930,10 @@ async def begin_create_notifications_at_action_group_resource_level( # pylint: :type action_group_name: str :param notification_request: The notification request body which includes the contact details. Required. - :type notification_request: IO + :type notification_request: 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 TestNotificationDetailsResponse or the result of cls(response) :rtype: @@ -1057,7 +946,7 @@ async def begin_create_notifications_at_action_group_resource_level( # pylint: self, resource_group_name: str, action_group_name: str, - notification_request: Union[_models.NotificationRequestBody, IO], + notification_request: Union[_models.NotificationRequestBody, IO[bytes]], **kwargs: Any ) -> AsyncLROPoller[_models.TestNotificationDetailsResponse]: """Send test notifications to a set of provided receivers. @@ -1068,20 +957,9 @@ async def begin_create_notifications_at_action_group_resource_level( # pylint: :param action_group_name: The name of the action group. Required. :type action_group_name: str :param notification_request: The notification request body which includes the contact details. - Is either a NotificationRequestBody type or a IO type. Required. + Is either a NotificationRequestBody type or a IO[bytes] type. Required. :type notification_request: ~azure.mgmt.monitor.v2021_09_01.models.NotificationRequestBody 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. + IO[bytes] :return: An instance of AsyncLROPoller that returns either TestNotificationDetailsResponse or the result of cls(response) :rtype: @@ -1091,7 +969,7 @@ async def begin_create_notifications_at_action_group_resource_level( # pylint: _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", "2021-09-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-09-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.TestNotificationDetailsResponse] = kwargs.pop("cls", None) polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) @@ -1109,12 +987,13 @@ async def begin_create_notifications_at_action_group_resource_level( # pylint: 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("TestNotificationDetailsResponse", pipeline_response) + deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: @@ -1126,17 +1005,15 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return AsyncLROPoller.from_continuation_token( + return AsyncLROPoller[_models.TestNotificationDetailsResponse].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_create_notifications_at_action_group_resource_level.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/actionGroups/{actionGroupName}/createNotifications" - } + return AsyncLROPoller[_models.TestNotificationDetailsResponse]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) @distributed_trace_async async def get_test_notifications( @@ -1146,12 +1023,11 @@ async def get_test_notifications( :param notification_id: The notification id. Required. :type notification_id: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: TestNotificationDetailsResponse or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_09_01.models.TestNotificationDetailsResponse :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1162,23 +1038,21 @@ async def get_test_notifications( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-09-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-09-01")) cls: ClsType[_models.TestNotificationDetailsResponse] = kwargs.pop("cls", None) - request = build_get_test_notifications_request( + _request = build_get_test_notifications_request( notification_id=notification_id, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get_test_notifications.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1188,16 +1062,12 @@ async def get_test_notifications( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response) + deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get_test_notifications.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/notificationStatus/{notificationId}" - } + return deserialized # type: ignore @distributed_trace_async async def get_test_notifications_at_resource_group_level( # pylint: disable=name-too-long @@ -1210,12 +1080,11 @@ async def get_test_notifications_at_resource_group_level( # pylint: disable=nam :type resource_group_name: str :param notification_id: The notification id. Required. :type notification_id: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: TestNotificationDetailsResponse or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_09_01.models.TestNotificationDetailsResponse :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1226,24 +1095,22 @@ async def get_test_notifications_at_resource_group_level( # pylint: disable=nam _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-09-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-09-01")) cls: ClsType[_models.TestNotificationDetailsResponse] = kwargs.pop("cls", None) - request = build_get_test_notifications_at_resource_group_level_request( + _request = build_get_test_notifications_at_resource_group_level_request( resource_group_name=resource_group_name, notification_id=notification_id, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get_test_notifications_at_resource_group_level.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1253,16 +1120,12 @@ async def get_test_notifications_at_resource_group_level( # pylint: disable=nam error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response) + deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get_test_notifications_at_resource_group_level.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/notificationStatus/{notificationId}" - } + return deserialized # type: ignore @distributed_trace_async async def get_test_notifications_at_action_group_resource_level( # pylint: disable=name-too-long @@ -1277,12 +1140,11 @@ async def get_test_notifications_at_action_group_resource_level( # pylint: disa :type action_group_name: str :param notification_id: The notification id. Required. :type notification_id: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: TestNotificationDetailsResponse or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_09_01.models.TestNotificationDetailsResponse :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1293,25 +1155,23 @@ async def get_test_notifications_at_action_group_resource_level( # pylint: disa _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-09-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-09-01")) cls: ClsType[_models.TestNotificationDetailsResponse] = kwargs.pop("cls", None) - request = build_get_test_notifications_at_action_group_resource_level_request( + _request = build_get_test_notifications_at_action_group_resource_level_request( resource_group_name=resource_group_name, action_group_name=action_group_name, notification_id=notification_id, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get_test_notifications_at_action_group_resource_level.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1321,22 +1181,17 @@ async def get_test_notifications_at_action_group_resource_level( # pylint: disa error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response) + deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get_test_notifications_at_action_group_resource_level.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/actionGroups/{actionGroupName}/notificationStatus/{notificationId}" - } + return deserialized # type: ignore @distributed_trace def list_by_subscription_id(self, **kwargs: Any) -> AsyncIterable["_models.ActionGroupResource"]: """Get a list of all action groups in a subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ActionGroupResource or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.monitor.v2021_09_01.models.ActionGroupResource] @@ -1345,10 +1200,10 @@ def list_by_subscription_id(self, **kwargs: Any) -> AsyncIterable["_models.Actio _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-09-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-09-01")) cls: ClsType[_models.ActionGroupList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1359,15 +1214,13 @@ def list_by_subscription_id(self, **kwargs: Any) -> AsyncIterable["_models.Actio def prepare_request(next_link=None): if not next_link: - request = build_list_by_subscription_id_request( + _request = build_list_by_subscription_id_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_subscription_id.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -1378,14 +1231,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("ActionGroupList", pipeline_response) @@ -1395,11 +1247,11 @@ async def extract_data(pipeline_response): return None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1412,10 +1264,6 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_by_subscription_id.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/actionGroups" - } - @distributed_trace def list_by_resource_group( self, resource_group_name: str, **kwargs: Any @@ -1425,7 +1273,6 @@ def list_by_resource_group( :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ActionGroupResource or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.monitor.v2021_09_01.models.ActionGroupResource] @@ -1434,10 +1281,10 @@ def list_by_resource_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-09-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-09-01")) cls: ClsType[_models.ActionGroupList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1448,16 +1295,14 @@ 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_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -1468,14 +1313,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("ActionGroupList", pipeline_response) @@ -1485,11 +1329,11 @@ async def extract_data(pipeline_response): return None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1502,12 +1346,8 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/actionGroups" - } - @overload - async def enable_receiver( # pylint: disable=inconsistent-return-statements + async def enable_receiver( self, resource_group_name: str, action_group_name: str, @@ -1529,18 +1369,17 @@ async def enable_receiver( # pylint: disable=inconsistent-return-statements :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: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def enable_receiver( # pylint: disable=inconsistent-return-statements + async def enable_receiver( self, resource_group_name: str, action_group_name: str, - enable_request: IO, + enable_request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -1554,22 +1393,21 @@ async def enable_receiver( # pylint: disable=inconsistent-return-statements :param action_group_name: The name of the action group. Required. :type action_group_name: str :param enable_request: The receiver to re-enable. Required. - :type enable_request: IO + :type enable_request: 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: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async - async def enable_receiver( # pylint: disable=inconsistent-return-statements + async def enable_receiver( self, resource_group_name: str, action_group_name: str, - enable_request: Union[_models.EnableRequest, IO], + enable_request: Union[_models.EnableRequest, IO[bytes]], **kwargs: Any ) -> None: """Enable a receiver in an action group. This changes the receiver's status from Disabled to @@ -1580,41 +1418,40 @@ async def enable_receiver( # pylint: disable=inconsistent-return-statements :type resource_group_name: str :param action_group_name: The name of the action group. Required. :type action_group_name: str - :param enable_request: The receiver to re-enable. Is either a EnableRequest type or a IO type. - Required. - :type enable_request: ~azure.mgmt.monitor.v2021_09_01.models.EnableRequest 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 + :param enable_request: The receiver to re-enable. Is either a EnableRequest type or a IO[bytes] + type. Required. + :type enable_request: ~azure.mgmt.monitor.v2021_09_01.models.EnableRequest or IO[bytes] :return: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 304: ResourceNotModifiedError, - 409: lambda response: ResourceExistsError(response=response, error_format=ARMErrorFormat), + 409: cast( + Type[HttpResponseError], + lambda response: ResourceExistsError(response=response, error_format=ARMErrorFormat), + ), } 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: str = kwargs.pop("api_version", _params.pop("api-version", "2021-09-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-09-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[None] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(enable_request, (IO, bytes)): + if isinstance(enable_request, (IOBase, bytes)): _content = enable_request else: _json = self._serialize.body(enable_request, "EnableRequest") - request = build_enable_receiver_request( + _request = build_enable_receiver_request( resource_group_name=resource_group_name, action_group_name=action_group_name, subscription_id=self._config.subscription_id, @@ -1622,28 +1459,22 @@ async def enable_receiver( # pylint: disable=inconsistent-return-statements content_type=content_type, json=_json, content=_content, - template_url=self.enable_receiver.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _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) + map_error(status_code=response.status_code, response=response, error_map=error_map) # type: ignore 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, {}) - - enable_receiver.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/actionGroups/{actionGroupName}/subscribe" - } + return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_09_01/models/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_09_01/models/__init__.py index b1dac637c403..2e909d448f9e 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_09_01/models/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_09_01/models/__init__.py @@ -5,32 +5,43 @@ # 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 ActionDetail -from ._models_py3 import ActionGroupList -from ._models_py3 import ActionGroupPatchBody -from ._models_py3 import ActionGroupResource -from ._models_py3 import ArmRoleReceiver -from ._models_py3 import AutomationRunbookReceiver -from ._models_py3 import AzureAppPushReceiver -from ._models_py3 import AzureFunctionReceiver -from ._models_py3 import AzureResource -from ._models_py3 import Context -from ._models_py3 import EmailReceiver -from ._models_py3 import EnableRequest -from ._models_py3 import ErrorResponse -from ._models_py3 import EventHubReceiver -from ._models_py3 import ItsmReceiver -from ._models_py3 import LogicAppReceiver -from ._models_py3 import NotificationRequestBody -from ._models_py3 import SmsReceiver -from ._models_py3 import TestNotificationDetailsResponse -from ._models_py3 import VoiceReceiver -from ._models_py3 import WebhookReceiver +from typing import TYPE_CHECKING -from ._monitor_management_client_enums import ReceiverStatus +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models_py3 import ( # type: ignore + ActionDetail, + ActionGroupList, + ActionGroupPatchBody, + ActionGroupResource, + ArmRoleReceiver, + AutomationRunbookReceiver, + AzureAppPushReceiver, + AzureFunctionReceiver, + AzureResource, + Context, + EmailReceiver, + EnableRequest, + ErrorResponse, + EventHubReceiver, + ItsmReceiver, + LogicAppReceiver, + NotificationRequestBody, + SmsReceiver, + TestNotificationDetailsResponse, + VoiceReceiver, + WebhookReceiver, +) + +from ._monitor_management_client_enums import ( # type: ignore + ReceiverStatus, +) from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ @@ -57,5 +68,5 @@ "WebhookReceiver", "ReceiverStatus", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_09_01/models/_models_py3.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_09_01/models/_models_py3.py index 3894b56cc389..c4db2b9c8094 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_09_01/models/_models_py3.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_09_01/models/_models_py3.py @@ -1,5 +1,5 @@ -# coding=utf-8 # 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. @@ -12,7 +12,6 @@ from ... import _serialization if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from .. import models as _models @@ -141,7 +140,7 @@ class AzureResource(_serialization.Model): 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: Azure resource Id. :vartype id: str @@ -185,12 +184,12 @@ def __init__(self, *, location: str, tags: Optional[Dict[str, str]] = None, **kw self.tags = tags -class ActionGroupResource(AzureResource): # pylint: disable=too-many-instance-attributes +class ActionGroupResource(AzureResource): """An action group 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: Azure resource Id. :vartype id: str @@ -352,7 +351,7 @@ def __init__( class ArmRoleReceiver(_serialization.Model): """An arm role receiver. - 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 name of the arm role receiver. Names must be unique across all receivers within an action group. Required. @@ -393,7 +392,7 @@ def __init__(self, *, name: str, role_id: str, use_common_alert_schema: bool = F class AutomationRunbookReceiver(_serialization.Model): """The Azure Automation Runbook notification receiver. - 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 automation_account_id: The Azure automation account Id which holds this runbook and authenticate to Azure resource. Required. @@ -471,7 +470,7 @@ def __init__( class AzureAppPushReceiver(_serialization.Model): """The Azure mobile App push notification receiver. - 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 name of the Azure mobile app push receiver. Names must be unique across all receivers within an action group. Required. @@ -506,7 +505,7 @@ def __init__(self, *, name: str, email_address: str, **kwargs: Any) -> None: class AzureFunctionReceiver(_serialization.Model): """An azure function receiver. - 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 name of the azure function receiver. Names must be unique across all receivers within an action group. Required. @@ -600,7 +599,7 @@ class EmailReceiver(_serialization.Model): 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 name: The name of the email receiver. Names must be unique across all receivers within an action group. Required. @@ -647,7 +646,7 @@ def __init__(self, *, name: str, email_address: str, use_common_alert_schema: bo class EnableRequest(_serialization.Model): """Describes a receiver that should be resubscribed. - 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 receiver_name: The name of the receiver to resubscribe. Required. :vartype receiver_name: str @@ -699,7 +698,7 @@ def __init__(self, *, code: Optional[str] = None, message: Optional[str] = None, class EventHubReceiver(_serialization.Model): """An Event hub receiver. - 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 name of the Event hub receiver. Names must be unique across all receivers within an action group. Required. @@ -770,7 +769,7 @@ def __init__( class ItsmReceiver(_serialization.Model): """An Itsm receiver. - 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 name of the Itsm receiver. Names must be unique across all receivers within an action group. Required. @@ -784,7 +783,7 @@ class ItsmReceiver(_serialization.Model): CreateMultipleWorkItems option will be part of this blob as well. Required. :vartype ticket_configuration: str :ivar region: Region in which workspace resides. Supported - values:'centralindia','japaneast','southeastasia','australiasoutheast','uksouth','westcentralus','canadacentral','eastus','westeurope'. + values:'centralindia','japaneast','southeastasia','australiasoutheast','uksouth','westcentralus','canadacentral','eastus','westeurope'. # pylint: disable=line-too-long Required. :vartype region: str """ @@ -821,7 +820,7 @@ def __init__( CreateMultipleWorkItems option will be part of this blob as well. Required. :paramtype ticket_configuration: str :keyword region: Region in which workspace resides. Supported - values:'centralindia','japaneast','southeastasia','australiasoutheast','uksouth','westcentralus','canadacentral','eastus','westeurope'. + values:'centralindia','japaneast','southeastasia','australiasoutheast','uksouth','westcentralus','canadacentral','eastus','westeurope'. # pylint: disable=line-too-long Required. :paramtype region: str """ @@ -836,7 +835,7 @@ def __init__( class LogicAppReceiver(_serialization.Model): """A logic app receiver. - 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 name of the logic app receiver. Names must be unique across all receivers within an action group. Required. @@ -883,10 +882,10 @@ def __init__( self.use_common_alert_schema = use_common_alert_schema -class NotificationRequestBody(_serialization.Model): # pylint: disable=too-many-instance-attributes +class NotificationRequestBody(_serialization.Model): """The request body which contain contact detail metadata. - 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 alert_type: The value of the supported alert type. Supported alert type values are: servicehealth, metricstaticthreshold, metricsdynamicthreshold, logalertv2, smartalert, @@ -1018,7 +1017,7 @@ class SmsReceiver(_serialization.Model): 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 name: The name of the SMS receiver. Names must be unique across all receivers within an action group. Required. @@ -1066,7 +1065,7 @@ def __init__(self, *, name: str, country_code: str, phone_number: str, **kwargs: class TestNotificationDetailsResponse(_serialization.Model): """The details of the test notification results. - 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 context: The context info. :vartype context: ~azure.mgmt.monitor.v2021_09_01.models.Context @@ -1125,7 +1124,7 @@ def __init__( class VoiceReceiver(_serialization.Model): """A voice receiver. - 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 name of the voice receiver. Names must be unique across all receivers within an action group. Required. @@ -1167,7 +1166,7 @@ def __init__(self, *, name: str, country_code: str, phone_number: str, **kwargs: class WebhookReceiver(_serialization.Model): """A webhook receiver. - 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 name of the webhook receiver. Names must be unique across all receivers within an action group. Required. diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_09_01/operations/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_09_01/operations/__init__.py index 05f0527dc979..410e631e0472 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_09_01/operations/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_09_01/operations/__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 ._action_groups_operations import ActionGroupsOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._action_groups_operations import ActionGroupsOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ "ActionGroupsOperations", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_09_01/operations/_action_groups_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_09_01/operations/_action_groups_operations.py index 1d0a98482f43..127feaf2126e 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_09_01/operations/_action_groups_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_09_01/operations/_action_groups_operations.py @@ -6,7 +6,9 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload +from io import IOBase +import sys +from typing import Any, Callable, Dict, IO, Iterable, Iterator, Optional, Type, TypeVar, Union, cast, overload import urllib.parse from azure.core.exceptions import ( @@ -15,13 +17,14 @@ 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 @@ -29,8 +32,11 @@ from .. import models as _models from ..._serialization import Serializer -from .._vendor import _convert_request, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -61,7 +67,7 @@ def build_create_or_update_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -96,7 +102,7 @@ def build_get_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -129,7 +135,7 @@ def build_delete_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -163,7 +169,7 @@ def build_update_request( "actionGroupName": _SERIALIZER.url("action_group_name", action_group_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -192,7 +198,7 @@ def build_post_test_notifications_request(subscription_id: str, **kwargs: Any) - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -227,7 +233,7 @@ def build_create_notifications_at_resource_group_level_request( # pylint: disab ), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -263,7 +269,7 @@ def build_create_notifications_at_action_group_resource_level_request( # pylint "actionGroupName": _SERIALIZER.url("action_group_name", action_group_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -293,7 +299,7 @@ def build_get_test_notifications_request(notification_id: str, subscription_id: "notificationId": _SERIALIZER.url("notification_id", notification_id, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -326,7 +332,7 @@ def build_get_test_notifications_at_resource_group_level_request( # pylint: dis "notificationId": _SERIALIZER.url("notification_id", notification_id, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -360,7 +366,7 @@ def build_get_test_notifications_at_action_group_resource_level_request( # pyli "notificationId": _SERIALIZER.url("notification_id", notification_id, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -384,7 +390,7 @@ def build_list_by_subscription_id_request(subscription_id: str, **kwargs: Any) - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -414,7 +420,7 @@ def build_list_by_resource_group_request(resource_group_name: str, subscription_ "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -448,7 +454,7 @@ def build_enable_receiver_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -479,6 +485,7 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @overload def create_or_update( @@ -502,7 +509,6 @@ def create_or_update( :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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_09_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -513,7 +519,7 @@ def create_or_update( self, resource_group_name: str, action_group_name: str, - action_group: IO, + action_group: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -526,11 +532,10 @@ def create_or_update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group: The action group to create or use for the update. Required. - :type action_group: IO + :type action_group: 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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_09_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -541,7 +546,7 @@ def create_or_update( self, resource_group_name: str, action_group_name: str, - action_group: Union[_models.ActionGroupResource, IO], + action_group: Union[_models.ActionGroupResource, IO[bytes]], **kwargs: Any ) -> _models.ActionGroupResource: """Create a new action group or update an existing one. @@ -552,17 +557,13 @@ def create_or_update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group: The action group to create or use for the update. Is either a - ActionGroupResource type or a IO type. Required. - :type action_group: ~azure.mgmt.monitor.v2021_09_01.models.ActionGroupResource 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 + ActionGroupResource type or a IO[bytes] type. Required. + :type action_group: ~azure.mgmt.monitor.v2021_09_01.models.ActionGroupResource or IO[bytes] :return: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_09_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -573,19 +574,19 @@ def create_or_update( _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", "2021-09-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-09-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ActionGroupResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(action_group, (IO, bytes)): + if isinstance(action_group, (IOBase, bytes)): _content = action_group else: _json = self._serialize.body(action_group, "ActionGroupResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, action_group_name=action_group_name, subscription_id=self._config.subscription_id, @@ -593,16 +594,14 @@ def create_or_update( 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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -612,21 +611,13 @@ def create_or_update( 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("ActionGroupResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("ActionGroupResource", pipeline_response) + deserialized = self._deserialize("ActionGroupResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/actionGroups/{actionGroupName}" - } - @distributed_trace def get(self, resource_group_name: str, action_group_name: str, **kwargs: Any) -> _models.ActionGroupResource: """Get an action group. @@ -636,12 +627,11 @@ def get(self, resource_group_name: str, action_group_name: str, **kwargs: Any) - :type resource_group_name: str :param action_group_name: The name of the action group. Required. :type action_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_09_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -652,24 +642,22 @@ def get(self, resource_group_name: str, action_group_name: str, **kwargs: Any) - _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-09-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-09-01")) cls: ClsType[_models.ActionGroupResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, action_group_name=action_group_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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -679,16 +667,12 @@ def get(self, resource_group_name: str, action_group_name: str, **kwargs: Any) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ActionGroupResource", pipeline_response) + deserialized = self._deserialize("ActionGroupResource", 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.Insights/actionGroups/{actionGroupName}" - } + return deserialized # type: ignore @distributed_trace def delete( # pylint: disable=inconsistent-return-statements @@ -701,12 +685,11 @@ def delete( # pylint: disable=inconsistent-return-statements :type resource_group_name: str :param action_group_name: The name of the action group. Required. :type action_group_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, @@ -717,24 +700,22 @@ def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-09-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-09-01")) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, action_group_name=action_group_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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -745,11 +726,7 @@ def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/actionGroups/{actionGroupName}" - } + return cls(pipeline_response, None, {}) # type: ignore @overload def update( @@ -773,7 +750,6 @@ def update( :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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_09_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -784,7 +760,7 @@ def update( self, resource_group_name: str, action_group_name: str, - action_group_patch: IO, + action_group_patch: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -797,11 +773,10 @@ def update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group_patch: Parameters supplied to the operation. Required. - :type action_group_patch: IO + :type action_group_patch: 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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_09_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -812,7 +787,7 @@ def update( self, resource_group_name: str, action_group_name: str, - action_group_patch: Union[_models.ActionGroupPatchBody, IO], + action_group_patch: Union[_models.ActionGroupPatchBody, IO[bytes]], **kwargs: Any ) -> _models.ActionGroupResource: """Updates an existing action group's tags. To update other fields use the CreateOrUpdate method. @@ -823,17 +798,14 @@ def update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group_patch: Parameters supplied to the operation. Is either a - ActionGroupPatchBody type or a IO type. Required. - :type action_group_patch: ~azure.mgmt.monitor.v2021_09_01.models.ActionGroupPatchBody 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 + ActionGroupPatchBody type or a IO[bytes] type. Required. + :type action_group_patch: ~azure.mgmt.monitor.v2021_09_01.models.ActionGroupPatchBody or + IO[bytes] :return: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_09_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -844,19 +816,19 @@ def update( _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", "2021-09-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-09-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ActionGroupResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(action_group_patch, (IO, bytes)): + if isinstance(action_group_patch, (IOBase, bytes)): _content = action_group_patch else: _json = self._serialize.body(action_group_patch, "ActionGroupPatchBody") - request = build_update_request( + _request = build_update_request( resource_group_name=resource_group_name, action_group_name=action_group_name, subscription_id=self._config.subscription_id, @@ -864,16 +836,14 @@ def update( 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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -883,21 +853,17 @@ def update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ActionGroupResource", pipeline_response) + deserialized = self._deserialize("ActionGroupResource", 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.Insights/actionGroups/{actionGroupName}" - } + return deserialized # type: ignore def _post_test_notifications_initial( - self, notification_request: Union[_models.NotificationRequestBody, IO], **kwargs: Any - ) -> Optional[_models.TestNotificationDetailsResponse]: - error_map = { + self, notification_request: Union[_models.NotificationRequestBody, IO[bytes]], **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -908,59 +874,56 @@ def _post_test_notifications_initial( _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", "2021-09-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-09-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Optional[_models.TestNotificationDetailsResponse]] = kwargs.pop("cls", None) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(notification_request, (IO, bytes)): + if isinstance(notification_request, (IOBase, bytes)): _content = notification_request else: _json = self._serialize.body(notification_request, "NotificationRequestBody") - request = build_post_test_notifications_request( + _request = build_post_test_notifications_request( subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, content=_content, - template_url=self._post_test_notifications_initial.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: + 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) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = None response_headers = {} - if response.status_code == 200: - deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response) - if response.status_code == 202: response_headers["location"] = self._deserialize("str", response.headers.get("location")) - if cls: - return cls(pipeline_response, deserialized, response_headers) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - return deserialized + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore - _post_test_notifications_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/createNotifications" - } + return deserialized # type: ignore @overload def begin_post_test_notifications( @@ -978,14 +941,6 @@ def begin_post_test_notifications( :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 TestNotificationDetailsResponse or the result of cls(response) :rtype: @@ -995,24 +950,16 @@ def begin_post_test_notifications( @overload def begin_post_test_notifications( - self, notification_request: IO, *, content_type: str = "application/json", **kwargs: Any + self, notification_request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.TestNotificationDetailsResponse]: """Send test notifications to a set of provided receivers. :param notification_request: The notification request body which includes the contact details. Required. - :type notification_request: IO + :type notification_request: 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 TestNotificationDetailsResponse or the result of cls(response) :rtype: @@ -1022,25 +969,14 @@ def begin_post_test_notifications( @distributed_trace def begin_post_test_notifications( - self, notification_request: Union[_models.NotificationRequestBody, IO], **kwargs: Any + self, notification_request: Union[_models.NotificationRequestBody, IO[bytes]], **kwargs: Any ) -> LROPoller[_models.TestNotificationDetailsResponse]: """Send test notifications to a set of provided receivers. :param notification_request: The notification request body which includes the contact details. - Is either a NotificationRequestBody type or a IO type. Required. + Is either a NotificationRequestBody type or a IO[bytes] type. Required. :type notification_request: ~azure.mgmt.monitor.v2021_09_01.models.NotificationRequestBody 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. + IO[bytes] :return: An instance of LROPoller that returns either TestNotificationDetailsResponse or the result of cls(response) :rtype: @@ -1050,7 +986,7 @@ def begin_post_test_notifications( _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", "2021-09-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-09-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.TestNotificationDetailsResponse] = kwargs.pop("cls", None) polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) @@ -1066,12 +1002,13 @@ def begin_post_test_notifications( 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("TestNotificationDetailsResponse", pipeline_response) + deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: @@ -1083,22 +1020,23 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return LROPoller.from_continuation_token( + return LROPoller[_models.TestNotificationDetailsResponse].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_post_test_notifications.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/createNotifications" - } + return LROPoller[_models.TestNotificationDetailsResponse]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) def _create_notifications_at_resource_group_level_initial( # pylint: disable=name-too-long - self, resource_group_name: str, notification_request: Union[_models.NotificationRequestBody, IO], **kwargs: Any - ) -> Optional[_models.TestNotificationDetailsResponse]: - error_map = { + self, + resource_group_name: str, + notification_request: Union[_models.NotificationRequestBody, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1109,60 +1047,57 @@ def _create_notifications_at_resource_group_level_initial( # pylint: disable=na _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", "2021-09-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-09-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Optional[_models.TestNotificationDetailsResponse]] = kwargs.pop("cls", None) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(notification_request, (IO, bytes)): + if isinstance(notification_request, (IOBase, bytes)): _content = notification_request else: _json = self._serialize.body(notification_request, "NotificationRequestBody") - request = build_create_notifications_at_resource_group_level_request( + _request = build_create_notifications_at_resource_group_level_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, content=_content, - template_url=self._create_notifications_at_resource_group_level_initial.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: + 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) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = None response_headers = {} - if response.status_code == 200: - deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response) - if response.status_code == 202: response_headers["location"] = self._deserialize("str", response.headers.get("location")) - if cls: - return cls(pipeline_response, deserialized, response_headers) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - return deserialized + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore - _create_notifications_at_resource_group_level_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/createNotifications" - } + return deserialized # type: ignore @overload def begin_create_notifications_at_resource_group_level( # pylint: disable=name-too-long @@ -1184,14 +1119,6 @@ def begin_create_notifications_at_resource_group_level( # pylint: disable=name- :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 TestNotificationDetailsResponse or the result of cls(response) :rtype: @@ -1203,7 +1130,7 @@ def begin_create_notifications_at_resource_group_level( # pylint: disable=name- def begin_create_notifications_at_resource_group_level( # pylint: disable=name-too-long self, resource_group_name: str, - notification_request: IO, + notification_request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -1215,18 +1142,10 @@ def begin_create_notifications_at_resource_group_level( # pylint: disable=name- :type resource_group_name: str :param notification_request: The notification request body which includes the contact details. Required. - :type notification_request: IO + :type notification_request: 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 TestNotificationDetailsResponse or the result of cls(response) :rtype: @@ -1236,7 +1155,10 @@ def begin_create_notifications_at_resource_group_level( # pylint: disable=name- @distributed_trace def begin_create_notifications_at_resource_group_level( # pylint: disable=name-too-long - self, resource_group_name: str, notification_request: Union[_models.NotificationRequestBody, IO], **kwargs: Any + self, + resource_group_name: str, + notification_request: Union[_models.NotificationRequestBody, IO[bytes]], + **kwargs: Any ) -> LROPoller[_models.TestNotificationDetailsResponse]: """Send test notifications to a set of provided receivers. @@ -1244,20 +1166,9 @@ def begin_create_notifications_at_resource_group_level( # pylint: disable=name- Required. :type resource_group_name: str :param notification_request: The notification request body which includes the contact details. - Is either a NotificationRequestBody type or a IO type. Required. + Is either a NotificationRequestBody type or a IO[bytes] type. Required. :type notification_request: ~azure.mgmt.monitor.v2021_09_01.models.NotificationRequestBody 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. + IO[bytes] :return: An instance of LROPoller that returns either TestNotificationDetailsResponse or the result of cls(response) :rtype: @@ -1267,7 +1178,7 @@ def begin_create_notifications_at_resource_group_level( # pylint: disable=name- _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", "2021-09-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-09-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.TestNotificationDetailsResponse] = kwargs.pop("cls", None) polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) @@ -1284,12 +1195,13 @@ def begin_create_notifications_at_resource_group_level( # pylint: disable=name- 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("TestNotificationDetailsResponse", pipeline_response) + deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: @@ -1301,26 +1213,24 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return LROPoller.from_continuation_token( + return LROPoller[_models.TestNotificationDetailsResponse].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_create_notifications_at_resource_group_level.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/createNotifications" - } + return LROPoller[_models.TestNotificationDetailsResponse]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) def _create_notifications_at_action_group_resource_level_initial( # pylint: disable=name-too-long self, resource_group_name: str, action_group_name: str, - notification_request: Union[_models.NotificationRequestBody, IO], + notification_request: Union[_models.NotificationRequestBody, IO[bytes]], **kwargs: Any - ) -> Optional[_models.TestNotificationDetailsResponse]: - error_map = { + ) -> Iterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1331,19 +1241,19 @@ def _create_notifications_at_action_group_resource_level_initial( # pylint: dis _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", "2021-09-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-09-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Optional[_models.TestNotificationDetailsResponse]] = kwargs.pop("cls", None) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(notification_request, (IO, bytes)): + if isinstance(notification_request, (IOBase, bytes)): _content = notification_request else: _json = self._serialize.body(notification_request, "NotificationRequestBody") - request = build_create_notifications_at_action_group_resource_level_request( + _request = build_create_notifications_at_action_group_resource_level_request( resource_group_name=resource_group_name, action_group_name=action_group_name, subscription_id=self._config.subscription_id, @@ -1351,41 +1261,38 @@ def _create_notifications_at_action_group_resource_level_initial( # pylint: dis content_type=content_type, json=_json, content=_content, - template_url=self._create_notifications_at_action_group_resource_level_initial.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: + 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) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = None response_headers = {} - if response.status_code == 200: - deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response) - if response.status_code == 202: response_headers["location"] = self._deserialize("str", response.headers.get("location")) - if cls: - return cls(pipeline_response, deserialized, response_headers) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - return deserialized + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore - _create_notifications_at_action_group_resource_level_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/actionGroups/{actionGroupName}/createNotifications" - } + return deserialized # type: ignore @overload def begin_create_notifications_at_action_group_resource_level( # pylint: disable=name-too-long @@ -1410,14 +1317,6 @@ def begin_create_notifications_at_action_group_resource_level( # pylint: disabl :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 TestNotificationDetailsResponse or the result of cls(response) :rtype: @@ -1430,7 +1329,7 @@ def begin_create_notifications_at_action_group_resource_level( # pylint: disabl self, resource_group_name: str, action_group_name: str, - notification_request: IO, + notification_request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -1444,18 +1343,10 @@ def begin_create_notifications_at_action_group_resource_level( # pylint: disabl :type action_group_name: str :param notification_request: The notification request body which includes the contact details. Required. - :type notification_request: IO + :type notification_request: 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 TestNotificationDetailsResponse or the result of cls(response) :rtype: @@ -1468,7 +1359,7 @@ def begin_create_notifications_at_action_group_resource_level( # pylint: disabl self, resource_group_name: str, action_group_name: str, - notification_request: Union[_models.NotificationRequestBody, IO], + notification_request: Union[_models.NotificationRequestBody, IO[bytes]], **kwargs: Any ) -> LROPoller[_models.TestNotificationDetailsResponse]: """Send test notifications to a set of provided receivers. @@ -1479,20 +1370,9 @@ def begin_create_notifications_at_action_group_resource_level( # pylint: disabl :param action_group_name: The name of the action group. Required. :type action_group_name: str :param notification_request: The notification request body which includes the contact details. - Is either a NotificationRequestBody type or a IO type. Required. + Is either a NotificationRequestBody type or a IO[bytes] type. Required. :type notification_request: ~azure.mgmt.monitor.v2021_09_01.models.NotificationRequestBody 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. + IO[bytes] :return: An instance of LROPoller that returns either TestNotificationDetailsResponse or the result of cls(response) :rtype: @@ -1502,7 +1382,7 @@ def begin_create_notifications_at_action_group_resource_level( # pylint: disabl _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", "2021-09-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-09-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.TestNotificationDetailsResponse] = kwargs.pop("cls", None) polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) @@ -1520,12 +1400,13 @@ def begin_create_notifications_at_action_group_resource_level( # pylint: disabl 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("TestNotificationDetailsResponse", pipeline_response) + deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: @@ -1537,17 +1418,15 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return LROPoller.from_continuation_token( + return LROPoller[_models.TestNotificationDetailsResponse].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_create_notifications_at_action_group_resource_level.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/actionGroups/{actionGroupName}/createNotifications" - } + return LROPoller[_models.TestNotificationDetailsResponse]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) @distributed_trace def get_test_notifications(self, notification_id: str, **kwargs: Any) -> _models.TestNotificationDetailsResponse: @@ -1555,12 +1434,11 @@ def get_test_notifications(self, notification_id: str, **kwargs: Any) -> _models :param notification_id: The notification id. Required. :type notification_id: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: TestNotificationDetailsResponse or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_09_01.models.TestNotificationDetailsResponse :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1571,23 +1449,21 @@ def get_test_notifications(self, notification_id: str, **kwargs: Any) -> _models _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-09-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-09-01")) cls: ClsType[_models.TestNotificationDetailsResponse] = kwargs.pop("cls", None) - request = build_get_test_notifications_request( + _request = build_get_test_notifications_request( notification_id=notification_id, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get_test_notifications.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1597,16 +1473,12 @@ def get_test_notifications(self, notification_id: str, **kwargs: Any) -> _models error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response) + deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get_test_notifications.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/notificationStatus/{notificationId}" - } + return deserialized # type: ignore @distributed_trace def get_test_notifications_at_resource_group_level( # pylint: disable=name-too-long @@ -1619,12 +1491,11 @@ def get_test_notifications_at_resource_group_level( # pylint: disable=name-too- :type resource_group_name: str :param notification_id: The notification id. Required. :type notification_id: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: TestNotificationDetailsResponse or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_09_01.models.TestNotificationDetailsResponse :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1635,24 +1506,22 @@ def get_test_notifications_at_resource_group_level( # pylint: disable=name-too- _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-09-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-09-01")) cls: ClsType[_models.TestNotificationDetailsResponse] = kwargs.pop("cls", None) - request = build_get_test_notifications_at_resource_group_level_request( + _request = build_get_test_notifications_at_resource_group_level_request( resource_group_name=resource_group_name, notification_id=notification_id, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get_test_notifications_at_resource_group_level.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1662,16 +1531,12 @@ def get_test_notifications_at_resource_group_level( # pylint: disable=name-too- error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response) + deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get_test_notifications_at_resource_group_level.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/notificationStatus/{notificationId}" - } + return deserialized # type: ignore @distributed_trace def get_test_notifications_at_action_group_resource_level( # pylint: disable=name-too-long @@ -1686,12 +1551,11 @@ def get_test_notifications_at_action_group_resource_level( # pylint: disable=na :type action_group_name: str :param notification_id: The notification id. Required. :type notification_id: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: TestNotificationDetailsResponse or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2021_09_01.models.TestNotificationDetailsResponse :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1702,25 +1566,23 @@ def get_test_notifications_at_action_group_resource_level( # pylint: disable=na _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-09-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-09-01")) cls: ClsType[_models.TestNotificationDetailsResponse] = kwargs.pop("cls", None) - request = build_get_test_notifications_at_action_group_resource_level_request( + _request = build_get_test_notifications_at_action_group_resource_level_request( resource_group_name=resource_group_name, action_group_name=action_group_name, notification_id=notification_id, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get_test_notifications_at_action_group_resource_level.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1730,22 +1592,17 @@ def get_test_notifications_at_action_group_resource_level( # pylint: disable=na error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response) + deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get_test_notifications_at_action_group_resource_level.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/actionGroups/{actionGroupName}/notificationStatus/{notificationId}" - } + return deserialized # type: ignore @distributed_trace def list_by_subscription_id(self, **kwargs: Any) -> Iterable["_models.ActionGroupResource"]: """Get a list of all action groups in a subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ActionGroupResource or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.monitor.v2021_09_01.models.ActionGroupResource] @@ -1754,10 +1611,10 @@ def list_by_subscription_id(self, **kwargs: Any) -> Iterable["_models.ActionGrou _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-09-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-09-01")) cls: ClsType[_models.ActionGroupList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1768,15 +1625,13 @@ def list_by_subscription_id(self, **kwargs: Any) -> Iterable["_models.ActionGrou def prepare_request(next_link=None): if not next_link: - request = build_list_by_subscription_id_request( + _request = build_list_by_subscription_id_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_subscription_id.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -1787,14 +1642,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("ActionGroupList", pipeline_response) @@ -1804,11 +1658,11 @@ def extract_data(pipeline_response): return None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1821,10 +1675,6 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_by_subscription_id.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/actionGroups" - } - @distributed_trace def list_by_resource_group( self, resource_group_name: str, **kwargs: Any @@ -1834,7 +1684,6 @@ def list_by_resource_group( :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ActionGroupResource or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.monitor.v2021_09_01.models.ActionGroupResource] @@ -1843,10 +1692,10 @@ def list_by_resource_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-09-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-09-01")) cls: ClsType[_models.ActionGroupList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1857,16 +1706,14 @@ 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_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -1877,14 +1724,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("ActionGroupList", pipeline_response) @@ -1894,11 +1740,11 @@ def extract_data(pipeline_response): return None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1911,12 +1757,8 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/actionGroups" - } - @overload - def enable_receiver( # pylint: disable=inconsistent-return-statements + def enable_receiver( self, resource_group_name: str, action_group_name: str, @@ -1938,18 +1780,17 @@ def enable_receiver( # pylint: disable=inconsistent-return-statements :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: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def enable_receiver( # pylint: disable=inconsistent-return-statements + def enable_receiver( self, resource_group_name: str, action_group_name: str, - enable_request: IO, + enable_request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -1963,11 +1804,10 @@ def enable_receiver( # pylint: disable=inconsistent-return-statements :param action_group_name: The name of the action group. Required. :type action_group_name: str :param enable_request: The receiver to re-enable. Required. - :type enable_request: IO + :type enable_request: 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: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1978,7 +1818,7 @@ def enable_receiver( # pylint: disable=inconsistent-return-statements self, resource_group_name: str, action_group_name: str, - enable_request: Union[_models.EnableRequest, IO], + enable_request: Union[_models.EnableRequest, IO[bytes]], **kwargs: Any ) -> None: """Enable a receiver in an action group. This changes the receiver's status from Disabled to @@ -1989,41 +1829,40 @@ def enable_receiver( # pylint: disable=inconsistent-return-statements :type resource_group_name: str :param action_group_name: The name of the action group. Required. :type action_group_name: str - :param enable_request: The receiver to re-enable. Is either a EnableRequest type or a IO type. - Required. - :type enable_request: ~azure.mgmt.monitor.v2021_09_01.models.EnableRequest 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 + :param enable_request: The receiver to re-enable. Is either a EnableRequest type or a IO[bytes] + type. Required. + :type enable_request: ~azure.mgmt.monitor.v2021_09_01.models.EnableRequest or IO[bytes] :return: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 304: ResourceNotModifiedError, - 409: lambda response: ResourceExistsError(response=response, error_format=ARMErrorFormat), + 409: cast( + Type[HttpResponseError], + lambda response: ResourceExistsError(response=response, error_format=ARMErrorFormat), + ), } 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: str = kwargs.pop("api_version", _params.pop("api-version", "2021-09-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2021-09-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[None] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(enable_request, (IO, bytes)): + if isinstance(enable_request, (IOBase, bytes)): _content = enable_request else: _json = self._serialize.body(enable_request, "EnableRequest") - request = build_enable_receiver_request( + _request = build_enable_receiver_request( resource_group_name=resource_group_name, action_group_name=action_group_name, subscription_id=self._config.subscription_id, @@ -2031,28 +1870,22 @@ def enable_receiver( # pylint: disable=inconsistent-return-statements content_type=content_type, json=_json, content=_content, - template_url=self.enable_receiver.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _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) + map_error(status_code=response.status_code, response=response, error_map=error_map) # type: ignore 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, {}) - - enable_receiver.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/actionGroups/{actionGroupName}/subscribe" - } + return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/__init__.py index 2c7733bfd566..42cc62301757 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/__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 ._monitor_management_client import MonitorManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._monitor_management_client import MonitorManagementClient # type: ignore from ._version import VERSION __version__ = VERSION try: from ._patch import __all__ as _patch_all - from ._patch import * # 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__ = [ "MonitorManagementClient", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/_configuration.py index 9cefea7b878c..78e6157c3fd1 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/_configuration.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/_configuration.py @@ -8,18 +8,16 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy from ._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MonitorManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class MonitorManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for MonitorManagementClient. Note that all parameters used to create this instance are saved as instance @@ -35,7 +33,6 @@ class MonitorManagementClientConfiguration(Configuration): # pylint: disable=to """ def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: - super(MonitorManagementClientConfiguration, self).__init__(**kwargs) api_version: str = kwargs.pop("api_version", "2021-09-01-preview") if credential is None: @@ -48,6 +45,7 @@ def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-monitor/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -56,9 +54,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.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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/_metadata.json b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/_metadata.json index dd5ef3887f24..fe70acc74bcc 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/_metadata.json +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/_metadata.json @@ -8,10 +8,10 @@ "host_value": "\"https://management.azure.com\"", "parameterized_host_template": null, "azure_arm": true, - "has_lro_operations": false, + "has_public_lro_operations": false, "client_side_validation": false, - "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"sdkcore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMAutoResourceProviderRegistrationPolicy\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}, \"stdlib\": {\"typing_extensions\": [\"Self\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"sdkcore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"AsyncARMAutoResourceProviderRegistrationPolicy\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}, \"stdlib\": {\"typing_extensions\": [\"Self\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "global_parameters": { "sync": { @@ -101,8 +101,8 @@ "credential_scopes": ["https://management.azure.com/.default"], "credential_call_sync": "ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", "credential_call_async": "AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", - "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "sync_imports": "{\"regular\": {\"sdkcore\": {\"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"regular\": {\"sdkcore\": {\"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "operation_groups": { "data_collection_endpoints": "DataCollectionEndpointsOperations", diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/_monitor_management_client.py index 41cd39621823..eb105da04437 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/_monitor_management_client.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/_monitor_management_client.py @@ -8,9 +8,12 @@ from copy import deepcopy from typing import Any, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient +from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy from . import models as _models from .._serialization import Deserializer, Serializer @@ -22,11 +25,10 @@ ) if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MonitorManagementClient: # pylint: disable=client-accepts-api-version-keyword +class MonitorManagementClient: """Monitor Management Client. :ivar data_collection_endpoints: DataCollectionEndpointsOperations operations @@ -59,23 +61,41 @@ def __init__( self._config = MonitorManagementClientConfiguration( credential=credential, subscription_id=subscription_id, **kwargs ) - self._client: ARMPipelineClient = ARMPipelineClient(base_url=base_url, config=self._config, **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), + 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=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.data_collection_endpoints = DataCollectionEndpointsOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2021-09-01-preview" ) self.data_collection_rule_associations = DataCollectionRuleAssociationsOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2021-09-01-preview" ) self.data_collection_rules = DataCollectionRulesOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2021-09-01-preview" ) - 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 @@ -95,12 +115,12 @@ 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) -> None: self._client.close() - def __enter__(self) -> "MonitorManagementClient": + def __enter__(self) -> Self: self._client.__enter__() return self diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/_vendor.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/_vendor.py deleted file mode 100644 index bd0df84f5319..000000000000 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/_vendor.py +++ /dev/null @@ -1,30 +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 typing import List, cast - -from azure.core.pipeline.transport import HttpRequest - - -def _convert_request(request, files=None): - data = request.content if not files else None - request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) - if files: - request.set_formdata_body(files) - return request - - -def _format_url_section(template, **kwargs): - components = template.split("/") - while components: - try: - return template.format(**kwargs) - except KeyError as key: - # Need the cast, as for some reasons "split" is typed as list[str | Any] - formatted_components = cast(List[str], template.split("/")) - components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] - template = "/".join(components) diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/_version.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/_version.py index 394ee7c0c03c..e5754a47ce68 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/_version.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "6.0.2" +VERSION = "1.0.0b1" diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/aio/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/aio/__init__.py index 2c151bb41c19..3df30ff42149 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/aio/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/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 ._monitor_management_client import MonitorManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._monitor_management_client import MonitorManagementClient # type: ignore try: from ._patch import __all__ as _patch_all - from ._patch import * # 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__ = [ "MonitorManagementClient", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/aio/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/aio/_configuration.py index 821323054313..dddcc4e8377d 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/aio/_configuration.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/aio/_configuration.py @@ -8,18 +8,16 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy from .._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MonitorManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class MonitorManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for MonitorManagementClient. Note that all parameters used to create this instance are saved as instance @@ -35,7 +33,6 @@ class MonitorManagementClientConfiguration(Configuration): # pylint: disable=to """ def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: - super(MonitorManagementClientConfiguration, self).__init__(**kwargs) api_version: str = kwargs.pop("api_version", "2021-09-01-preview") if credential is None: @@ -48,6 +45,7 @@ def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **k self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-monitor/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -56,9 +54,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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/aio/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/aio/_monitor_management_client.py index 2ff8b450311b..42a1c78bcc85 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/aio/_monitor_management_client.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/aio/_monitor_management_client.py @@ -8,9 +8,12 @@ from copy import deepcopy from typing import Any, Awaitable, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient +from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy from .. import models as _models from ..._serialization import Deserializer, Serializer @@ -22,11 +25,10 @@ ) if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MonitorManagementClient: # pylint: disable=client-accepts-api-version-keyword +class MonitorManagementClient: """Monitor Management Client. :ivar data_collection_endpoints: DataCollectionEndpointsOperations operations @@ -59,23 +61,43 @@ def __init__( self._config = MonitorManagementClientConfiguration( credential=credential, subscription_id=subscription_id, **kwargs ) - self._client: AsyncARMPipelineClient = AsyncARMPipelineClient(base_url=base_url, config=self._config, **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=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.data_collection_endpoints = DataCollectionEndpointsOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2021-09-01-preview" ) self.data_collection_rule_associations = DataCollectionRuleAssociationsOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2021-09-01-preview" ) self.data_collection_rules = DataCollectionRulesOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2021-09-01-preview" ) - 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 @@ -95,12 +117,12 @@ 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) -> "MonitorManagementClient": + async def __aenter__(self) -> Self: await self._client.__aenter__() return self diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/aio/operations/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/aio/operations/__init__.py index 842046dd09e5..fe2d89505e75 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/aio/operations/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/aio/operations/__init__.py @@ -5,13 +5,19 @@ # 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 ._data_collection_endpoints_operations import DataCollectionEndpointsOperations -from ._data_collection_rule_associations_operations import DataCollectionRuleAssociationsOperations -from ._data_collection_rules_operations import DataCollectionRulesOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._data_collection_endpoints_operations import DataCollectionEndpointsOperations # type: ignore +from ._data_collection_rule_associations_operations import DataCollectionRuleAssociationsOperations # type: ignore +from ._data_collection_rules_operations import DataCollectionRulesOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ @@ -19,5 +25,5 @@ "DataCollectionRuleAssociationsOperations", "DataCollectionRulesOperations", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/aio/operations/_data_collection_endpoints_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/aio/operations/_data_collection_endpoints_operations.py index eaae30c3bbd2..cb15183bd101 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/aio/operations/_data_collection_endpoints_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/aio/operations/_data_collection_endpoints_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload import urllib.parse @@ -19,15 +20,13 @@ 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 ...operations._data_collection_endpoints_operations import ( build_create_request, build_delete_request, @@ -37,6 +36,10 @@ build_update_request, ) +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -59,11 +62,13 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list_by_resource_group( self, resource_group_name: str, **kwargs: Any ) -> AsyncIterable["_models.DataCollectionEndpointResource"]: + # pylint: disable=line-too-long """Lists all data collection endpoints in the specified resource group. Lists all data collection endpoints in the specified resource group. @@ -71,7 +76,6 @@ def list_by_resource_group( :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either DataCollectionEndpointResource or the result of cls(response) :rtype: @@ -81,10 +85,12 @@ def list_by_resource_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-09-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-09-01-preview") + ) cls: ClsType[_models.DataCollectionEndpointResourceListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -95,16 +101,14 @@ 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_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -115,14 +119,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("DataCollectionEndpointResourceListResult", pipeline_response) @@ -132,11 +135,11 @@ async def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -149,17 +152,13 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionEndpoints" - } - @distributed_trace def list_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.DataCollectionEndpointResource"]: + # pylint: disable=line-too-long """Lists all data collection endpoints in the specified subscription. Lists all data collection endpoints in the specified subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either DataCollectionEndpointResource or the result of cls(response) :rtype: @@ -169,10 +168,12 @@ def list_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.DataColl _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-09-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-09-01-preview") + ) cls: ClsType[_models.DataCollectionEndpointResourceListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -183,15 +184,13 @@ def list_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.DataColl def prepare_request(next_link=None): if not next_link: - request = build_list_by_subscription_request( + _request = build_list_by_subscription_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_subscription.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -202,14 +201,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("DataCollectionEndpointResourceListResult", pipeline_response) @@ -219,11 +217,11 @@ async def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -236,10 +234,6 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_by_subscription.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/dataCollectionEndpoints" - } - @distributed_trace_async async def get( self, resource_group_name: str, data_collection_endpoint_name: str, **kwargs: Any @@ -254,12 +248,11 @@ async def get( :param data_collection_endpoint_name: The name of the data collection endpoint. The name is case insensitive. Required. :type data_collection_endpoint_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: DataCollectionEndpointResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_02_01_preview.models.DataCollectionEndpointResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -270,24 +263,24 @@ async def get( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-09-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-09-01-preview") + ) cls: ClsType[_models.DataCollectionEndpointResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, data_collection_endpoint_name=data_collection_endpoint_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -297,16 +290,12 @@ async def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponseCommonV2, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("DataCollectionEndpointResource", pipeline_response) + deserialized = self._deserialize("DataCollectionEndpointResource", 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.Insights/dataCollectionEndpoints/{dataCollectionEndpointName}" - } + return deserialized # type: ignore @overload async def create( @@ -333,7 +322,6 @@ async def create( :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: DataCollectionEndpointResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_02_01_preview.models.DataCollectionEndpointResource :raises ~azure.core.exceptions.HttpResponseError: @@ -344,7 +332,7 @@ async def create( self, resource_group_name: str, data_collection_endpoint_name: str, - body: Optional[IO] = None, + body: Optional[IO[bytes]] = None, *, content_type: str = "application/json", **kwargs: Any @@ -360,11 +348,10 @@ async def create( case insensitive. Required. :type data_collection_endpoint_name: str :param body: The payload. Default value is None. - :type body: IO + :type body: 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: DataCollectionEndpointResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_02_01_preview.models.DataCollectionEndpointResource :raises ~azure.core.exceptions.HttpResponseError: @@ -375,7 +362,7 @@ async def create( self, resource_group_name: str, data_collection_endpoint_name: str, - body: Optional[Union[_models.DataCollectionEndpointResource, IO]] = None, + body: Optional[Union[_models.DataCollectionEndpointResource, IO[bytes]]] = None, **kwargs: Any ) -> _models.DataCollectionEndpointResource: """Creates or updates a data collection endpoint. @@ -388,18 +375,15 @@ async def create( :param data_collection_endpoint_name: The name of the data collection endpoint. The name is case insensitive. Required. :type data_collection_endpoint_name: str - :param body: The payload. Is either a DataCollectionEndpointResource type or a IO type. Default - value is None. - :type body: ~azure.mgmt.monitor.v2022_02_01_preview.models.DataCollectionEndpointResource or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + :param body: The payload. Is either a DataCollectionEndpointResource type or a IO[bytes] type. Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response + :type body: ~azure.mgmt.monitor.v2022_02_01_preview.models.DataCollectionEndpointResource or + IO[bytes] :return: DataCollectionEndpointResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_02_01_preview.models.DataCollectionEndpointResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -410,14 +394,16 @@ async def create( _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", "2021-09-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-09-01-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.DataCollectionEndpointResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(body, (IO, bytes)): + if isinstance(body, (IOBase, bytes)): _content = body else: if body is not None: @@ -425,7 +411,7 @@ async def create( else: _json = None - request = build_create_request( + _request = build_create_request( resource_group_name=resource_group_name, data_collection_endpoint_name=data_collection_endpoint_name, subscription_id=self._config.subscription_id, @@ -433,16 +419,14 @@ async def create( content_type=content_type, json=_json, content=_content, - template_url=self.create.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -452,21 +436,13 @@ async def create( error = self._deserialize.failsafe_deserialize(_models.ErrorResponseCommonV2, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if response.status_code == 200: - deserialized = self._deserialize("DataCollectionEndpointResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("DataCollectionEndpointResource", pipeline_response) + deserialized = self._deserialize("DataCollectionEndpointResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionEndpoints/{dataCollectionEndpointName}" - } - @overload async def update( self, @@ -492,7 +468,6 @@ async def update( :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: DataCollectionEndpointResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_02_01_preview.models.DataCollectionEndpointResource :raises ~azure.core.exceptions.HttpResponseError: @@ -503,7 +478,7 @@ async def update( self, resource_group_name: str, data_collection_endpoint_name: str, - body: Optional[IO] = None, + body: Optional[IO[bytes]] = None, *, content_type: str = "application/json", **kwargs: Any @@ -519,11 +494,10 @@ async def update( case insensitive. Required. :type data_collection_endpoint_name: str :param body: The payload. Default value is None. - :type body: IO + :type body: 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: DataCollectionEndpointResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_02_01_preview.models.DataCollectionEndpointResource :raises ~azure.core.exceptions.HttpResponseError: @@ -534,7 +508,7 @@ async def update( self, resource_group_name: str, data_collection_endpoint_name: str, - body: Optional[Union[_models.ResourceForUpdate, IO]] = None, + body: Optional[Union[_models.ResourceForUpdate, IO[bytes]]] = None, **kwargs: Any ) -> _models.DataCollectionEndpointResource: """Updates part of a data collection endpoint. @@ -547,18 +521,14 @@ async def update( :param data_collection_endpoint_name: The name of the data collection endpoint. The name is case insensitive. Required. :type data_collection_endpoint_name: str - :param body: The payload. Is either a ResourceForUpdate type or a IO type. Default value is - None. - :type body: ~azure.mgmt.monitor.v2022_02_01_preview.models.ResourceForUpdate 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 + :param body: The payload. Is either a ResourceForUpdate type or a IO[bytes] type. Default value + is None. + :type body: ~azure.mgmt.monitor.v2022_02_01_preview.models.ResourceForUpdate or IO[bytes] :return: DataCollectionEndpointResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_02_01_preview.models.DataCollectionEndpointResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -569,14 +539,16 @@ async def update( _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", "2021-09-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-09-01-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.DataCollectionEndpointResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(body, (IO, bytes)): + if isinstance(body, (IOBase, bytes)): _content = body else: if body is not None: @@ -584,7 +556,7 @@ async def update( else: _json = None - request = build_update_request( + _request = build_update_request( resource_group_name=resource_group_name, data_collection_endpoint_name=data_collection_endpoint_name, subscription_id=self._config.subscription_id, @@ -592,16 +564,14 @@ async def update( 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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -611,21 +581,15 @@ async def update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponseCommonV2, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("DataCollectionEndpointResource", pipeline_response) + deserialized = self._deserialize("DataCollectionEndpointResource", 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.Insights/dataCollectionEndpoints/{dataCollectionEndpointName}" - } + return deserialized # type: ignore @distributed_trace_async - async def delete( # pylint: disable=inconsistent-return-statements - self, resource_group_name: str, data_collection_endpoint_name: str, **kwargs: Any - ) -> None: + async def delete(self, resource_group_name: str, data_collection_endpoint_name: str, **kwargs: Any) -> None: """Deletes a data collection endpoint. Deletes a data collection endpoint. @@ -636,12 +600,11 @@ async def delete( # pylint: disable=inconsistent-return-statements :param data_collection_endpoint_name: The name of the data collection endpoint. The name is case insensitive. Required. :type data_collection_endpoint_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, @@ -652,24 +615,24 @@ async def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-09-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-09-01-preview") + ) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, data_collection_endpoint_name=data_collection_endpoint_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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -680,8 +643,4 @@ async def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionEndpoints/{dataCollectionEndpointName}" - } + return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/aio/operations/_data_collection_rule_associations_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/aio/operations/_data_collection_rule_associations_operations.py index f6127e5cd6bc..129abaf7c502 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/aio/operations/_data_collection_rule_associations_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/aio/operations/_data_collection_rule_associations_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload import urllib.parse @@ -19,15 +20,13 @@ 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 ...operations._data_collection_rule_associations_operations import ( build_create_request, build_delete_request, @@ -37,6 +36,10 @@ build_list_by_rule_request, ) +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -59,18 +62,19 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list_by_resource( self, resource_uri: str, **kwargs: Any ) -> AsyncIterable["_models.DataCollectionRuleAssociationProxyOnlyResource"]: + # pylint: disable=line-too-long """Lists associations for the specified resource. Lists associations for the specified resource. :param resource_uri: The identifier of the resource. Required. :type resource_uri: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either DataCollectionRuleAssociationProxyOnlyResource or the result of cls(response) :rtype: @@ -80,10 +84,12 @@ def list_by_resource( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-09-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-09-01-preview") + ) cls: ClsType[_models.DataCollectionRuleAssociationProxyOnlyResourceListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -94,15 +100,13 @@ def list_by_resource( def prepare_request(next_link=None): if not next_link: - request = build_list_by_resource_request( + _request = build_list_by_resource_request( resource_uri=resource_uri, api_version=api_version, - template_url=self.list_by_resource.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -113,14 +117,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize( @@ -132,11 +135,11 @@ async def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -149,12 +152,11 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_by_resource.metadata = {"url": "/{resourceUri}/providers/Microsoft.Insights/dataCollectionRuleAssociations"} - @distributed_trace def list_by_rule( self, resource_group_name: str, data_collection_rule_name: str, **kwargs: Any ) -> AsyncIterable["_models.DataCollectionRuleAssociationProxyOnlyResource"]: + # pylint: disable=line-too-long """Lists associations for the specified data collection rule. Lists associations for the specified data collection rule. @@ -165,7 +167,6 @@ def list_by_rule( :param data_collection_rule_name: The name of the data collection rule. The name is case insensitive. Required. :type data_collection_rule_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either DataCollectionRuleAssociationProxyOnlyResource or the result of cls(response) :rtype: @@ -175,10 +176,12 @@ def list_by_rule( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-09-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-09-01-preview") + ) cls: ClsType[_models.DataCollectionRuleAssociationProxyOnlyResourceListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -189,17 +192,15 @@ def list_by_rule( def prepare_request(next_link=None): if not next_link: - request = build_list_by_rule_request( + _request = build_list_by_rule_request( resource_group_name=resource_group_name, data_collection_rule_name=data_collection_rule_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_rule.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -210,14 +211,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize( @@ -229,11 +229,11 @@ async def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -246,14 +246,11 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_by_rule.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionRules/{dataCollectionRuleName}/associations" - } - @distributed_trace def list_by_data_collection_endpoint( self, resource_group_name: str, data_collection_endpoint_name: str, **kwargs: Any ) -> AsyncIterable["_models.DataCollectionRuleAssociationProxyOnlyResource"]: + # pylint: disable=line-too-long """Lists associations for the specified data collection endpoint. Lists associations for the specified data collection endpoint. @@ -264,7 +261,6 @@ def list_by_data_collection_endpoint( :param data_collection_endpoint_name: The name of the data collection endpoint. The name is case insensitive. Required. :type data_collection_endpoint_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either DataCollectionRuleAssociationProxyOnlyResource or the result of cls(response) :rtype: @@ -274,10 +270,12 @@ def list_by_data_collection_endpoint( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-09-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-09-01-preview") + ) cls: ClsType[_models.DataCollectionRuleAssociationProxyOnlyResourceListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -288,17 +286,15 @@ def list_by_data_collection_endpoint( def prepare_request(next_link=None): if not next_link: - request = build_list_by_data_collection_endpoint_request( + _request = build_list_by_data_collection_endpoint_request( resource_group_name=resource_group_name, data_collection_endpoint_name=data_collection_endpoint_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_data_collection_endpoint.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -309,14 +305,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize( @@ -328,11 +323,11 @@ async def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -345,10 +340,6 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_by_data_collection_endpoint.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionEndpoints/{dataCollectionEndpointName}/associations" - } - @distributed_trace_async async def get( self, resource_uri: str, association_name: str, **kwargs: Any @@ -361,13 +352,12 @@ async def get( :type resource_uri: str :param association_name: The name of the association. The name is case insensitive. Required. :type association_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: DataCollectionRuleAssociationProxyOnlyResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_02_01_preview.models.DataCollectionRuleAssociationProxyOnlyResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -378,23 +368,23 @@ async def get( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-09-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-09-01-preview") + ) cls: ClsType[_models.DataCollectionRuleAssociationProxyOnlyResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_uri=resource_uri, association_name=association_name, api_version=api_version, - template_url=self.get.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -404,16 +394,14 @@ async def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponseCommonV2, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("DataCollectionRuleAssociationProxyOnlyResource", pipeline_response) + deserialized = self._deserialize( + "DataCollectionRuleAssociationProxyOnlyResource", pipeline_response.http_response + ) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get.metadata = { - "url": "/{resourceUri}/providers/Microsoft.Insights/dataCollectionRuleAssociations/{associationName}" - } + return deserialized # type: ignore @overload async def create( @@ -439,7 +427,6 @@ async def create( :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: DataCollectionRuleAssociationProxyOnlyResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_02_01_preview.models.DataCollectionRuleAssociationProxyOnlyResource @@ -451,7 +438,7 @@ async def create( self, resource_uri: str, association_name: str, - body: Optional[IO] = None, + body: Optional[IO[bytes]] = None, *, content_type: str = "application/json", **kwargs: Any @@ -465,11 +452,10 @@ async def create( :param association_name: The name of the association. The name is case insensitive. Required. :type association_name: str :param body: The payload. Default value is None. - :type body: IO + :type body: 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: DataCollectionRuleAssociationProxyOnlyResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_02_01_preview.models.DataCollectionRuleAssociationProxyOnlyResource @@ -481,7 +467,7 @@ async def create( self, resource_uri: str, association_name: str, - body: Optional[Union[_models.DataCollectionRuleAssociationProxyOnlyResource, IO]] = None, + body: Optional[Union[_models.DataCollectionRuleAssociationProxyOnlyResource, IO[bytes]]] = None, **kwargs: Any ) -> _models.DataCollectionRuleAssociationProxyOnlyResource: """Creates or updates an association. @@ -493,20 +479,16 @@ async def create( :param association_name: The name of the association. The name is case insensitive. Required. :type association_name: str :param body: The payload. Is either a DataCollectionRuleAssociationProxyOnlyResource type or a - IO type. Default value is None. + IO[bytes] type. Default value is None. :type body: ~azure.mgmt.monitor.v2022_02_01_preview.models.DataCollectionRuleAssociationProxyOnlyResource - 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 + or IO[bytes] :return: DataCollectionRuleAssociationProxyOnlyResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_02_01_preview.models.DataCollectionRuleAssociationProxyOnlyResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -517,14 +499,16 @@ async def create( _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", "2021-09-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-09-01-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.DataCollectionRuleAssociationProxyOnlyResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(body, (IO, bytes)): + if isinstance(body, (IOBase, bytes)): _content = body else: if body is not None: @@ -532,23 +516,21 @@ async def create( else: _json = None - request = build_create_request( + _request = build_create_request( resource_uri=resource_uri, association_name=association_name, api_version=api_version, content_type=content_type, json=_json, content=_content, - template_url=self.create.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -558,25 +540,17 @@ async def create( error = self._deserialize.failsafe_deserialize(_models.ErrorResponseCommonV2, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if response.status_code == 200: - deserialized = self._deserialize("DataCollectionRuleAssociationProxyOnlyResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("DataCollectionRuleAssociationProxyOnlyResource", pipeline_response) + deserialized = self._deserialize( + "DataCollectionRuleAssociationProxyOnlyResource", pipeline_response.http_response + ) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create.metadata = { - "url": "/{resourceUri}/providers/Microsoft.Insights/dataCollectionRuleAssociations/{associationName}" - } - @distributed_trace_async - async def delete( # pylint: disable=inconsistent-return-statements - self, resource_uri: str, association_name: str, **kwargs: Any - ) -> None: + async def delete(self, resource_uri: str, association_name: str, **kwargs: Any) -> None: """Deletes an association. Deletes an association. @@ -585,12 +559,11 @@ async def delete( # pylint: disable=inconsistent-return-statements :type resource_uri: str :param association_name: The name of the association. The name is case insensitive. Required. :type association_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, @@ -601,23 +574,23 @@ async def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-09-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-09-01-preview") + ) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_uri=resource_uri, association_name=association_name, api_version=api_version, - template_url=self.delete.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -628,8 +601,4 @@ async def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/{resourceUri}/providers/Microsoft.Insights/dataCollectionRuleAssociations/{associationName}" - } + return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/aio/operations/_data_collection_rules_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/aio/operations/_data_collection_rules_operations.py index 59b8c8bc1018..c124f567485f 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/aio/operations/_data_collection_rules_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/aio/operations/_data_collection_rules_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload import urllib.parse @@ -19,15 +20,13 @@ 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 ...operations._data_collection_rules_operations import ( build_create_request, build_delete_request, @@ -37,6 +36,10 @@ build_update_request, ) +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -59,11 +62,13 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list_by_resource_group( self, resource_group_name: str, **kwargs: Any ) -> AsyncIterable["_models.DataCollectionRuleResource"]: + # pylint: disable=line-too-long """Lists all data collection rules in the specified resource group. Lists all data collection rules in the specified resource group. @@ -71,7 +76,6 @@ def list_by_resource_group( :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either DataCollectionRuleResource or the result of cls(response) :rtype: @@ -81,10 +85,12 @@ def list_by_resource_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-09-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-09-01-preview") + ) cls: ClsType[_models.DataCollectionRuleResourceListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -95,16 +101,14 @@ 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_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -115,14 +119,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("DataCollectionRuleResourceListResult", pipeline_response) @@ -132,11 +135,11 @@ async def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -149,17 +152,13 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionRules" - } - @distributed_trace def list_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.DataCollectionRuleResource"]: + # pylint: disable=line-too-long """Lists all data collection rules in the specified subscription. Lists all data collection rules in the specified subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either DataCollectionRuleResource or the result of cls(response) :rtype: @@ -169,10 +168,12 @@ def list_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.DataColl _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-09-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-09-01-preview") + ) cls: ClsType[_models.DataCollectionRuleResourceListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -183,15 +184,13 @@ def list_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.DataColl def prepare_request(next_link=None): if not next_link: - request = build_list_by_subscription_request( + _request = build_list_by_subscription_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_subscription.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -202,14 +201,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("DataCollectionRuleResourceListResult", pipeline_response) @@ -219,11 +217,11 @@ async def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -236,10 +234,6 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_by_subscription.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/dataCollectionRules" - } - @distributed_trace_async async def get( self, resource_group_name: str, data_collection_rule_name: str, **kwargs: Any @@ -254,12 +248,11 @@ async def get( :param data_collection_rule_name: The name of the data collection rule. The name is case insensitive. Required. :type data_collection_rule_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: DataCollectionRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_02_01_preview.models.DataCollectionRuleResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -270,24 +263,24 @@ async def get( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-09-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-09-01-preview") + ) cls: ClsType[_models.DataCollectionRuleResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, data_collection_rule_name=data_collection_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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -297,16 +290,12 @@ async def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponseCommonV2, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("DataCollectionRuleResource", pipeline_response) + deserialized = self._deserialize("DataCollectionRuleResource", 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.Insights/dataCollectionRules/{dataCollectionRuleName}" - } + return deserialized # type: ignore @overload async def create( @@ -333,7 +322,6 @@ async def create( :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: DataCollectionRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_02_01_preview.models.DataCollectionRuleResource :raises ~azure.core.exceptions.HttpResponseError: @@ -344,7 +332,7 @@ async def create( self, resource_group_name: str, data_collection_rule_name: str, - body: Optional[IO] = None, + body: Optional[IO[bytes]] = None, *, content_type: str = "application/json", **kwargs: Any @@ -360,11 +348,10 @@ async def create( insensitive. Required. :type data_collection_rule_name: str :param body: The payload. Default value is None. - :type body: IO + :type body: 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: DataCollectionRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_02_01_preview.models.DataCollectionRuleResource :raises ~azure.core.exceptions.HttpResponseError: @@ -375,7 +362,7 @@ async def create( self, resource_group_name: str, data_collection_rule_name: str, - body: Optional[Union[_models.DataCollectionRuleResource, IO]] = None, + body: Optional[Union[_models.DataCollectionRuleResource, IO[bytes]]] = None, **kwargs: Any ) -> _models.DataCollectionRuleResource: """Creates or updates a data collection rule. @@ -388,18 +375,15 @@ async def create( :param data_collection_rule_name: The name of the data collection rule. The name is case insensitive. Required. :type data_collection_rule_name: str - :param body: The payload. Is either a DataCollectionRuleResource type or a IO type. Default - value is None. - :type body: ~azure.mgmt.monitor.v2022_02_01_preview.models.DataCollectionRuleResource or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + :param body: The payload. Is either a DataCollectionRuleResource type or a IO[bytes] type. Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response + :type body: ~azure.mgmt.monitor.v2022_02_01_preview.models.DataCollectionRuleResource or + IO[bytes] :return: DataCollectionRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_02_01_preview.models.DataCollectionRuleResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -410,14 +394,16 @@ async def create( _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", "2021-09-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-09-01-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.DataCollectionRuleResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(body, (IO, bytes)): + if isinstance(body, (IOBase, bytes)): _content = body else: if body is not None: @@ -425,7 +411,7 @@ async def create( else: _json = None - request = build_create_request( + _request = build_create_request( resource_group_name=resource_group_name, data_collection_rule_name=data_collection_rule_name, subscription_id=self._config.subscription_id, @@ -433,16 +419,14 @@ async def create( content_type=content_type, json=_json, content=_content, - template_url=self.create.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -452,21 +436,13 @@ async def create( error = self._deserialize.failsafe_deserialize(_models.ErrorResponseCommonV2, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if response.status_code == 200: - deserialized = self._deserialize("DataCollectionRuleResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("DataCollectionRuleResource", pipeline_response) + deserialized = self._deserialize("DataCollectionRuleResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionRules/{dataCollectionRuleName}" - } - @overload async def update( self, @@ -492,7 +468,6 @@ async def update( :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: DataCollectionRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_02_01_preview.models.DataCollectionRuleResource :raises ~azure.core.exceptions.HttpResponseError: @@ -503,7 +478,7 @@ async def update( self, resource_group_name: str, data_collection_rule_name: str, - body: Optional[IO] = None, + body: Optional[IO[bytes]] = None, *, content_type: str = "application/json", **kwargs: Any @@ -519,11 +494,10 @@ async def update( insensitive. Required. :type data_collection_rule_name: str :param body: The payload. Default value is None. - :type body: IO + :type body: 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: DataCollectionRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_02_01_preview.models.DataCollectionRuleResource :raises ~azure.core.exceptions.HttpResponseError: @@ -534,7 +508,7 @@ async def update( self, resource_group_name: str, data_collection_rule_name: str, - body: Optional[Union[_models.ResourceForUpdate, IO]] = None, + body: Optional[Union[_models.ResourceForUpdate, IO[bytes]]] = None, **kwargs: Any ) -> _models.DataCollectionRuleResource: """Updates part of a data collection rule. @@ -547,18 +521,14 @@ async def update( :param data_collection_rule_name: The name of the data collection rule. The name is case insensitive. Required. :type data_collection_rule_name: str - :param body: The payload. Is either a ResourceForUpdate type or a IO type. Default value is - None. - :type body: ~azure.mgmt.monitor.v2022_02_01_preview.models.ResourceForUpdate 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 + :param body: The payload. Is either a ResourceForUpdate type or a IO[bytes] type. Default value + is None. + :type body: ~azure.mgmt.monitor.v2022_02_01_preview.models.ResourceForUpdate or IO[bytes] :return: DataCollectionRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_02_01_preview.models.DataCollectionRuleResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -569,14 +539,16 @@ async def update( _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", "2021-09-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-09-01-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.DataCollectionRuleResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(body, (IO, bytes)): + if isinstance(body, (IOBase, bytes)): _content = body else: if body is not None: @@ -584,7 +556,7 @@ async def update( else: _json = None - request = build_update_request( + _request = build_update_request( resource_group_name=resource_group_name, data_collection_rule_name=data_collection_rule_name, subscription_id=self._config.subscription_id, @@ -592,16 +564,14 @@ async def update( 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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -611,21 +581,15 @@ async def update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponseCommonV2, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("DataCollectionRuleResource", pipeline_response) + deserialized = self._deserialize("DataCollectionRuleResource", 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.Insights/dataCollectionRules/{dataCollectionRuleName}" - } + return deserialized # type: ignore @distributed_trace_async - async def delete( # pylint: disable=inconsistent-return-statements - self, resource_group_name: str, data_collection_rule_name: str, **kwargs: Any - ) -> None: + async def delete(self, resource_group_name: str, data_collection_rule_name: str, **kwargs: Any) -> None: """Deletes a data collection rule. Deletes a data collection rule. @@ -636,12 +600,11 @@ async def delete( # pylint: disable=inconsistent-return-statements :param data_collection_rule_name: The name of the data collection rule. The name is case insensitive. Required. :type data_collection_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, @@ -652,24 +615,24 @@ async def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-09-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-09-01-preview") + ) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, data_collection_rule_name=data_collection_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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -680,8 +643,4 @@ async def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionRules/{dataCollectionRuleName}" - } + return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/models/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/models/__init__.py index f75486391895..6932633b33bc 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/models/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/models/__init__.py @@ -5,76 +5,87 @@ # 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 AzureMonitorMetricsDestination -from ._models_py3 import ColumnDefinition -from ._models_py3 import ConfigurationAccessEndpointSpec -from ._models_py3 import DataCollectionEndpoint -from ._models_py3 import DataCollectionEndpointConfigurationAccess -from ._models_py3 import DataCollectionEndpointLogsIngestion -from ._models_py3 import DataCollectionEndpointNetworkAcls -from ._models_py3 import DataCollectionEndpointResource -from ._models_py3 import DataCollectionEndpointResourceListResult -from ._models_py3 import DataCollectionEndpointResourceProperties -from ._models_py3 import DataCollectionEndpointResourceSystemData -from ._models_py3 import DataCollectionRule -from ._models_py3 import DataCollectionRuleAssociation -from ._models_py3 import DataCollectionRuleAssociationMetadata -from ._models_py3 import DataCollectionRuleAssociationProxyOnlyResource -from ._models_py3 import DataCollectionRuleAssociationProxyOnlyResourceListResult -from ._models_py3 import DataCollectionRuleAssociationProxyOnlyResourceProperties -from ._models_py3 import DataCollectionRuleAssociationProxyOnlyResourceSystemData -from ._models_py3 import DataCollectionRuleDataSources -from ._models_py3 import DataCollectionRuleDestinations -from ._models_py3 import DataCollectionRuleMetadata -from ._models_py3 import DataCollectionRuleResource -from ._models_py3 import DataCollectionRuleResourceListResult -from ._models_py3 import DataCollectionRuleResourceProperties -from ._models_py3 import DataCollectionRuleResourceSystemData -from ._models_py3 import DataFlow -from ._models_py3 import DataSourcesSpec -from ._models_py3 import DestinationsSpec -from ._models_py3 import DestinationsSpecAzureMonitorMetrics -from ._models_py3 import ErrorAdditionalInfo -from ._models_py3 import ErrorDetail -from ._models_py3 import ErrorResponseCommonV2 -from ._models_py3 import ExtensionDataSource -from ._models_py3 import IisLogsDataSource -from ._models_py3 import LogAnalyticsDestination -from ._models_py3 import LogFileSettings -from ._models_py3 import LogFileSettingsText -from ._models_py3 import LogFileTextSettings -from ._models_py3 import LogFilesDataSource -from ._models_py3 import LogFilesDataSourceSettings -from ._models_py3 import LogsIngestionEndpointSpec -from ._models_py3 import Metadata -from ._models_py3 import NetworkRuleSet -from ._models_py3 import PerfCounterDataSource -from ._models_py3 import ResourceForUpdate -from ._models_py3 import StreamDeclaration -from ._models_py3 import SyslogDataSource -from ._models_py3 import SystemData -from ._models_py3 import WindowsEventLogDataSource +from typing import TYPE_CHECKING -from ._monitor_management_client_enums import CreatedByType -from ._monitor_management_client_enums import KnownColumnDefinitionType -from ._monitor_management_client_enums import KnownDataCollectionEndpointProvisioningState -from ._monitor_management_client_enums import KnownDataCollectionEndpointResourceKind -from ._monitor_management_client_enums import KnownDataCollectionRuleAssociationProvisioningState -from ._monitor_management_client_enums import KnownDataCollectionRuleProvisioningState -from ._monitor_management_client_enums import KnownDataCollectionRuleResourceKind -from ._monitor_management_client_enums import KnownDataFlowStreams -from ._monitor_management_client_enums import KnownExtensionDataSourceStreams -from ._monitor_management_client_enums import KnownLogFileTextSettingsRecordStartTimestampFormat -from ._monitor_management_client_enums import KnownLogFilesDataSourceFormat -from ._monitor_management_client_enums import KnownPerfCounterDataSourceStreams -from ._monitor_management_client_enums import KnownPublicNetworkAccessOptions -from ._monitor_management_client_enums import KnownSyslogDataSourceFacilityNames -from ._monitor_management_client_enums import KnownSyslogDataSourceLogLevels -from ._monitor_management_client_enums import KnownSyslogDataSourceStreams -from ._monitor_management_client_enums import KnownWindowsEventLogDataSourceStreams +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models_py3 import ( # type: ignore + AzureMonitorMetricsDestination, + ColumnDefinition, + ConfigurationAccessEndpointSpec, + DataCollectionEndpoint, + DataCollectionEndpointConfigurationAccess, + DataCollectionEndpointLogsIngestion, + DataCollectionEndpointNetworkAcls, + DataCollectionEndpointResource, + DataCollectionEndpointResourceListResult, + DataCollectionEndpointResourceProperties, + DataCollectionEndpointResourceSystemData, + DataCollectionRule, + DataCollectionRuleAssociation, + DataCollectionRuleAssociationMetadata, + DataCollectionRuleAssociationProxyOnlyResource, + DataCollectionRuleAssociationProxyOnlyResourceListResult, + DataCollectionRuleAssociationProxyOnlyResourceProperties, + DataCollectionRuleAssociationProxyOnlyResourceSystemData, + DataCollectionRuleDataSources, + DataCollectionRuleDestinations, + DataCollectionRuleMetadata, + DataCollectionRuleResource, + DataCollectionRuleResourceListResult, + DataCollectionRuleResourceProperties, + DataCollectionRuleResourceSystemData, + DataFlow, + DataSourcesSpec, + DestinationsSpec, + DestinationsSpecAzureMonitorMetrics, + ErrorAdditionalInfo, + ErrorDetail, + ErrorResponseCommonV2, + ExtensionDataSource, + IisLogsDataSource, + LogAnalyticsDestination, + LogFileSettings, + LogFileSettingsText, + LogFileTextSettings, + LogFilesDataSource, + LogFilesDataSourceSettings, + LogsIngestionEndpointSpec, + Metadata, + NetworkRuleSet, + PerfCounterDataSource, + ResourceForUpdate, + StreamDeclaration, + SyslogDataSource, + SystemData, + WindowsEventLogDataSource, +) + +from ._monitor_management_client_enums import ( # type: ignore + CreatedByType, + KnownColumnDefinitionType, + KnownDataCollectionEndpointProvisioningState, + KnownDataCollectionEndpointResourceKind, + KnownDataCollectionRuleAssociationProvisioningState, + KnownDataCollectionRuleProvisioningState, + KnownDataCollectionRuleResourceKind, + KnownDataFlowStreams, + KnownExtensionDataSourceStreams, + KnownLogFileTextSettingsRecordStartTimestampFormat, + KnownLogFilesDataSourceFormat, + KnownPerfCounterDataSourceStreams, + KnownPublicNetworkAccessOptions, + KnownSyslogDataSourceFacilityNames, + KnownSyslogDataSourceLogLevels, + KnownSyslogDataSourceStreams, + KnownWindowsEventLogDataSourceStreams, +) from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ @@ -145,5 +156,5 @@ "KnownSyslogDataSourceStreams", "KnownWindowsEventLogDataSourceStreams", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/models/_models_py3.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/models/_models_py3.py index aa859920ff5d..a6e742e9b47f 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/models/_models_py3.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/models/_models_py3.py @@ -1,5 +1,5 @@ -# coding=utf-8 # 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. @@ -16,10 +16,9 @@ if sys.version_info >= (3, 9): from collections.abc import MutableMapping else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports + from typing import MutableMapping # type: ignore if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from .. import models as _models JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object @@ -54,7 +53,7 @@ class ColumnDefinition(_serialization.Model): :ivar name: The name of the column. :vartype name: str :ivar type: The type of the column data. Known values are: "string", "int", "long", "real", - "boolean", "datetime", and "dynamic". + "boolean", "datetime", "dynamic", and "int". :vartype type: str or ~azure.mgmt.monitor.v2022_02_01_preview.models.KnownColumnDefinitionType """ @@ -74,7 +73,7 @@ def __init__( :keyword name: The name of the column. :paramtype name: str :keyword type: The type of the column data. Known values are: "string", "int", "long", "real", - "boolean", "datetime", and "dynamic". + "boolean", "datetime", "dynamic", and "int". :paramtype type: str or ~azure.mgmt.monitor.v2022_02_01_preview.models.KnownColumnDefinitionType """ @@ -179,7 +178,7 @@ def __init__( self.provisioning_state = None -class DataCollectionEndpointConfigurationAccess(ConfigurationAccessEndpointSpec): +class DataCollectionEndpointConfigurationAccess(ConfigurationAccessEndpointSpec): # pylint: disable=name-too-long """The endpoint used by clients to access their configuration. Variables are only populated by the server, and will be ignored when sending a request. @@ -188,18 +187,6 @@ class DataCollectionEndpointConfigurationAccess(ConfigurationAccessEndpointSpec) :vartype endpoint: str """ - _validation = { - "endpoint": {"readonly": True}, - } - - _attribute_map = { - "endpoint": {"key": "endpoint", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - class LogsIngestionEndpointSpec(_serialization.Model): """Definition of the endpoint used for ingesting logs. @@ -233,18 +220,6 @@ class DataCollectionEndpointLogsIngestion(LogsIngestionEndpointSpec): :vartype endpoint: str """ - _validation = { - "endpoint": {"readonly": True}, - } - - _attribute_map = { - "endpoint": {"key": "endpoint", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - class NetworkRuleSet(_serialization.Model): """Definition of the network rules. @@ -284,31 +259,13 @@ class DataCollectionEndpointNetworkAcls(NetworkRuleSet): ~azure.mgmt.monitor.v2022_02_01_preview.models.KnownPublicNetworkAccessOptions """ - _attribute_map = { - "public_network_access": {"key": "publicNetworkAccess", "type": "str"}, - } - def __init__( - self, - *, - public_network_access: Optional[Union[str, "_models.KnownPublicNetworkAccessOptions"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword public_network_access: The configuration to set whether network access from public - internet to the endpoints are allowed. Known values are: "Enabled" and "Disabled". - :paramtype public_network_access: str or - ~azure.mgmt.monitor.v2022_02_01_preview.models.KnownPublicNetworkAccessOptions - """ - super().__init__(public_network_access=public_network_access, **kwargs) - - -class DataCollectionEndpointResource(_serialization.Model): # pylint: disable=too-many-instance-attributes +class DataCollectionEndpointResource(_serialization.Model): """Definition of ARM tracked top level 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 location: The geo-location where the resource lives. Required. :vartype location: str @@ -434,7 +391,7 @@ def __init__( class DataCollectionEndpointResourceListResult(_serialization.Model): """A pageable list of resources. - 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 value: A list of resources. Required. :vartype value: @@ -492,54 +449,6 @@ class DataCollectionEndpointResourceProperties(DataCollectionEndpoint): ~azure.mgmt.monitor.v2022_02_01_preview.models.KnownDataCollectionEndpointProvisioningState """ - _validation = { - "provisioning_state": {"readonly": True}, - } - - _attribute_map = { - "description": {"key": "description", "type": "str"}, - "immutable_id": {"key": "immutableId", "type": "str"}, - "configuration_access": {"key": "configurationAccess", "type": "DataCollectionEndpointConfigurationAccess"}, - "logs_ingestion": {"key": "logsIngestion", "type": "DataCollectionEndpointLogsIngestion"}, - "network_acls": {"key": "networkAcls", "type": "DataCollectionEndpointNetworkAcls"}, - "provisioning_state": {"key": "provisioningState", "type": "str"}, - } - - def __init__( - self, - *, - description: Optional[str] = None, - immutable_id: Optional[str] = None, - configuration_access: Optional["_models.DataCollectionEndpointConfigurationAccess"] = None, - logs_ingestion: Optional["_models.DataCollectionEndpointLogsIngestion"] = None, - network_acls: Optional["_models.DataCollectionEndpointNetworkAcls"] = None, - **kwargs: Any - ) -> None: - """ - :keyword description: Description of the data collection endpoint. - :paramtype description: str - :keyword immutable_id: The immutable ID of this data collection endpoint resource. This - property is READ-ONLY. - :paramtype immutable_id: str - :keyword configuration_access: The endpoint used by clients to access their configuration. - :paramtype configuration_access: - ~azure.mgmt.monitor.v2022_02_01_preview.models.DataCollectionEndpointConfigurationAccess - :keyword logs_ingestion: The endpoint used by clients to ingest logs. - :paramtype logs_ingestion: - ~azure.mgmt.monitor.v2022_02_01_preview.models.DataCollectionEndpointLogsIngestion - :keyword network_acls: Network access control rules for the endpoints. - :paramtype network_acls: - ~azure.mgmt.monitor.v2022_02_01_preview.models.DataCollectionEndpointNetworkAcls - """ - super().__init__( - description=description, - immutable_id=immutable_id, - configuration_access=configuration_access, - logs_ingestion=logs_ingestion, - network_acls=network_acls, - **kwargs - ) - class SystemData(_serialization.Model): """Metadata pertaining to creation and last modification of the resource. @@ -627,53 +536,6 @@ class DataCollectionEndpointResourceSystemData(SystemData): :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: 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.monitor.v2022_02_01_preview.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.monitor.v2022_02_01_preview.models.CreatedByType - :keyword last_modified_at: The timestamp of resource last modification (UTC). - :paramtype last_modified_at: ~datetime.datetime - """ - super().__init__( - created_by=created_by, - created_by_type=created_by_type, - created_at=created_at, - last_modified_by=last_modified_by, - last_modified_by_type=last_modified_by_type, - last_modified_at=last_modified_at, - **kwargs - ) - class DataCollectionRule(_serialization.Model): """Definition of what monitoring data to collect and where that data should be sent. @@ -862,20 +724,8 @@ class DataCollectionRuleAssociationMetadata(Metadata): :vartype provisioned_by: str """ - _validation = { - "provisioned_by": {"readonly": True}, - } - - _attribute_map = { - "provisioned_by": {"key": "provisionedBy", "type": "str"}, - } - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - - -class DataCollectionRuleAssociationProxyOnlyResource(_serialization.Model): +class DataCollectionRuleAssociationProxyOnlyResource(_serialization.Model): # pylint: disable=name-too-long """Definition of generic ARM proxy resource. Variables are only populated by the server, and will be ignored when sending a request. @@ -962,10 +812,10 @@ def __init__( self.metadata = None -class DataCollectionRuleAssociationProxyOnlyResourceListResult(_serialization.Model): +class DataCollectionRuleAssociationProxyOnlyResourceListResult(_serialization.Model): # pylint: disable=name-too-long """A pageable list of resources. - 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 value: A list of resources. Required. :vartype value: @@ -1002,7 +852,9 @@ def __init__( self.next_link = next_link -class DataCollectionRuleAssociationProxyOnlyResourceProperties(DataCollectionRuleAssociation): +class DataCollectionRuleAssociationProxyOnlyResourceProperties( + DataCollectionRuleAssociation +): # pylint: disable=name-too-long """Resource properties. Variables are only populated by the server, and will be ignored when sending a request. @@ -1024,46 +876,8 @@ class DataCollectionRuleAssociationProxyOnlyResourceProperties(DataCollectionRul ~azure.mgmt.monitor.v2022_02_01_preview.models.DataCollectionRuleAssociationMetadata """ - _validation = { - "provisioning_state": {"readonly": True}, - "metadata": {"readonly": True}, - } - _attribute_map = { - "description": {"key": "description", "type": "str"}, - "data_collection_rule_id": {"key": "dataCollectionRuleId", "type": "str"}, - "data_collection_endpoint_id": {"key": "dataCollectionEndpointId", "type": "str"}, - "provisioning_state": {"key": "provisioningState", "type": "str"}, - "metadata": {"key": "metadata", "type": "DataCollectionRuleAssociationMetadata"}, - } - - def __init__( - self, - *, - description: Optional[str] = None, - data_collection_rule_id: Optional[str] = None, - data_collection_endpoint_id: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword description: Description of the association. - :paramtype description: str - :keyword data_collection_rule_id: The resource ID of the data collection rule that is to be - associated. - :paramtype data_collection_rule_id: str - :keyword data_collection_endpoint_id: The resource ID of the data collection endpoint that is - to be associated. - :paramtype data_collection_endpoint_id: str - """ - super().__init__( - description=description, - data_collection_rule_id=data_collection_rule_id, - data_collection_endpoint_id=data_collection_endpoint_id, - **kwargs - ) - - -class DataCollectionRuleAssociationProxyOnlyResourceSystemData(SystemData): +class DataCollectionRuleAssociationProxyOnlyResourceSystemData(SystemData): # pylint: disable=name-too-long """Metadata pertaining to creation and last modification of the resource. :ivar created_by: The identity that created the resource. @@ -1083,53 +897,6 @@ class DataCollectionRuleAssociationProxyOnlyResourceSystemData(SystemData): :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: 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.monitor.v2022_02_01_preview.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.monitor.v2022_02_01_preview.models.CreatedByType - :keyword last_modified_at: The timestamp of resource last modification (UTC). - :paramtype last_modified_at: ~datetime.datetime - """ - super().__init__( - created_by=created_by, - created_by_type=created_by_type, - created_at=created_at, - last_modified_by=last_modified_by, - last_modified_by_type=last_modified_by_type, - last_modified_at=last_modified_at, - **kwargs - ) - class DataSourcesSpec(_serialization.Model): """Specification of data sources that will be collected. @@ -1216,52 +983,6 @@ class DataCollectionRuleDataSources(DataSourcesSpec): :vartype iis_logs: list[~azure.mgmt.monitor.v2022_02_01_preview.models.IisLogsDataSource] """ - _attribute_map = { - "performance_counters": {"key": "performanceCounters", "type": "[PerfCounterDataSource]"}, - "windows_event_logs": {"key": "windowsEventLogs", "type": "[WindowsEventLogDataSource]"}, - "syslog": {"key": "syslog", "type": "[SyslogDataSource]"}, - "extensions": {"key": "extensions", "type": "[ExtensionDataSource]"}, - "log_files": {"key": "logFiles", "type": "[LogFilesDataSource]"}, - "iis_logs": {"key": "iisLogs", "type": "[IisLogsDataSource]"}, - } - - def __init__( - self, - *, - performance_counters: Optional[List["_models.PerfCounterDataSource"]] = None, - windows_event_logs: Optional[List["_models.WindowsEventLogDataSource"]] = None, - syslog: Optional[List["_models.SyslogDataSource"]] = None, - extensions: Optional[List["_models.ExtensionDataSource"]] = None, - log_files: Optional[List["_models.LogFilesDataSource"]] = None, - iis_logs: Optional[List["_models.IisLogsDataSource"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword performance_counters: The list of performance counter data source configurations. - :paramtype performance_counters: - list[~azure.mgmt.monitor.v2022_02_01_preview.models.PerfCounterDataSource] - :keyword windows_event_logs: The list of Windows Event Log data source configurations. - :paramtype windows_event_logs: - list[~azure.mgmt.monitor.v2022_02_01_preview.models.WindowsEventLogDataSource] - :keyword syslog: The list of Syslog data source configurations. - :paramtype syslog: list[~azure.mgmt.monitor.v2022_02_01_preview.models.SyslogDataSource] - :keyword extensions: The list of Azure VM extension data source configurations. - :paramtype extensions: list[~azure.mgmt.monitor.v2022_02_01_preview.models.ExtensionDataSource] - :keyword log_files: The list of Log files source configurations. - :paramtype log_files: list[~azure.mgmt.monitor.v2022_02_01_preview.models.LogFilesDataSource] - :keyword iis_logs: The list of IIS logs source configurations. - :paramtype iis_logs: list[~azure.mgmt.monitor.v2022_02_01_preview.models.IisLogsDataSource] - """ - super().__init__( - performance_counters=performance_counters, - windows_event_logs=windows_event_logs, - syslog=syslog, - extensions=extensions, - log_files=log_files, - iis_logs=iis_logs, - **kwargs - ) - class DestinationsSpec(_serialization.Model): """Specification of destinations that can be used in data flows. @@ -1310,28 +1031,6 @@ class DataCollectionRuleDestinations(DestinationsSpec): ~azure.mgmt.monitor.v2022_02_01_preview.models.DestinationsSpecAzureMonitorMetrics """ - _attribute_map = { - "log_analytics": {"key": "logAnalytics", "type": "[LogAnalyticsDestination]"}, - "azure_monitor_metrics": {"key": "azureMonitorMetrics", "type": "DestinationsSpecAzureMonitorMetrics"}, - } - - def __init__( - self, - *, - log_analytics: Optional[List["_models.LogAnalyticsDestination"]] = None, - azure_monitor_metrics: Optional["_models.DestinationsSpecAzureMonitorMetrics"] = None, - **kwargs: Any - ) -> None: - """ - :keyword log_analytics: List of Log Analytics destinations. - :paramtype log_analytics: - list[~azure.mgmt.monitor.v2022_02_01_preview.models.LogAnalyticsDestination] - :keyword azure_monitor_metrics: Azure Monitor Metrics destination. - :paramtype azure_monitor_metrics: - ~azure.mgmt.monitor.v2022_02_01_preview.models.DestinationsSpecAzureMonitorMetrics - """ - super().__init__(log_analytics=log_analytics, azure_monitor_metrics=azure_monitor_metrics, **kwargs) - class DataCollectionRuleMetadata(Metadata): """Metadata about the resource. @@ -1342,25 +1041,13 @@ class DataCollectionRuleMetadata(Metadata): :vartype provisioned_by: str """ - _validation = { - "provisioned_by": {"readonly": True}, - } - - _attribute_map = { - "provisioned_by": {"key": "provisionedBy", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - -class DataCollectionRuleResource(_serialization.Model): # pylint: disable=too-many-instance-attributes +class DataCollectionRuleResource(_serialization.Model): """Definition of ARM tracked top level 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 location: The geo-location where the resource lives. Required. :vartype location: str @@ -1504,7 +1191,7 @@ def __init__( class DataCollectionRuleResourceListResult(_serialization.Model): """A pageable list of resources. - 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 value: A list of resources. Required. :vartype value: list[~azure.mgmt.monitor.v2022_02_01_preview.models.DataCollectionRuleResource] @@ -1569,65 +1256,6 @@ class DataCollectionRuleResourceProperties(DataCollectionRule): ~azure.mgmt.monitor.v2022_02_01_preview.models.KnownDataCollectionRuleProvisioningState """ - _validation = { - "immutable_id": {"readonly": True}, - "metadata": {"readonly": True}, - "provisioning_state": {"readonly": True}, - } - - _attribute_map = { - "description": {"key": "description", "type": "str"}, - "immutable_id": {"key": "immutableId", "type": "str"}, - "data_collection_endpoint_id": {"key": "dataCollectionEndpointId", "type": "str"}, - "metadata": {"key": "metadata", "type": "DataCollectionRuleMetadata"}, - "stream_declarations": {"key": "streamDeclarations", "type": "{StreamDeclaration}"}, - "data_sources": {"key": "dataSources", "type": "DataCollectionRuleDataSources"}, - "destinations": {"key": "destinations", "type": "DataCollectionRuleDestinations"}, - "data_flows": {"key": "dataFlows", "type": "[DataFlow]"}, - "provisioning_state": {"key": "provisioningState", "type": "str"}, - } - - def __init__( - self, - *, - description: Optional[str] = None, - data_collection_endpoint_id: Optional[str] = None, - stream_declarations: Optional[Dict[str, "_models.StreamDeclaration"]] = None, - data_sources: Optional["_models.DataCollectionRuleDataSources"] = None, - destinations: Optional["_models.DataCollectionRuleDestinations"] = None, - data_flows: Optional[List["_models.DataFlow"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword description: Description of the data collection rule. - :paramtype description: str - :keyword data_collection_endpoint_id: The resource ID of the data collection endpoint that this - rule can be used with. - :paramtype data_collection_endpoint_id: str - :keyword stream_declarations: Declaration of custom streams used in this rule. - :paramtype stream_declarations: dict[str, - ~azure.mgmt.monitor.v2022_02_01_preview.models.StreamDeclaration] - :keyword data_sources: The specification of data sources. - This property is optional and can be omitted if the rule is meant to be used via direct calls - to the provisioned endpoint. - :paramtype data_sources: - ~azure.mgmt.monitor.v2022_02_01_preview.models.DataCollectionRuleDataSources - :keyword destinations: The specification of destinations. - :paramtype destinations: - ~azure.mgmt.monitor.v2022_02_01_preview.models.DataCollectionRuleDestinations - :keyword data_flows: The specification of data flows. - :paramtype data_flows: list[~azure.mgmt.monitor.v2022_02_01_preview.models.DataFlow] - """ - super().__init__( - description=description, - data_collection_endpoint_id=data_collection_endpoint_id, - stream_declarations=stream_declarations, - data_sources=data_sources, - destinations=destinations, - data_flows=data_flows, - **kwargs - ) - class DataCollectionRuleResourceSystemData(SystemData): """Metadata pertaining to creation and last modification of the resource. @@ -1649,53 +1277,6 @@ class DataCollectionRuleResourceSystemData(SystemData): :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: 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.monitor.v2022_02_01_preview.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.monitor.v2022_02_01_preview.models.CreatedByType - :keyword last_modified_at: The timestamp of resource last modification (UTC). - :paramtype last_modified_at: ~datetime.datetime - """ - super().__init__( - created_by=created_by, - created_by_type=created_by_type, - created_at=created_at, - last_modified_by=last_modified_by, - last_modified_by_type=last_modified_by_type, - last_modified_at=last_modified_at, - **kwargs - ) - class DataFlow(_serialization.Model): """Definition of which streams are sent to which destinations. @@ -1756,19 +1337,6 @@ class DestinationsSpecAzureMonitorMetrics(AzureMonitorMetricsDestination): :vartype name: str """ - _attribute_map = { - "name": {"key": "name", "type": "str"}, - } - - def __init__(self, *, name: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword name: A friendly name for the destination. - This name should be unique across all destinations (regardless of type) within the data - collection rule. - :paramtype name: str - """ - super().__init__(name=name, **kwargs) - class ErrorAdditionalInfo(_serialization.Model): """The resource management error additional info. @@ -1868,7 +1436,7 @@ class ExtensionDataSource(_serialization.Model): the Azure Monitor Agent. Collected from either Windows and Linux machines, depending on which extension is defined. - 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 streams: List of streams that this data source will be sent to. A stream indicates what schema will be used for this data and usually what table in Log @@ -1939,7 +1507,7 @@ def __init__( class IisLogsDataSource(_serialization.Model): """Enables IIS logs to be collected by this data collection rule. - 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 streams: IIS streams. Required. :vartype streams: list[str] @@ -2030,7 +1598,7 @@ def __init__( class LogFilesDataSource(_serialization.Model): """Definition of which custom log files will be collected by this data collection rule. - 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 streams: List of streams that this data source will be sent to. A stream indicates what schema will be used for this data source. Required. @@ -2123,22 +1691,11 @@ class LogFilesDataSourceSettings(LogFileSettings): :vartype text: ~azure.mgmt.monitor.v2022_02_01_preview.models.LogFileSettingsText """ - _attribute_map = { - "text": {"key": "text", "type": "LogFileSettingsText"}, - } - - def __init__(self, *, text: Optional["_models.LogFileSettingsText"] = None, **kwargs: Any) -> None: - """ - :keyword text: Text settings. - :paramtype text: ~azure.mgmt.monitor.v2022_02_01_preview.models.LogFileSettingsText - """ - super().__init__(text=text, **kwargs) - class LogFileTextSettings(_serialization.Model): """Settings for text log files. - 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 record_start_timestamp_format: One of the supported timestamp formats. Required. Known values are: "ISO 8601", "YYYY-MM-DD HH:MM:SS", "M/D/YYYY HH:MM:SS AM/PM", "Mon DD, YYYY @@ -2177,7 +1734,7 @@ def __init__( class LogFileSettingsText(LogFileTextSettings): """Text settings. - 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 record_start_timestamp_format: One of the supported timestamp formats. Required. Known values are: "ISO 8601", "YYYY-MM-DD HH:MM:SS", "M/D/YYYY HH:MM:SS AM/PM", "Mon DD, YYYY @@ -2187,30 +1744,6 @@ class LogFileSettingsText(LogFileTextSettings): ~azure.mgmt.monitor.v2022_02_01_preview.models.KnownLogFileTextSettingsRecordStartTimestampFormat """ - _validation = { - "record_start_timestamp_format": {"required": True}, - } - - _attribute_map = { - "record_start_timestamp_format": {"key": "recordStartTimestampFormat", "type": "str"}, - } - - def __init__( - self, - *, - record_start_timestamp_format: Union[str, "_models.KnownLogFileTextSettingsRecordStartTimestampFormat"], - **kwargs: Any - ) -> None: - """ - :keyword record_start_timestamp_format: One of the supported timestamp formats. Required. Known - values are: "ISO 8601", "YYYY-MM-DD HH:MM:SS", "M/D/YYYY HH:MM:SS AM/PM", "Mon DD, YYYY - HH:MM:SS", "yyMMdd HH:mm:ss", "ddMMyy HH:mm:ss", "MMM d hh:mm:ss", "dd/MMM/yyyy:HH:mm:ss zzz", - and "yyyy-MM-ddTHH:mm:ssK". - :paramtype record_start_timestamp_format: str or - ~azure.mgmt.monitor.v2022_02_01_preview.models.KnownLogFileTextSettingsRecordStartTimestampFormat - """ - super().__init__(record_start_timestamp_format=record_start_timestamp_format, **kwargs) - class PerfCounterDataSource(_serialization.Model): """Definition of which performance counters will be collected and how they will be collected by diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/models/_monitor_management_client_enums.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/models/_monitor_management_client_enums.py index 0ae017838570..237002455ad2 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/models/_monitor_management_client_enums.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/models/_monitor_management_client_enums.py @@ -29,6 +29,7 @@ class KnownColumnDefinitionType(str, Enum, metaclass=CaseInsensitiveEnumMeta): BOOLEAN = "boolean" DATETIME = "datetime" DYNAMIC = "dynamic" + INT_ENUM = "int" class KnownDataCollectionEndpointProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/operations/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/operations/__init__.py index 842046dd09e5..fe2d89505e75 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/operations/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/operations/__init__.py @@ -5,13 +5,19 @@ # 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 ._data_collection_endpoints_operations import DataCollectionEndpointsOperations -from ._data_collection_rule_associations_operations import DataCollectionRuleAssociationsOperations -from ._data_collection_rules_operations import DataCollectionRulesOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._data_collection_endpoints_operations import DataCollectionEndpointsOperations # type: ignore +from ._data_collection_rule_associations_operations import DataCollectionRuleAssociationsOperations # type: ignore +from ._data_collection_rules_operations import DataCollectionRulesOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ @@ -19,5 +25,5 @@ "DataCollectionRuleAssociationsOperations", "DataCollectionRulesOperations", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/operations/_data_collection_endpoints_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/operations/_data_collection_endpoints_operations.py index 05f8e5f02243..c4d17be58e59 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/operations/_data_collection_endpoints_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/operations/_data_collection_endpoints_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload import urllib.parse @@ -19,16 +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, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -55,7 +58,7 @@ def build_list_by_resource_group_request(resource_group_name: str, subscription_ ), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -81,7 +84,7 @@ def build_list_by_subscription_request(subscription_id: str, **kwargs: Any) -> H "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -116,7 +119,7 @@ def build_get_request( ), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -152,7 +155,7 @@ def build_create_request( ), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -190,7 +193,7 @@ def build_update_request( ), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -227,7 +230,7 @@ def build_delete_request( ), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -256,6 +259,7 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list_by_resource_group( @@ -268,7 +272,6 @@ def list_by_resource_group( :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either DataCollectionEndpointResource or the result of cls(response) :rtype: @@ -278,10 +281,12 @@ def list_by_resource_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-09-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-09-01-preview") + ) cls: ClsType[_models.DataCollectionEndpointResourceListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -292,16 +297,14 @@ 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_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -312,14 +315,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("DataCollectionEndpointResourceListResult", pipeline_response) @@ -329,11 +331,11 @@ def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -346,17 +348,12 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionEndpoints" - } - @distributed_trace def list_by_subscription(self, **kwargs: Any) -> Iterable["_models.DataCollectionEndpointResource"]: """Lists all data collection endpoints in the specified subscription. Lists all data collection endpoints in the specified subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either DataCollectionEndpointResource or the result of cls(response) :rtype: @@ -366,10 +363,12 @@ def list_by_subscription(self, **kwargs: Any) -> Iterable["_models.DataCollectio _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-09-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-09-01-preview") + ) cls: ClsType[_models.DataCollectionEndpointResourceListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -380,15 +379,13 @@ def list_by_subscription(self, **kwargs: Any) -> Iterable["_models.DataCollectio def prepare_request(next_link=None): if not next_link: - request = build_list_by_subscription_request( + _request = build_list_by_subscription_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_subscription.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -399,14 +396,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("DataCollectionEndpointResourceListResult", pipeline_response) @@ -416,11 +412,11 @@ def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -433,10 +429,6 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_by_subscription.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/dataCollectionEndpoints" - } - @distributed_trace def get( self, resource_group_name: str, data_collection_endpoint_name: str, **kwargs: Any @@ -451,12 +443,11 @@ def get( :param data_collection_endpoint_name: The name of the data collection endpoint. The name is case insensitive. Required. :type data_collection_endpoint_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: DataCollectionEndpointResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_02_01_preview.models.DataCollectionEndpointResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -467,24 +458,24 @@ def get( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-09-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-09-01-preview") + ) cls: ClsType[_models.DataCollectionEndpointResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, data_collection_endpoint_name=data_collection_endpoint_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -494,16 +485,12 @@ def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponseCommonV2, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("DataCollectionEndpointResource", pipeline_response) + deserialized = self._deserialize("DataCollectionEndpointResource", 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.Insights/dataCollectionEndpoints/{dataCollectionEndpointName}" - } + return deserialized # type: ignore @overload def create( @@ -530,7 +517,6 @@ def create( :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: DataCollectionEndpointResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_02_01_preview.models.DataCollectionEndpointResource :raises ~azure.core.exceptions.HttpResponseError: @@ -541,7 +527,7 @@ def create( self, resource_group_name: str, data_collection_endpoint_name: str, - body: Optional[IO] = None, + body: Optional[IO[bytes]] = None, *, content_type: str = "application/json", **kwargs: Any @@ -557,11 +543,10 @@ def create( case insensitive. Required. :type data_collection_endpoint_name: str :param body: The payload. Default value is None. - :type body: IO + :type body: 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: DataCollectionEndpointResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_02_01_preview.models.DataCollectionEndpointResource :raises ~azure.core.exceptions.HttpResponseError: @@ -572,7 +557,7 @@ def create( self, resource_group_name: str, data_collection_endpoint_name: str, - body: Optional[Union[_models.DataCollectionEndpointResource, IO]] = None, + body: Optional[Union[_models.DataCollectionEndpointResource, IO[bytes]]] = None, **kwargs: Any ) -> _models.DataCollectionEndpointResource: """Creates or updates a data collection endpoint. @@ -585,18 +570,15 @@ def create( :param data_collection_endpoint_name: The name of the data collection endpoint. The name is case insensitive. Required. :type data_collection_endpoint_name: str - :param body: The payload. Is either a DataCollectionEndpointResource type or a IO type. Default - value is None. - :type body: ~azure.mgmt.monitor.v2022_02_01_preview.models.DataCollectionEndpointResource or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + :param body: The payload. Is either a DataCollectionEndpointResource type or a IO[bytes] type. Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response + :type body: ~azure.mgmt.monitor.v2022_02_01_preview.models.DataCollectionEndpointResource or + IO[bytes] :return: DataCollectionEndpointResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_02_01_preview.models.DataCollectionEndpointResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -607,14 +589,16 @@ def create( _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", "2021-09-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-09-01-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.DataCollectionEndpointResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(body, (IO, bytes)): + if isinstance(body, (IOBase, bytes)): _content = body else: if body is not None: @@ -622,7 +606,7 @@ def create( else: _json = None - request = build_create_request( + _request = build_create_request( resource_group_name=resource_group_name, data_collection_endpoint_name=data_collection_endpoint_name, subscription_id=self._config.subscription_id, @@ -630,16 +614,14 @@ def create( content_type=content_type, json=_json, content=_content, - template_url=self.create.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -649,21 +631,13 @@ def create( error = self._deserialize.failsafe_deserialize(_models.ErrorResponseCommonV2, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if response.status_code == 200: - deserialized = self._deserialize("DataCollectionEndpointResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("DataCollectionEndpointResource", pipeline_response) + deserialized = self._deserialize("DataCollectionEndpointResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionEndpoints/{dataCollectionEndpointName}" - } - @overload def update( self, @@ -689,7 +663,6 @@ def update( :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: DataCollectionEndpointResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_02_01_preview.models.DataCollectionEndpointResource :raises ~azure.core.exceptions.HttpResponseError: @@ -700,7 +673,7 @@ def update( self, resource_group_name: str, data_collection_endpoint_name: str, - body: Optional[IO] = None, + body: Optional[IO[bytes]] = None, *, content_type: str = "application/json", **kwargs: Any @@ -716,11 +689,10 @@ def update( case insensitive. Required. :type data_collection_endpoint_name: str :param body: The payload. Default value is None. - :type body: IO + :type body: 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: DataCollectionEndpointResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_02_01_preview.models.DataCollectionEndpointResource :raises ~azure.core.exceptions.HttpResponseError: @@ -731,7 +703,7 @@ def update( self, resource_group_name: str, data_collection_endpoint_name: str, - body: Optional[Union[_models.ResourceForUpdate, IO]] = None, + body: Optional[Union[_models.ResourceForUpdate, IO[bytes]]] = None, **kwargs: Any ) -> _models.DataCollectionEndpointResource: """Updates part of a data collection endpoint. @@ -744,18 +716,14 @@ def update( :param data_collection_endpoint_name: The name of the data collection endpoint. The name is case insensitive. Required. :type data_collection_endpoint_name: str - :param body: The payload. Is either a ResourceForUpdate type or a IO type. Default value is - None. - :type body: ~azure.mgmt.monitor.v2022_02_01_preview.models.ResourceForUpdate 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 + :param body: The payload. Is either a ResourceForUpdate type or a IO[bytes] type. Default value + is None. + :type body: ~azure.mgmt.monitor.v2022_02_01_preview.models.ResourceForUpdate or IO[bytes] :return: DataCollectionEndpointResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_02_01_preview.models.DataCollectionEndpointResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -766,14 +734,16 @@ def update( _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", "2021-09-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-09-01-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.DataCollectionEndpointResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(body, (IO, bytes)): + if isinstance(body, (IOBase, bytes)): _content = body else: if body is not None: @@ -781,7 +751,7 @@ def update( else: _json = None - request = build_update_request( + _request = build_update_request( resource_group_name=resource_group_name, data_collection_endpoint_name=data_collection_endpoint_name, subscription_id=self._config.subscription_id, @@ -789,16 +759,14 @@ def update( 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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -808,16 +776,12 @@ def update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponseCommonV2, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("DataCollectionEndpointResource", pipeline_response) + deserialized = self._deserialize("DataCollectionEndpointResource", 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.Insights/dataCollectionEndpoints/{dataCollectionEndpointName}" - } + return deserialized # type: ignore @distributed_trace def delete( # pylint: disable=inconsistent-return-statements @@ -833,12 +797,11 @@ def delete( # pylint: disable=inconsistent-return-statements :param data_collection_endpoint_name: The name of the data collection endpoint. The name is case insensitive. Required. :type data_collection_endpoint_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, @@ -849,24 +812,24 @@ def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-09-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-09-01-preview") + ) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, data_collection_endpoint_name=data_collection_endpoint_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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -877,8 +840,4 @@ def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionEndpoints/{dataCollectionEndpointName}" - } + return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/operations/_data_collection_rule_associations_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/operations/_data_collection_rule_associations_operations.py index f25e0ce5a1f9..dc9068646257 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/operations/_data_collection_rule_associations_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/operations/_data_collection_rule_associations_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload import urllib.parse @@ -19,16 +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, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -49,7 +52,7 @@ def build_list_by_resource_request(resource_uri: str, **kwargs: Any) -> HttpRequ "resourceUri": _SERIALIZER.url("resource_uri", resource_uri, "str", skip_quote=True, min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -82,7 +85,7 @@ def build_list_by_rule_request( "dataCollectionRuleName": _SERIALIZER.url("data_collection_rule_name", data_collection_rule_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -117,7 +120,7 @@ def build_list_by_data_collection_endpoint_request( # pylint: disable=name-too- ), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -144,7 +147,7 @@ def build_get_request(resource_uri: str, association_name: str, **kwargs: Any) - "associationName": _SERIALIZER.url("association_name", association_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -172,7 +175,7 @@ def build_create_request(resource_uri: str, association_name: str, **kwargs: Any "associationName": _SERIALIZER.url("association_name", association_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -201,7 +204,7 @@ def build_delete_request(resource_uri: str, association_name: str, **kwargs: Any "associationName": _SERIALIZER.url("association_name", association_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -230,18 +233,19 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list_by_resource( self, resource_uri: str, **kwargs: Any ) -> Iterable["_models.DataCollectionRuleAssociationProxyOnlyResource"]: + # pylint: disable=line-too-long """Lists associations for the specified resource. Lists associations for the specified resource. :param resource_uri: The identifier of the resource. Required. :type resource_uri: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either DataCollectionRuleAssociationProxyOnlyResource or the result of cls(response) :rtype: @@ -251,10 +255,12 @@ def list_by_resource( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-09-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-09-01-preview") + ) cls: ClsType[_models.DataCollectionRuleAssociationProxyOnlyResourceListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -265,15 +271,13 @@ def list_by_resource( def prepare_request(next_link=None): if not next_link: - request = build_list_by_resource_request( + _request = build_list_by_resource_request( resource_uri=resource_uri, api_version=api_version, - template_url=self.list_by_resource.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -284,14 +288,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize( @@ -303,11 +306,11 @@ def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -320,12 +323,11 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_by_resource.metadata = {"url": "/{resourceUri}/providers/Microsoft.Insights/dataCollectionRuleAssociations"} - @distributed_trace def list_by_rule( self, resource_group_name: str, data_collection_rule_name: str, **kwargs: Any ) -> Iterable["_models.DataCollectionRuleAssociationProxyOnlyResource"]: + # pylint: disable=line-too-long """Lists associations for the specified data collection rule. Lists associations for the specified data collection rule. @@ -336,7 +338,6 @@ def list_by_rule( :param data_collection_rule_name: The name of the data collection rule. The name is case insensitive. Required. :type data_collection_rule_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either DataCollectionRuleAssociationProxyOnlyResource or the result of cls(response) :rtype: @@ -346,10 +347,12 @@ def list_by_rule( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-09-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-09-01-preview") + ) cls: ClsType[_models.DataCollectionRuleAssociationProxyOnlyResourceListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -360,17 +363,15 @@ def list_by_rule( def prepare_request(next_link=None): if not next_link: - request = build_list_by_rule_request( + _request = build_list_by_rule_request( resource_group_name=resource_group_name, data_collection_rule_name=data_collection_rule_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_rule.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -381,14 +382,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize( @@ -400,11 +400,11 @@ def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -417,14 +417,11 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_by_rule.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionRules/{dataCollectionRuleName}/associations" - } - @distributed_trace def list_by_data_collection_endpoint( self, resource_group_name: str, data_collection_endpoint_name: str, **kwargs: Any ) -> Iterable["_models.DataCollectionRuleAssociationProxyOnlyResource"]: + # pylint: disable=line-too-long """Lists associations for the specified data collection endpoint. Lists associations for the specified data collection endpoint. @@ -435,7 +432,6 @@ def list_by_data_collection_endpoint( :param data_collection_endpoint_name: The name of the data collection endpoint. The name is case insensitive. Required. :type data_collection_endpoint_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either DataCollectionRuleAssociationProxyOnlyResource or the result of cls(response) :rtype: @@ -445,10 +441,12 @@ def list_by_data_collection_endpoint( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-09-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-09-01-preview") + ) cls: ClsType[_models.DataCollectionRuleAssociationProxyOnlyResourceListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -459,17 +457,15 @@ def list_by_data_collection_endpoint( def prepare_request(next_link=None): if not next_link: - request = build_list_by_data_collection_endpoint_request( + _request = build_list_by_data_collection_endpoint_request( resource_group_name=resource_group_name, data_collection_endpoint_name=data_collection_endpoint_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_data_collection_endpoint.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -480,14 +476,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize( @@ -499,11 +494,11 @@ def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -516,10 +511,6 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_by_data_collection_endpoint.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionEndpoints/{dataCollectionEndpointName}/associations" - } - @distributed_trace def get( self, resource_uri: str, association_name: str, **kwargs: Any @@ -532,13 +523,12 @@ def get( :type resource_uri: str :param association_name: The name of the association. The name is case insensitive. Required. :type association_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: DataCollectionRuleAssociationProxyOnlyResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_02_01_preview.models.DataCollectionRuleAssociationProxyOnlyResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -549,23 +539,23 @@ def get( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-09-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-09-01-preview") + ) cls: ClsType[_models.DataCollectionRuleAssociationProxyOnlyResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_uri=resource_uri, association_name=association_name, api_version=api_version, - template_url=self.get.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -575,16 +565,14 @@ def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponseCommonV2, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("DataCollectionRuleAssociationProxyOnlyResource", pipeline_response) + deserialized = self._deserialize( + "DataCollectionRuleAssociationProxyOnlyResource", pipeline_response.http_response + ) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get.metadata = { - "url": "/{resourceUri}/providers/Microsoft.Insights/dataCollectionRuleAssociations/{associationName}" - } + return deserialized # type: ignore @overload def create( @@ -610,7 +598,6 @@ def create( :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: DataCollectionRuleAssociationProxyOnlyResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_02_01_preview.models.DataCollectionRuleAssociationProxyOnlyResource @@ -622,7 +609,7 @@ def create( self, resource_uri: str, association_name: str, - body: Optional[IO] = None, + body: Optional[IO[bytes]] = None, *, content_type: str = "application/json", **kwargs: Any @@ -636,11 +623,10 @@ def create( :param association_name: The name of the association. The name is case insensitive. Required. :type association_name: str :param body: The payload. Default value is None. - :type body: IO + :type body: 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: DataCollectionRuleAssociationProxyOnlyResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_02_01_preview.models.DataCollectionRuleAssociationProxyOnlyResource @@ -652,7 +638,7 @@ def create( self, resource_uri: str, association_name: str, - body: Optional[Union[_models.DataCollectionRuleAssociationProxyOnlyResource, IO]] = None, + body: Optional[Union[_models.DataCollectionRuleAssociationProxyOnlyResource, IO[bytes]]] = None, **kwargs: Any ) -> _models.DataCollectionRuleAssociationProxyOnlyResource: """Creates or updates an association. @@ -664,20 +650,16 @@ def create( :param association_name: The name of the association. The name is case insensitive. Required. :type association_name: str :param body: The payload. Is either a DataCollectionRuleAssociationProxyOnlyResource type or a - IO type. Default value is None. + IO[bytes] type. Default value is None. :type body: ~azure.mgmt.monitor.v2022_02_01_preview.models.DataCollectionRuleAssociationProxyOnlyResource - 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 + or IO[bytes] :return: DataCollectionRuleAssociationProxyOnlyResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_02_01_preview.models.DataCollectionRuleAssociationProxyOnlyResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -688,14 +670,16 @@ def create( _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", "2021-09-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-09-01-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.DataCollectionRuleAssociationProxyOnlyResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(body, (IO, bytes)): + if isinstance(body, (IOBase, bytes)): _content = body else: if body is not None: @@ -703,23 +687,21 @@ def create( else: _json = None - request = build_create_request( + _request = build_create_request( resource_uri=resource_uri, association_name=association_name, api_version=api_version, content_type=content_type, json=_json, content=_content, - template_url=self.create.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -729,21 +711,15 @@ def create( error = self._deserialize.failsafe_deserialize(_models.ErrorResponseCommonV2, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if response.status_code == 200: - deserialized = self._deserialize("DataCollectionRuleAssociationProxyOnlyResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("DataCollectionRuleAssociationProxyOnlyResource", pipeline_response) + deserialized = self._deserialize( + "DataCollectionRuleAssociationProxyOnlyResource", pipeline_response.http_response + ) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create.metadata = { - "url": "/{resourceUri}/providers/Microsoft.Insights/dataCollectionRuleAssociations/{associationName}" - } - @distributed_trace def delete( # pylint: disable=inconsistent-return-statements self, resource_uri: str, association_name: str, **kwargs: Any @@ -756,12 +732,11 @@ def delete( # pylint: disable=inconsistent-return-statements :type resource_uri: str :param association_name: The name of the association. The name is case insensitive. Required. :type association_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, @@ -772,23 +747,23 @@ def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-09-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-09-01-preview") + ) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_uri=resource_uri, association_name=association_name, api_version=api_version, - template_url=self.delete.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -799,8 +774,4 @@ def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/{resourceUri}/providers/Microsoft.Insights/dataCollectionRuleAssociations/{associationName}" - } + return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/operations/_data_collection_rules_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/operations/_data_collection_rules_operations.py index cac42d3bef4c..ba47c71079ba 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/operations/_data_collection_rules_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_02_01_preview/operations/_data_collection_rules_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload import urllib.parse @@ -19,16 +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, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -55,7 +58,7 @@ def build_list_by_resource_group_request(resource_group_name: str, subscription_ ), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -81,7 +84,7 @@ def build_list_by_subscription_request(subscription_id: str, **kwargs: Any) -> H "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -114,7 +117,7 @@ def build_get_request( "dataCollectionRuleName": _SERIALIZER.url("data_collection_rule_name", data_collection_rule_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -148,7 +151,7 @@ def build_create_request( "dataCollectionRuleName": _SERIALIZER.url("data_collection_rule_name", data_collection_rule_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -184,7 +187,7 @@ def build_update_request( "dataCollectionRuleName": _SERIALIZER.url("data_collection_rule_name", data_collection_rule_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -219,7 +222,7 @@ def build_delete_request( "dataCollectionRuleName": _SERIALIZER.url("data_collection_rule_name", data_collection_rule_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -248,6 +251,7 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list_by_resource_group( @@ -260,7 +264,6 @@ def list_by_resource_group( :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either DataCollectionRuleResource or the result of cls(response) :rtype: @@ -270,10 +273,12 @@ def list_by_resource_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-09-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-09-01-preview") + ) cls: ClsType[_models.DataCollectionRuleResourceListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -284,16 +289,14 @@ 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_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -304,14 +307,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("DataCollectionRuleResourceListResult", pipeline_response) @@ -321,11 +323,11 @@ def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -338,17 +340,12 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionRules" - } - @distributed_trace def list_by_subscription(self, **kwargs: Any) -> Iterable["_models.DataCollectionRuleResource"]: """Lists all data collection rules in the specified subscription. Lists all data collection rules in the specified subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either DataCollectionRuleResource or the result of cls(response) :rtype: @@ -358,10 +355,12 @@ def list_by_subscription(self, **kwargs: Any) -> Iterable["_models.DataCollectio _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-09-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-09-01-preview") + ) cls: ClsType[_models.DataCollectionRuleResourceListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -372,15 +371,13 @@ def list_by_subscription(self, **kwargs: Any) -> Iterable["_models.DataCollectio def prepare_request(next_link=None): if not next_link: - request = build_list_by_subscription_request( + _request = build_list_by_subscription_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_subscription.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -391,14 +388,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("DataCollectionRuleResourceListResult", pipeline_response) @@ -408,11 +404,11 @@ def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -425,10 +421,6 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_by_subscription.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/dataCollectionRules" - } - @distributed_trace def get( self, resource_group_name: str, data_collection_rule_name: str, **kwargs: Any @@ -443,12 +435,11 @@ def get( :param data_collection_rule_name: The name of the data collection rule. The name is case insensitive. Required. :type data_collection_rule_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: DataCollectionRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_02_01_preview.models.DataCollectionRuleResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -459,24 +450,24 @@ def get( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-09-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-09-01-preview") + ) cls: ClsType[_models.DataCollectionRuleResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, data_collection_rule_name=data_collection_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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -486,16 +477,12 @@ def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponseCommonV2, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("DataCollectionRuleResource", pipeline_response) + deserialized = self._deserialize("DataCollectionRuleResource", 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.Insights/dataCollectionRules/{dataCollectionRuleName}" - } + return deserialized # type: ignore @overload def create( @@ -522,7 +509,6 @@ def create( :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: DataCollectionRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_02_01_preview.models.DataCollectionRuleResource :raises ~azure.core.exceptions.HttpResponseError: @@ -533,7 +519,7 @@ def create( self, resource_group_name: str, data_collection_rule_name: str, - body: Optional[IO] = None, + body: Optional[IO[bytes]] = None, *, content_type: str = "application/json", **kwargs: Any @@ -549,11 +535,10 @@ def create( insensitive. Required. :type data_collection_rule_name: str :param body: The payload. Default value is None. - :type body: IO + :type body: 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: DataCollectionRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_02_01_preview.models.DataCollectionRuleResource :raises ~azure.core.exceptions.HttpResponseError: @@ -564,7 +549,7 @@ def create( self, resource_group_name: str, data_collection_rule_name: str, - body: Optional[Union[_models.DataCollectionRuleResource, IO]] = None, + body: Optional[Union[_models.DataCollectionRuleResource, IO[bytes]]] = None, **kwargs: Any ) -> _models.DataCollectionRuleResource: """Creates or updates a data collection rule. @@ -577,18 +562,15 @@ def create( :param data_collection_rule_name: The name of the data collection rule. The name is case insensitive. Required. :type data_collection_rule_name: str - :param body: The payload. Is either a DataCollectionRuleResource type or a IO type. Default - value is None. - :type body: ~azure.mgmt.monitor.v2022_02_01_preview.models.DataCollectionRuleResource or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + :param body: The payload. Is either a DataCollectionRuleResource type or a IO[bytes] type. Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response + :type body: ~azure.mgmt.monitor.v2022_02_01_preview.models.DataCollectionRuleResource or + IO[bytes] :return: DataCollectionRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_02_01_preview.models.DataCollectionRuleResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -599,14 +581,16 @@ def create( _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", "2021-09-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-09-01-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.DataCollectionRuleResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(body, (IO, bytes)): + if isinstance(body, (IOBase, bytes)): _content = body else: if body is not None: @@ -614,7 +598,7 @@ def create( else: _json = None - request = build_create_request( + _request = build_create_request( resource_group_name=resource_group_name, data_collection_rule_name=data_collection_rule_name, subscription_id=self._config.subscription_id, @@ -622,16 +606,14 @@ def create( content_type=content_type, json=_json, content=_content, - template_url=self.create.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -641,21 +623,13 @@ def create( error = self._deserialize.failsafe_deserialize(_models.ErrorResponseCommonV2, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if response.status_code == 200: - deserialized = self._deserialize("DataCollectionRuleResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("DataCollectionRuleResource", pipeline_response) + deserialized = self._deserialize("DataCollectionRuleResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionRules/{dataCollectionRuleName}" - } - @overload def update( self, @@ -681,7 +655,6 @@ def update( :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: DataCollectionRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_02_01_preview.models.DataCollectionRuleResource :raises ~azure.core.exceptions.HttpResponseError: @@ -692,7 +665,7 @@ def update( self, resource_group_name: str, data_collection_rule_name: str, - body: Optional[IO] = None, + body: Optional[IO[bytes]] = None, *, content_type: str = "application/json", **kwargs: Any @@ -708,11 +681,10 @@ def update( insensitive. Required. :type data_collection_rule_name: str :param body: The payload. Default value is None. - :type body: IO + :type body: 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: DataCollectionRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_02_01_preview.models.DataCollectionRuleResource :raises ~azure.core.exceptions.HttpResponseError: @@ -723,7 +695,7 @@ def update( self, resource_group_name: str, data_collection_rule_name: str, - body: Optional[Union[_models.ResourceForUpdate, IO]] = None, + body: Optional[Union[_models.ResourceForUpdate, IO[bytes]]] = None, **kwargs: Any ) -> _models.DataCollectionRuleResource: """Updates part of a data collection rule. @@ -736,18 +708,14 @@ def update( :param data_collection_rule_name: The name of the data collection rule. The name is case insensitive. Required. :type data_collection_rule_name: str - :param body: The payload. Is either a ResourceForUpdate type or a IO type. Default value is - None. - :type body: ~azure.mgmt.monitor.v2022_02_01_preview.models.ResourceForUpdate 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 + :param body: The payload. Is either a ResourceForUpdate type or a IO[bytes] type. Default value + is None. + :type body: ~azure.mgmt.monitor.v2022_02_01_preview.models.ResourceForUpdate or IO[bytes] :return: DataCollectionRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_02_01_preview.models.DataCollectionRuleResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -758,14 +726,16 @@ def update( _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", "2021-09-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-09-01-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.DataCollectionRuleResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(body, (IO, bytes)): + if isinstance(body, (IOBase, bytes)): _content = body else: if body is not None: @@ -773,7 +743,7 @@ def update( else: _json = None - request = build_update_request( + _request = build_update_request( resource_group_name=resource_group_name, data_collection_rule_name=data_collection_rule_name, subscription_id=self._config.subscription_id, @@ -781,16 +751,14 @@ def update( 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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -800,16 +768,12 @@ def update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponseCommonV2, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("DataCollectionRuleResource", pipeline_response) + deserialized = self._deserialize("DataCollectionRuleResource", 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.Insights/dataCollectionRules/{dataCollectionRuleName}" - } + return deserialized # type: ignore @distributed_trace def delete( # pylint: disable=inconsistent-return-statements @@ -825,12 +789,11 @@ def delete( # pylint: disable=inconsistent-return-statements :param data_collection_rule_name: The name of the data collection rule. The name is case insensitive. Required. :type data_collection_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, @@ -841,24 +804,24 @@ def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-09-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2021-09-01-preview") + ) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, data_collection_rule_name=data_collection_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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -869,8 +832,4 @@ def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionRules/{dataCollectionRuleName}" - } + return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_04_01/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_04_01/__init__.py index 2c7733bfd566..42cc62301757 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_04_01/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_04_01/__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 ._monitor_management_client import MonitorManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._monitor_management_client import MonitorManagementClient # type: ignore from ._version import VERSION __version__ = VERSION try: from ._patch import __all__ as _patch_all - from ._patch import * # 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__ = [ "MonitorManagementClient", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_04_01/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_04_01/_configuration.py index 660245741936..682b497ae904 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_04_01/_configuration.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_04_01/_configuration.py @@ -8,18 +8,16 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy from ._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MonitorManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class MonitorManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for MonitorManagementClient. Note that all parameters used to create this instance are saved as instance @@ -35,7 +33,6 @@ class MonitorManagementClientConfiguration(Configuration): # pylint: disable=to """ def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: - super(MonitorManagementClientConfiguration, self).__init__(**kwargs) api_version: str = kwargs.pop("api_version", "2022-04-01") if credential is None: @@ -48,6 +45,7 @@ def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-monitor/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -56,9 +54,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.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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_04_01/_metadata.json b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_04_01/_metadata.json index c8694bb8c160..0696ade2b5b6 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_04_01/_metadata.json +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_04_01/_metadata.json @@ -8,10 +8,10 @@ "host_value": "\"https://management.azure.com\"", "parameterized_host_template": null, "azure_arm": true, - "has_lro_operations": true, + "has_public_lro_operations": true, "client_side_validation": false, - "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"sdkcore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMAutoResourceProviderRegistrationPolicy\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}, \"stdlib\": {\"typing_extensions\": [\"Self\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"sdkcore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"AsyncARMAutoResourceProviderRegistrationPolicy\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}, \"stdlib\": {\"typing_extensions\": [\"Self\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "global_parameters": { "sync": { @@ -101,8 +101,8 @@ "credential_scopes": ["https://management.azure.com/.default"], "credential_call_sync": "ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", "credential_call_async": "AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", - "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "sync_imports": "{\"regular\": {\"sdkcore\": {\"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"regular\": {\"sdkcore\": {\"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "operation_groups": { "action_groups": "ActionGroupsOperations" diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_04_01/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_04_01/_monitor_management_client.py index a0198919ab76..5b82e44274a5 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_04_01/_monitor_management_client.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_04_01/_monitor_management_client.py @@ -8,9 +8,12 @@ from copy import deepcopy from typing import Any, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient +from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy from . import models as _models from .._serialization import Deserializer, Serializer @@ -18,11 +21,10 @@ from .operations import ActionGroupsOperations if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MonitorManagementClient: # pylint: disable=client-accepts-api-version-keyword +class MonitorManagementClient: """Monitor Management Client. :ivar action_groups: ActionGroupsOperations operations @@ -50,15 +52,35 @@ def __init__( self._config = MonitorManagementClientConfiguration( credential=credential, subscription_id=subscription_id, **kwargs ) - self._client: ARMPipelineClient = ARMPipelineClient(base_url=base_url, config=self._config, **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), + 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=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.action_groups = ActionGroupsOperations(self._client, self._config, self._serialize, self._deserialize) + self.action_groups = ActionGroupsOperations( + self._client, self._config, self._serialize, self._deserialize, "2022-04-01" + ) - 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 @@ -78,12 +100,12 @@ 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) -> None: self._client.close() - def __enter__(self) -> "MonitorManagementClient": + def __enter__(self) -> Self: self._client.__enter__() return self diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_04_01/_vendor.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_04_01/_vendor.py deleted file mode 100644 index bd0df84f5319..000000000000 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_04_01/_vendor.py +++ /dev/null @@ -1,30 +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 typing import List, cast - -from azure.core.pipeline.transport import HttpRequest - - -def _convert_request(request, files=None): - data = request.content if not files else None - request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) - if files: - request.set_formdata_body(files) - return request - - -def _format_url_section(template, **kwargs): - components = template.split("/") - while components: - try: - return template.format(**kwargs) - except KeyError as key: - # Need the cast, as for some reasons "split" is typed as list[str | Any] - formatted_components = cast(List[str], template.split("/")) - components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] - template = "/".join(components) diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_04_01/_version.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_04_01/_version.py index 394ee7c0c03c..e5754a47ce68 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_04_01/_version.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_04_01/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "6.0.2" +VERSION = "1.0.0b1" diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_04_01/aio/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_04_01/aio/__init__.py index 2c151bb41c19..3df30ff42149 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_04_01/aio/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_04_01/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 ._monitor_management_client import MonitorManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._monitor_management_client import MonitorManagementClient # type: ignore try: from ._patch import __all__ as _patch_all - from ._patch import * # 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__ = [ "MonitorManagementClient", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_04_01/aio/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_04_01/aio/_configuration.py index 3df538e5f118..7048deab1ed2 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_04_01/aio/_configuration.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_04_01/aio/_configuration.py @@ -8,18 +8,16 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy from .._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MonitorManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class MonitorManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for MonitorManagementClient. Note that all parameters used to create this instance are saved as instance @@ -35,7 +33,6 @@ class MonitorManagementClientConfiguration(Configuration): # pylint: disable=to """ def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: - super(MonitorManagementClientConfiguration, self).__init__(**kwargs) api_version: str = kwargs.pop("api_version", "2022-04-01") if credential is None: @@ -48,6 +45,7 @@ def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **k self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-monitor/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -56,9 +54,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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_04_01/aio/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_04_01/aio/_monitor_management_client.py index 4c55b4206c0b..82554cf54784 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_04_01/aio/_monitor_management_client.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_04_01/aio/_monitor_management_client.py @@ -8,9 +8,12 @@ from copy import deepcopy from typing import Any, Awaitable, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient +from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy from .. import models as _models from ..._serialization import Deserializer, Serializer @@ -18,11 +21,10 @@ from .operations import ActionGroupsOperations if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MonitorManagementClient: # pylint: disable=client-accepts-api-version-keyword +class MonitorManagementClient: """Monitor Management Client. :ivar action_groups: ActionGroupsOperations operations @@ -50,15 +52,37 @@ def __init__( self._config = MonitorManagementClientConfiguration( credential=credential, subscription_id=subscription_id, **kwargs ) - self._client: AsyncARMPipelineClient = AsyncARMPipelineClient(base_url=base_url, config=self._config, **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=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.action_groups = ActionGroupsOperations(self._client, self._config, self._serialize, self._deserialize) + self.action_groups = ActionGroupsOperations( + self._client, self._config, self._serialize, self._deserialize, "2022-04-01" + ) - 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 @@ -78,12 +102,12 @@ 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) -> "MonitorManagementClient": + async def __aenter__(self) -> Self: await self._client.__aenter__() return self diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_04_01/aio/operations/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_04_01/aio/operations/__init__.py index 05f0527dc979..410e631e0472 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_04_01/aio/operations/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_04_01/aio/operations/__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 ._action_groups_operations import ActionGroupsOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._action_groups_operations import ActionGroupsOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ "ActionGroupsOperations", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_04_01/aio/operations/_action_groups_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_04_01/aio/operations/_action_groups_operations.py index f75b03332f7a..f9afd5a7cfc9 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_04_01/aio/operations/_action_groups_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_04_01/aio/operations/_action_groups_operations.py @@ -6,7 +6,9 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload +from io import IOBase +import sys +from typing import Any, AsyncIterable, AsyncIterator, Callable, Dict, IO, Optional, Type, TypeVar, Union, cast, overload import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList @@ -16,12 +18,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 @@ -29,7 +32,6 @@ from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models -from ..._vendor import _convert_request from ...operations._action_groups_operations import ( build_create_notifications_at_resource_group_level_request, build_create_or_update_request, @@ -44,6 +46,10 @@ build_update_request, ) +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -66,6 +72,7 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @overload async def create_or_update( @@ -89,7 +96,6 @@ async def create_or_update( :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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_04_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -100,7 +106,7 @@ async def create_or_update( self, resource_group_name: str, action_group_name: str, - action_group: IO, + action_group: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -113,11 +119,10 @@ async def create_or_update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group: The action group to create or use for the update. Required. - :type action_group: IO + :type action_group: 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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_04_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -128,7 +133,7 @@ async def create_or_update( self, resource_group_name: str, action_group_name: str, - action_group: Union[_models.ActionGroupResource, IO], + action_group: Union[_models.ActionGroupResource, IO[bytes]], **kwargs: Any ) -> _models.ActionGroupResource: """Create a new action group or update an existing one. @@ -139,17 +144,13 @@ async def create_or_update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group: The action group to create or use for the update. Is either a - ActionGroupResource type or a IO type. Required. - :type action_group: ~azure.mgmt.monitor.v2022_04_01.models.ActionGroupResource 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 + ActionGroupResource type or a IO[bytes] type. Required. + :type action_group: ~azure.mgmt.monitor.v2022_04_01.models.ActionGroupResource or IO[bytes] :return: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_04_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -160,19 +161,19 @@ async def create_or_update( _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", "2022-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-04-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ActionGroupResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(action_group, (IO, bytes)): + if isinstance(action_group, (IOBase, bytes)): _content = action_group else: _json = self._serialize.body(action_group, "ActionGroupResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, action_group_name=action_group_name, subscription_id=self._config.subscription_id, @@ -180,16 +181,14 @@ async def create_or_update( 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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -199,21 +198,13 @@ async def create_or_update( 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("ActionGroupResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("ActionGroupResource", pipeline_response) + deserialized = self._deserialize("ActionGroupResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/actionGroups/{actionGroupName}" - } - @distributed_trace_async async def get(self, resource_group_name: str, action_group_name: str, **kwargs: Any) -> _models.ActionGroupResource: """Get an action group. @@ -223,12 +214,11 @@ async def get(self, resource_group_name: str, action_group_name: str, **kwargs: :type resource_group_name: str :param action_group_name: The name of the action group. Required. :type action_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_04_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -239,24 +229,22 @@ async def get(self, resource_group_name: str, action_group_name: str, **kwargs: _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-04-01")) cls: ClsType[_models.ActionGroupResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, action_group_name=action_group_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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -266,21 +254,15 @@ async def get(self, resource_group_name: str, action_group_name: str, **kwargs: error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ActionGroupResource", pipeline_response) + deserialized = self._deserialize("ActionGroupResource", 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.Insights/actionGroups/{actionGroupName}" - } + return deserialized # type: ignore @distributed_trace_async - async def delete( # pylint: disable=inconsistent-return-statements - self, resource_group_name: str, action_group_name: str, **kwargs: Any - ) -> None: + async def delete(self, resource_group_name: str, action_group_name: str, **kwargs: Any) -> None: """Delete an action group. :param resource_group_name: The name of the resource group. The name is case insensitive. @@ -288,12 +270,11 @@ async def delete( # pylint: disable=inconsistent-return-statements :type resource_group_name: str :param action_group_name: The name of the action group. Required. :type action_group_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, @@ -304,24 +285,22 @@ async def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-04-01")) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, action_group_name=action_group_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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -332,11 +311,7 @@ async def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/actionGroups/{actionGroupName}" - } + return cls(pipeline_response, None, {}) # type: ignore @overload async def update( @@ -360,7 +335,6 @@ async def update( :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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_04_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -371,7 +345,7 @@ async def update( self, resource_group_name: str, action_group_name: str, - action_group_patch: IO, + action_group_patch: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -384,11 +358,10 @@ async def update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group_patch: Parameters supplied to the operation. Required. - :type action_group_patch: IO + :type action_group_patch: 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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_04_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -399,7 +372,7 @@ async def update( self, resource_group_name: str, action_group_name: str, - action_group_patch: Union[_models.ActionGroupPatchBody, IO], + action_group_patch: Union[_models.ActionGroupPatchBody, IO[bytes]], **kwargs: Any ) -> _models.ActionGroupResource: """Updates an existing action group's tags. To update other fields use the CreateOrUpdate method. @@ -410,17 +383,14 @@ async def update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group_patch: Parameters supplied to the operation. Is either a - ActionGroupPatchBody type or a IO type. Required. - :type action_group_patch: ~azure.mgmt.monitor.v2022_04_01.models.ActionGroupPatchBody 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 + ActionGroupPatchBody type or a IO[bytes] type. Required. + :type action_group_patch: ~azure.mgmt.monitor.v2022_04_01.models.ActionGroupPatchBody or + IO[bytes] :return: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_04_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -431,19 +401,19 @@ async def update( _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", "2022-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-04-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ActionGroupResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(action_group_patch, (IO, bytes)): + if isinstance(action_group_patch, (IOBase, bytes)): _content = action_group_patch else: _json = self._serialize.body(action_group_patch, "ActionGroupPatchBody") - request = build_update_request( + _request = build_update_request( resource_group_name=resource_group_name, action_group_name=action_group_name, subscription_id=self._config.subscription_id, @@ -451,16 +421,14 @@ async def update( 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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -470,21 +438,17 @@ async def update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ActionGroupResource", pipeline_response) + deserialized = self._deserialize("ActionGroupResource", 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.Insights/actionGroups/{actionGroupName}" - } + return deserialized # type: ignore async def _post_test_notifications_initial( - self, notification_request: Union[_models.NotificationRequestBody, IO], **kwargs: Any - ) -> Optional[_models.TestNotificationDetailsResponse]: - error_map = { + self, notification_request: Union[_models.NotificationRequestBody, IO[bytes]], **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -495,59 +459,56 @@ async def _post_test_notifications_initial( _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", "2022-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-04-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Optional[_models.TestNotificationDetailsResponse]] = kwargs.pop("cls", None) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(notification_request, (IO, bytes)): + if isinstance(notification_request, (IOBase, bytes)): _content = notification_request else: _json = self._serialize.body(notification_request, "NotificationRequestBody") - request = build_post_test_notifications_request( + _request = build_post_test_notifications_request( subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, content=_content, - template_url=self._post_test_notifications_initial.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: + 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 = None response_headers = {} - if response.status_code == 200: - deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response) - if response.status_code == 202: response_headers["location"] = self._deserialize("str", response.headers.get("location")) - if cls: - return cls(pipeline_response, deserialized, response_headers) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - return deserialized + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore - _post_test_notifications_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/createNotifications" - } + return deserialized # type: ignore @overload async def begin_post_test_notifications( @@ -565,14 +526,6 @@ async def begin_post_test_notifications( :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 TestNotificationDetailsResponse or the result of cls(response) :rtype: @@ -582,24 +535,16 @@ async def begin_post_test_notifications( @overload async def begin_post_test_notifications( - self, notification_request: IO, *, content_type: str = "application/json", **kwargs: Any + self, notification_request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.TestNotificationDetailsResponse]: """Send test notifications to a set of provided receivers. :param notification_request: The notification request body which includes the contact details. Required. - :type notification_request: IO + :type notification_request: 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 TestNotificationDetailsResponse or the result of cls(response) :rtype: @@ -609,25 +554,14 @@ async def begin_post_test_notifications( @distributed_trace_async async def begin_post_test_notifications( - self, notification_request: Union[_models.NotificationRequestBody, IO], **kwargs: Any + self, notification_request: Union[_models.NotificationRequestBody, IO[bytes]], **kwargs: Any ) -> AsyncLROPoller[_models.TestNotificationDetailsResponse]: """Send test notifications to a set of provided receivers. :param notification_request: The notification request body which includes the contact details. - Is either a NotificationRequestBody type or a IO type. Required. + Is either a NotificationRequestBody type or a IO[bytes] type. Required. :type notification_request: ~azure.mgmt.monitor.v2022_04_01.models.NotificationRequestBody 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. + IO[bytes] :return: An instance of AsyncLROPoller that returns either TestNotificationDetailsResponse or the result of cls(response) :rtype: @@ -637,7 +571,7 @@ async def begin_post_test_notifications( _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", "2022-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-04-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.TestNotificationDetailsResponse] = kwargs.pop("cls", None) polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) @@ -653,12 +587,13 @@ async def begin_post_test_notifications( 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("TestNotificationDetailsResponse", pipeline_response) + deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: @@ -670,22 +605,23 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return AsyncLROPoller.from_continuation_token( + return AsyncLROPoller[_models.TestNotificationDetailsResponse].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_post_test_notifications.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/createNotifications" - } + return AsyncLROPoller[_models.TestNotificationDetailsResponse]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) async def _create_notifications_at_resource_group_level_initial( # pylint: disable=name-too-long - self, resource_group_name: str, notification_request: Union[_models.NotificationRequestBody, IO], **kwargs: Any - ) -> Optional[_models.TestNotificationDetailsResponse]: - error_map = { + self, + resource_group_name: str, + notification_request: Union[_models.NotificationRequestBody, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -696,60 +632,57 @@ async def _create_notifications_at_resource_group_level_initial( # pylint: disa _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", "2022-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-04-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Optional[_models.TestNotificationDetailsResponse]] = kwargs.pop("cls", None) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(notification_request, (IO, bytes)): + if isinstance(notification_request, (IOBase, bytes)): _content = notification_request else: _json = self._serialize.body(notification_request, "NotificationRequestBody") - request = build_create_notifications_at_resource_group_level_request( + _request = build_create_notifications_at_resource_group_level_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, content=_content, - template_url=self._create_notifications_at_resource_group_level_initial.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: + 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 = None response_headers = {} - if response.status_code == 200: - deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response) - if response.status_code == 202: response_headers["location"] = self._deserialize("str", response.headers.get("location")) - if cls: - return cls(pipeline_response, deserialized, response_headers) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - return deserialized + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore - _create_notifications_at_resource_group_level_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/createNotifications" - } + return deserialized # type: ignore @overload async def begin_create_notifications_at_resource_group_level( # pylint: disable=name-too-long @@ -771,14 +704,6 @@ async def begin_create_notifications_at_resource_group_level( # pylint: disable :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 TestNotificationDetailsResponse or the result of cls(response) :rtype: @@ -790,7 +715,7 @@ async def begin_create_notifications_at_resource_group_level( # pylint: disable async def begin_create_notifications_at_resource_group_level( # pylint: disable=name-too-long self, resource_group_name: str, - notification_request: IO, + notification_request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -802,18 +727,10 @@ async def begin_create_notifications_at_resource_group_level( # pylint: disable :type resource_group_name: str :param notification_request: The notification request body which includes the contact details. Required. - :type notification_request: IO + :type notification_request: 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 TestNotificationDetailsResponse or the result of cls(response) :rtype: @@ -823,7 +740,10 @@ async def begin_create_notifications_at_resource_group_level( # pylint: disable @distributed_trace_async async def begin_create_notifications_at_resource_group_level( # pylint: disable=name-too-long - self, resource_group_name: str, notification_request: Union[_models.NotificationRequestBody, IO], **kwargs: Any + self, + resource_group_name: str, + notification_request: Union[_models.NotificationRequestBody, IO[bytes]], + **kwargs: Any ) -> AsyncLROPoller[_models.TestNotificationDetailsResponse]: """Send test notifications to a set of provided receivers. @@ -831,20 +751,9 @@ async def begin_create_notifications_at_resource_group_level( # pylint: disable Required. :type resource_group_name: str :param notification_request: The notification request body which includes the contact details. - Is either a NotificationRequestBody type or a IO type. Required. + Is either a NotificationRequestBody type or a IO[bytes] type. Required. :type notification_request: ~azure.mgmt.monitor.v2022_04_01.models.NotificationRequestBody 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. + IO[bytes] :return: An instance of AsyncLROPoller that returns either TestNotificationDetailsResponse or the result of cls(response) :rtype: @@ -854,7 +763,7 @@ async def begin_create_notifications_at_resource_group_level( # pylint: disable _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", "2022-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-04-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.TestNotificationDetailsResponse] = kwargs.pop("cls", None) polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) @@ -871,12 +780,13 @@ async def begin_create_notifications_at_resource_group_level( # pylint: disable 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("TestNotificationDetailsResponse", pipeline_response) + deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: @@ -888,17 +798,15 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return AsyncLROPoller.from_continuation_token( + return AsyncLROPoller[_models.TestNotificationDetailsResponse].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_create_notifications_at_resource_group_level.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/createNotifications" - } + return AsyncLROPoller[_models.TestNotificationDetailsResponse]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) @distributed_trace_async async def get_test_notifications( @@ -908,12 +816,11 @@ async def get_test_notifications( :param notification_id: The notification id. Required. :type notification_id: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: TestNotificationDetailsResponse or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_04_01.models.TestNotificationDetailsResponse :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -924,23 +831,21 @@ async def get_test_notifications( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-04-01")) cls: ClsType[_models.TestNotificationDetailsResponse] = kwargs.pop("cls", None) - request = build_get_test_notifications_request( + _request = build_get_test_notifications_request( notification_id=notification_id, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get_test_notifications.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -950,16 +855,12 @@ async def get_test_notifications( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response) + deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get_test_notifications.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/notificationStatus/{notificationId}" - } + return deserialized # type: ignore @distributed_trace_async async def get_test_notifications_at_resource_group_level( # pylint: disable=name-too-long @@ -972,12 +873,11 @@ async def get_test_notifications_at_resource_group_level( # pylint: disable=nam :type resource_group_name: str :param notification_id: The notification id. Required. :type notification_id: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: TestNotificationDetailsResponse or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_04_01.models.TestNotificationDetailsResponse :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -988,24 +888,22 @@ async def get_test_notifications_at_resource_group_level( # pylint: disable=nam _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-04-01")) cls: ClsType[_models.TestNotificationDetailsResponse] = kwargs.pop("cls", None) - request = build_get_test_notifications_at_resource_group_level_request( + _request = build_get_test_notifications_at_resource_group_level_request( resource_group_name=resource_group_name, notification_id=notification_id, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get_test_notifications_at_resource_group_level.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1015,22 +913,17 @@ async def get_test_notifications_at_resource_group_level( # pylint: disable=nam error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response) + deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get_test_notifications_at_resource_group_level.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/notificationStatus/{notificationId}" - } + return deserialized # type: ignore @distributed_trace def list_by_subscription_id(self, **kwargs: Any) -> AsyncIterable["_models.ActionGroupResource"]: """Get a list of all action groups in a subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ActionGroupResource or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.monitor.v2022_04_01.models.ActionGroupResource] @@ -1039,10 +932,10 @@ def list_by_subscription_id(self, **kwargs: Any) -> AsyncIterable["_models.Actio _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-04-01")) cls: ClsType[_models.ActionGroupList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1053,15 +946,13 @@ def list_by_subscription_id(self, **kwargs: Any) -> AsyncIterable["_models.Actio def prepare_request(next_link=None): if not next_link: - request = build_list_by_subscription_id_request( + _request = build_list_by_subscription_id_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_subscription_id.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -1072,14 +963,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("ActionGroupList", pipeline_response) @@ -1089,11 +979,11 @@ async def extract_data(pipeline_response): return None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1106,10 +996,6 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_by_subscription_id.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/actionGroups" - } - @distributed_trace def list_by_resource_group( self, resource_group_name: str, **kwargs: Any @@ -1119,7 +1005,6 @@ def list_by_resource_group( :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ActionGroupResource or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.monitor.v2022_04_01.models.ActionGroupResource] @@ -1128,10 +1013,10 @@ def list_by_resource_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-04-01")) cls: ClsType[_models.ActionGroupList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1142,16 +1027,14 @@ 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_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -1162,14 +1045,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("ActionGroupList", pipeline_response) @@ -1179,11 +1061,11 @@ async def extract_data(pipeline_response): return None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1196,12 +1078,8 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/actionGroups" - } - @overload - async def enable_receiver( # pylint: disable=inconsistent-return-statements + async def enable_receiver( self, resource_group_name: str, action_group_name: str, @@ -1223,18 +1101,17 @@ async def enable_receiver( # pylint: disable=inconsistent-return-statements :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: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def enable_receiver( # pylint: disable=inconsistent-return-statements + async def enable_receiver( self, resource_group_name: str, action_group_name: str, - enable_request: IO, + enable_request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -1248,22 +1125,21 @@ async def enable_receiver( # pylint: disable=inconsistent-return-statements :param action_group_name: The name of the action group. Required. :type action_group_name: str :param enable_request: The receiver to re-enable. Required. - :type enable_request: IO + :type enable_request: 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: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async - async def enable_receiver( # pylint: disable=inconsistent-return-statements + async def enable_receiver( self, resource_group_name: str, action_group_name: str, - enable_request: Union[_models.EnableRequest, IO], + enable_request: Union[_models.EnableRequest, IO[bytes]], **kwargs: Any ) -> None: """Enable a receiver in an action group. This changes the receiver's status from Disabled to @@ -1274,41 +1150,40 @@ async def enable_receiver( # pylint: disable=inconsistent-return-statements :type resource_group_name: str :param action_group_name: The name of the action group. Required. :type action_group_name: str - :param enable_request: The receiver to re-enable. Is either a EnableRequest type or a IO type. - Required. - :type enable_request: ~azure.mgmt.monitor.v2022_04_01.models.EnableRequest 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 + :param enable_request: The receiver to re-enable. Is either a EnableRequest type or a IO[bytes] + type. Required. + :type enable_request: ~azure.mgmt.monitor.v2022_04_01.models.EnableRequest or IO[bytes] :return: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 304: ResourceNotModifiedError, - 409: lambda response: ResourceExistsError(response=response, error_format=ARMErrorFormat), + 409: cast( + Type[HttpResponseError], + lambda response: ResourceExistsError(response=response, error_format=ARMErrorFormat), + ), } 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: str = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-04-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[None] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(enable_request, (IO, bytes)): + if isinstance(enable_request, (IOBase, bytes)): _content = enable_request else: _json = self._serialize.body(enable_request, "EnableRequest") - request = build_enable_receiver_request( + _request = build_enable_receiver_request( resource_group_name=resource_group_name, action_group_name=action_group_name, subscription_id=self._config.subscription_id, @@ -1316,28 +1191,22 @@ async def enable_receiver( # pylint: disable=inconsistent-return-statements content_type=content_type, json=_json, content=_content, - template_url=self.enable_receiver.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _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) + map_error(status_code=response.status_code, response=response, error_map=error_map) # type: ignore 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, {}) - - enable_receiver.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/actionGroups/{actionGroupName}/subscribe" - } + return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_04_01/models/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_04_01/models/__init__.py index b1dac637c403..2e909d448f9e 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_04_01/models/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_04_01/models/__init__.py @@ -5,32 +5,43 @@ # 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 ActionDetail -from ._models_py3 import ActionGroupList -from ._models_py3 import ActionGroupPatchBody -from ._models_py3 import ActionGroupResource -from ._models_py3 import ArmRoleReceiver -from ._models_py3 import AutomationRunbookReceiver -from ._models_py3 import AzureAppPushReceiver -from ._models_py3 import AzureFunctionReceiver -from ._models_py3 import AzureResource -from ._models_py3 import Context -from ._models_py3 import EmailReceiver -from ._models_py3 import EnableRequest -from ._models_py3 import ErrorResponse -from ._models_py3 import EventHubReceiver -from ._models_py3 import ItsmReceiver -from ._models_py3 import LogicAppReceiver -from ._models_py3 import NotificationRequestBody -from ._models_py3 import SmsReceiver -from ._models_py3 import TestNotificationDetailsResponse -from ._models_py3 import VoiceReceiver -from ._models_py3 import WebhookReceiver +from typing import TYPE_CHECKING -from ._monitor_management_client_enums import ReceiverStatus +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models_py3 import ( # type: ignore + ActionDetail, + ActionGroupList, + ActionGroupPatchBody, + ActionGroupResource, + ArmRoleReceiver, + AutomationRunbookReceiver, + AzureAppPushReceiver, + AzureFunctionReceiver, + AzureResource, + Context, + EmailReceiver, + EnableRequest, + ErrorResponse, + EventHubReceiver, + ItsmReceiver, + LogicAppReceiver, + NotificationRequestBody, + SmsReceiver, + TestNotificationDetailsResponse, + VoiceReceiver, + WebhookReceiver, +) + +from ._monitor_management_client_enums import ( # type: ignore + ReceiverStatus, +) from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ @@ -57,5 +68,5 @@ "WebhookReceiver", "ReceiverStatus", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_04_01/models/_models_py3.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_04_01/models/_models_py3.py index b71023d76c8f..700bc26120a9 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_04_01/models/_models_py3.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_04_01/models/_models_py3.py @@ -1,5 +1,5 @@ -# coding=utf-8 # 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. @@ -12,7 +12,6 @@ from ... import _serialization if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from .. import models as _models @@ -141,7 +140,7 @@ class AzureResource(_serialization.Model): 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: Azure resource Id. :vartype id: str @@ -185,12 +184,12 @@ def __init__(self, *, location: str, tags: Optional[Dict[str, str]] = None, **kw self.tags = tags -class ActionGroupResource(AzureResource): # pylint: disable=too-many-instance-attributes +class ActionGroupResource(AzureResource): """An action group 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: Azure resource Id. :vartype id: str @@ -352,7 +351,7 @@ def __init__( class ArmRoleReceiver(_serialization.Model): """An arm role receiver. - 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 name of the arm role receiver. Names must be unique across all receivers within an action group. Required. @@ -393,7 +392,7 @@ def __init__(self, *, name: str, role_id: str, use_common_alert_schema: bool = F class AutomationRunbookReceiver(_serialization.Model): """The Azure Automation Runbook notification receiver. - 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 automation_account_id: The Azure automation account Id which holds this runbook and authenticate to Azure resource. Required. @@ -471,7 +470,7 @@ def __init__( class AzureAppPushReceiver(_serialization.Model): """The Azure mobile App push notification receiver. - 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 name of the Azure mobile app push receiver. Names must be unique across all receivers within an action group. Required. @@ -506,7 +505,7 @@ def __init__(self, *, name: str, email_address: str, **kwargs: Any) -> None: class AzureFunctionReceiver(_serialization.Model): """An azure function receiver. - 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 name of the azure function receiver. Names must be unique across all receivers within an action group. Required. @@ -600,7 +599,7 @@ class EmailReceiver(_serialization.Model): 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 name: The name of the email receiver. Names must be unique across all receivers within an action group. Required. @@ -647,7 +646,7 @@ def __init__(self, *, name: str, email_address: str, use_common_alert_schema: bo class EnableRequest(_serialization.Model): """Describes a receiver that should be resubscribed. - 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 receiver_name: The name of the receiver to resubscribe. Required. :vartype receiver_name: str @@ -699,7 +698,7 @@ def __init__(self, *, code: Optional[str] = None, message: Optional[str] = None, class EventHubReceiver(_serialization.Model): """An Event hub receiver. - 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 name of the Event hub receiver. Names must be unique across all receivers within an action group. Required. @@ -770,7 +769,7 @@ def __init__( class ItsmReceiver(_serialization.Model): """An Itsm receiver. - 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 name of the Itsm receiver. Names must be unique across all receivers within an action group. Required. @@ -784,7 +783,7 @@ class ItsmReceiver(_serialization.Model): CreateMultipleWorkItems option will be part of this blob as well. Required. :vartype ticket_configuration: str :ivar region: Region in which workspace resides. Supported - values:'centralindia','japaneast','southeastasia','australiasoutheast','uksouth','westcentralus','canadacentral','eastus','westeurope'. + values:'centralindia','japaneast','southeastasia','australiasoutheast','uksouth','westcentralus','canadacentral','eastus','westeurope'. # pylint: disable=line-too-long Required. :vartype region: str """ @@ -821,7 +820,7 @@ def __init__( CreateMultipleWorkItems option will be part of this blob as well. Required. :paramtype ticket_configuration: str :keyword region: Region in which workspace resides. Supported - values:'centralindia','japaneast','southeastasia','australiasoutheast','uksouth','westcentralus','canadacentral','eastus','westeurope'. + values:'centralindia','japaneast','southeastasia','australiasoutheast','uksouth','westcentralus','canadacentral','eastus','westeurope'. # pylint: disable=line-too-long Required. :paramtype region: str """ @@ -836,7 +835,7 @@ def __init__( class LogicAppReceiver(_serialization.Model): """A logic app receiver. - 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 name of the logic app receiver. Names must be unique across all receivers within an action group. Required. @@ -883,10 +882,10 @@ def __init__( self.use_common_alert_schema = use_common_alert_schema -class NotificationRequestBody(_serialization.Model): # pylint: disable=too-many-instance-attributes +class NotificationRequestBody(_serialization.Model): """The request body which contain contact detail metadata. - 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 alert_type: The value of the supported alert type. Supported alert type values are: servicehealth, metricstaticthreshold, metricsdynamicthreshold, logalertv2, smartalert, @@ -1018,7 +1017,7 @@ class SmsReceiver(_serialization.Model): 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 name: The name of the SMS receiver. Names must be unique across all receivers within an action group. Required. @@ -1066,7 +1065,7 @@ def __init__(self, *, name: str, country_code: str, phone_number: str, **kwargs: class TestNotificationDetailsResponse(_serialization.Model): """The details of the test notification results. - 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 context: The context info. :vartype context: ~azure.mgmt.monitor.v2022_04_01.models.Context @@ -1125,7 +1124,7 @@ def __init__( class VoiceReceiver(_serialization.Model): """A voice receiver. - 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 name of the voice receiver. Names must be unique across all receivers within an action group. Required. @@ -1167,7 +1166,7 @@ def __init__(self, *, name: str, country_code: str, phone_number: str, **kwargs: class WebhookReceiver(_serialization.Model): """A webhook receiver. - 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 name of the webhook receiver. Names must be unique across all receivers within an action group. Required. diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_04_01/operations/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_04_01/operations/__init__.py index 05f0527dc979..410e631e0472 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_04_01/operations/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_04_01/operations/__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 ._action_groups_operations import ActionGroupsOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._action_groups_operations import ActionGroupsOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ "ActionGroupsOperations", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_04_01/operations/_action_groups_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_04_01/operations/_action_groups_operations.py index fe3985a8494a..730d7baecce2 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_04_01/operations/_action_groups_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_04_01/operations/_action_groups_operations.py @@ -6,7 +6,9 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload +from io import IOBase +import sys +from typing import Any, Callable, Dict, IO, Iterable, Iterator, Optional, Type, TypeVar, Union, cast, overload import urllib.parse from azure.core.exceptions import ( @@ -15,13 +17,14 @@ 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 @@ -29,8 +32,11 @@ from .. import models as _models from ..._serialization import Serializer -from .._vendor import _convert_request, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -61,7 +67,7 @@ def build_create_or_update_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -96,7 +102,7 @@ def build_get_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -129,7 +135,7 @@ def build_delete_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -163,7 +169,7 @@ def build_update_request( "actionGroupName": _SERIALIZER.url("action_group_name", action_group_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -192,7 +198,7 @@ def build_post_test_notifications_request(subscription_id: str, **kwargs: Any) - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -227,7 +233,7 @@ def build_create_notifications_at_resource_group_level_request( # pylint: disab ), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -257,7 +263,7 @@ def build_get_test_notifications_request(notification_id: str, subscription_id: "notificationId": _SERIALIZER.url("notification_id", notification_id, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -290,7 +296,7 @@ def build_get_test_notifications_at_resource_group_level_request( # pylint: dis "notificationId": _SERIALIZER.url("notification_id", notification_id, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -314,7 +320,7 @@ def build_list_by_subscription_id_request(subscription_id: str, **kwargs: Any) - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -344,7 +350,7 @@ def build_list_by_resource_group_request(resource_group_name: str, subscription_ "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -378,7 +384,7 @@ def build_enable_receiver_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -409,6 +415,7 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @overload def create_or_update( @@ -432,7 +439,6 @@ def create_or_update( :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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_04_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -443,7 +449,7 @@ def create_or_update( self, resource_group_name: str, action_group_name: str, - action_group: IO, + action_group: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -456,11 +462,10 @@ def create_or_update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group: The action group to create or use for the update. Required. - :type action_group: IO + :type action_group: 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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_04_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -471,7 +476,7 @@ def create_or_update( self, resource_group_name: str, action_group_name: str, - action_group: Union[_models.ActionGroupResource, IO], + action_group: Union[_models.ActionGroupResource, IO[bytes]], **kwargs: Any ) -> _models.ActionGroupResource: """Create a new action group or update an existing one. @@ -482,17 +487,13 @@ def create_or_update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group: The action group to create or use for the update. Is either a - ActionGroupResource type or a IO type. Required. - :type action_group: ~azure.mgmt.monitor.v2022_04_01.models.ActionGroupResource 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 + ActionGroupResource type or a IO[bytes] type. Required. + :type action_group: ~azure.mgmt.monitor.v2022_04_01.models.ActionGroupResource or IO[bytes] :return: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_04_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -503,19 +504,19 @@ def create_or_update( _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", "2022-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-04-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ActionGroupResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(action_group, (IO, bytes)): + if isinstance(action_group, (IOBase, bytes)): _content = action_group else: _json = self._serialize.body(action_group, "ActionGroupResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, action_group_name=action_group_name, subscription_id=self._config.subscription_id, @@ -523,16 +524,14 @@ def create_or_update( 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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -542,21 +541,13 @@ def create_or_update( 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("ActionGroupResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("ActionGroupResource", pipeline_response) + deserialized = self._deserialize("ActionGroupResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/actionGroups/{actionGroupName}" - } - @distributed_trace def get(self, resource_group_name: str, action_group_name: str, **kwargs: Any) -> _models.ActionGroupResource: """Get an action group. @@ -566,12 +557,11 @@ def get(self, resource_group_name: str, action_group_name: str, **kwargs: Any) - :type resource_group_name: str :param action_group_name: The name of the action group. Required. :type action_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_04_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -582,24 +572,22 @@ def get(self, resource_group_name: str, action_group_name: str, **kwargs: Any) - _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-04-01")) cls: ClsType[_models.ActionGroupResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, action_group_name=action_group_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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -609,16 +597,12 @@ def get(self, resource_group_name: str, action_group_name: str, **kwargs: Any) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ActionGroupResource", pipeline_response) + deserialized = self._deserialize("ActionGroupResource", 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.Insights/actionGroups/{actionGroupName}" - } + return deserialized # type: ignore @distributed_trace def delete( # pylint: disable=inconsistent-return-statements @@ -631,12 +615,11 @@ def delete( # pylint: disable=inconsistent-return-statements :type resource_group_name: str :param action_group_name: The name of the action group. Required. :type action_group_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, @@ -647,24 +630,22 @@ def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-04-01")) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, action_group_name=action_group_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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -675,11 +656,7 @@ def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/actionGroups/{actionGroupName}" - } + return cls(pipeline_response, None, {}) # type: ignore @overload def update( @@ -703,7 +680,6 @@ def update( :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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_04_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -714,7 +690,7 @@ def update( self, resource_group_name: str, action_group_name: str, - action_group_patch: IO, + action_group_patch: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -727,11 +703,10 @@ def update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group_patch: Parameters supplied to the operation. Required. - :type action_group_patch: IO + :type action_group_patch: 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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_04_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -742,7 +717,7 @@ def update( self, resource_group_name: str, action_group_name: str, - action_group_patch: Union[_models.ActionGroupPatchBody, IO], + action_group_patch: Union[_models.ActionGroupPatchBody, IO[bytes]], **kwargs: Any ) -> _models.ActionGroupResource: """Updates an existing action group's tags. To update other fields use the CreateOrUpdate method. @@ -753,17 +728,14 @@ def update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group_patch: Parameters supplied to the operation. Is either a - ActionGroupPatchBody type or a IO type. Required. - :type action_group_patch: ~azure.mgmt.monitor.v2022_04_01.models.ActionGroupPatchBody 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 + ActionGroupPatchBody type or a IO[bytes] type. Required. + :type action_group_patch: ~azure.mgmt.monitor.v2022_04_01.models.ActionGroupPatchBody or + IO[bytes] :return: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_04_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -774,19 +746,19 @@ def update( _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", "2022-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-04-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ActionGroupResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(action_group_patch, (IO, bytes)): + if isinstance(action_group_patch, (IOBase, bytes)): _content = action_group_patch else: _json = self._serialize.body(action_group_patch, "ActionGroupPatchBody") - request = build_update_request( + _request = build_update_request( resource_group_name=resource_group_name, action_group_name=action_group_name, subscription_id=self._config.subscription_id, @@ -794,16 +766,14 @@ def update( 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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -813,21 +783,17 @@ def update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ActionGroupResource", pipeline_response) + deserialized = self._deserialize("ActionGroupResource", 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.Insights/actionGroups/{actionGroupName}" - } + return deserialized # type: ignore def _post_test_notifications_initial( - self, notification_request: Union[_models.NotificationRequestBody, IO], **kwargs: Any - ) -> Optional[_models.TestNotificationDetailsResponse]: - error_map = { + self, notification_request: Union[_models.NotificationRequestBody, IO[bytes]], **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -838,59 +804,56 @@ def _post_test_notifications_initial( _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", "2022-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-04-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Optional[_models.TestNotificationDetailsResponse]] = kwargs.pop("cls", None) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(notification_request, (IO, bytes)): + if isinstance(notification_request, (IOBase, bytes)): _content = notification_request else: _json = self._serialize.body(notification_request, "NotificationRequestBody") - request = build_post_test_notifications_request( + _request = build_post_test_notifications_request( subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, content=_content, - template_url=self._post_test_notifications_initial.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: + 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) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = None response_headers = {} - if response.status_code == 200: - deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response) - if response.status_code == 202: response_headers["location"] = self._deserialize("str", response.headers.get("location")) - if cls: - return cls(pipeline_response, deserialized, response_headers) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - return deserialized + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore - _post_test_notifications_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/createNotifications" - } + return deserialized # type: ignore @overload def begin_post_test_notifications( @@ -908,14 +871,6 @@ def begin_post_test_notifications( :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 TestNotificationDetailsResponse or the result of cls(response) :rtype: @@ -925,24 +880,16 @@ def begin_post_test_notifications( @overload def begin_post_test_notifications( - self, notification_request: IO, *, content_type: str = "application/json", **kwargs: Any + self, notification_request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.TestNotificationDetailsResponse]: """Send test notifications to a set of provided receivers. :param notification_request: The notification request body which includes the contact details. Required. - :type notification_request: IO + :type notification_request: 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 TestNotificationDetailsResponse or the result of cls(response) :rtype: @@ -952,25 +899,14 @@ def begin_post_test_notifications( @distributed_trace def begin_post_test_notifications( - self, notification_request: Union[_models.NotificationRequestBody, IO], **kwargs: Any + self, notification_request: Union[_models.NotificationRequestBody, IO[bytes]], **kwargs: Any ) -> LROPoller[_models.TestNotificationDetailsResponse]: """Send test notifications to a set of provided receivers. :param notification_request: The notification request body which includes the contact details. - Is either a NotificationRequestBody type or a IO type. Required. + Is either a NotificationRequestBody type or a IO[bytes] type. Required. :type notification_request: ~azure.mgmt.monitor.v2022_04_01.models.NotificationRequestBody 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. + IO[bytes] :return: An instance of LROPoller that returns either TestNotificationDetailsResponse or the result of cls(response) :rtype: @@ -980,7 +916,7 @@ def begin_post_test_notifications( _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", "2022-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-04-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.TestNotificationDetailsResponse] = kwargs.pop("cls", None) polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) @@ -996,12 +932,13 @@ def begin_post_test_notifications( 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("TestNotificationDetailsResponse", pipeline_response) + deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: @@ -1013,22 +950,23 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return LROPoller.from_continuation_token( + return LROPoller[_models.TestNotificationDetailsResponse].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_post_test_notifications.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/createNotifications" - } + return LROPoller[_models.TestNotificationDetailsResponse]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) def _create_notifications_at_resource_group_level_initial( # pylint: disable=name-too-long - self, resource_group_name: str, notification_request: Union[_models.NotificationRequestBody, IO], **kwargs: Any - ) -> Optional[_models.TestNotificationDetailsResponse]: - error_map = { + self, + resource_group_name: str, + notification_request: Union[_models.NotificationRequestBody, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1039,60 +977,57 @@ def _create_notifications_at_resource_group_level_initial( # pylint: disable=na _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", "2022-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-04-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Optional[_models.TestNotificationDetailsResponse]] = kwargs.pop("cls", None) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(notification_request, (IO, bytes)): + if isinstance(notification_request, (IOBase, bytes)): _content = notification_request else: _json = self._serialize.body(notification_request, "NotificationRequestBody") - request = build_create_notifications_at_resource_group_level_request( + _request = build_create_notifications_at_resource_group_level_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, content=_content, - template_url=self._create_notifications_at_resource_group_level_initial.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: + 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) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = None response_headers = {} - if response.status_code == 200: - deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response) - if response.status_code == 202: response_headers["location"] = self._deserialize("str", response.headers.get("location")) - if cls: - return cls(pipeline_response, deserialized, response_headers) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - return deserialized + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore - _create_notifications_at_resource_group_level_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/createNotifications" - } + return deserialized # type: ignore @overload def begin_create_notifications_at_resource_group_level( # pylint: disable=name-too-long @@ -1114,14 +1049,6 @@ def begin_create_notifications_at_resource_group_level( # pylint: disable=name- :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 TestNotificationDetailsResponse or the result of cls(response) :rtype: @@ -1133,7 +1060,7 @@ def begin_create_notifications_at_resource_group_level( # pylint: disable=name- def begin_create_notifications_at_resource_group_level( # pylint: disable=name-too-long self, resource_group_name: str, - notification_request: IO, + notification_request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -1145,18 +1072,10 @@ def begin_create_notifications_at_resource_group_level( # pylint: disable=name- :type resource_group_name: str :param notification_request: The notification request body which includes the contact details. Required. - :type notification_request: IO + :type notification_request: 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 TestNotificationDetailsResponse or the result of cls(response) :rtype: @@ -1166,7 +1085,10 @@ def begin_create_notifications_at_resource_group_level( # pylint: disable=name- @distributed_trace def begin_create_notifications_at_resource_group_level( # pylint: disable=name-too-long - self, resource_group_name: str, notification_request: Union[_models.NotificationRequestBody, IO], **kwargs: Any + self, + resource_group_name: str, + notification_request: Union[_models.NotificationRequestBody, IO[bytes]], + **kwargs: Any ) -> LROPoller[_models.TestNotificationDetailsResponse]: """Send test notifications to a set of provided receivers. @@ -1174,20 +1096,9 @@ def begin_create_notifications_at_resource_group_level( # pylint: disable=name- Required. :type resource_group_name: str :param notification_request: The notification request body which includes the contact details. - Is either a NotificationRequestBody type or a IO type. Required. + Is either a NotificationRequestBody type or a IO[bytes] type. Required. :type notification_request: ~azure.mgmt.monitor.v2022_04_01.models.NotificationRequestBody 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. + IO[bytes] :return: An instance of LROPoller that returns either TestNotificationDetailsResponse or the result of cls(response) :rtype: @@ -1197,7 +1108,7 @@ def begin_create_notifications_at_resource_group_level( # pylint: disable=name- _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", "2022-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-04-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.TestNotificationDetailsResponse] = kwargs.pop("cls", None) polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) @@ -1214,12 +1125,13 @@ def begin_create_notifications_at_resource_group_level( # pylint: disable=name- 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("TestNotificationDetailsResponse", pipeline_response) + deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: @@ -1231,17 +1143,15 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return LROPoller.from_continuation_token( + return LROPoller[_models.TestNotificationDetailsResponse].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_create_notifications_at_resource_group_level.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/createNotifications" - } + return LROPoller[_models.TestNotificationDetailsResponse]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) @distributed_trace def get_test_notifications(self, notification_id: str, **kwargs: Any) -> _models.TestNotificationDetailsResponse: @@ -1249,12 +1159,11 @@ def get_test_notifications(self, notification_id: str, **kwargs: Any) -> _models :param notification_id: The notification id. Required. :type notification_id: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: TestNotificationDetailsResponse or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_04_01.models.TestNotificationDetailsResponse :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1265,23 +1174,21 @@ def get_test_notifications(self, notification_id: str, **kwargs: Any) -> _models _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-04-01")) cls: ClsType[_models.TestNotificationDetailsResponse] = kwargs.pop("cls", None) - request = build_get_test_notifications_request( + _request = build_get_test_notifications_request( notification_id=notification_id, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get_test_notifications.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1291,16 +1198,12 @@ def get_test_notifications(self, notification_id: str, **kwargs: Any) -> _models error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response) + deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get_test_notifications.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/notificationStatus/{notificationId}" - } + return deserialized # type: ignore @distributed_trace def get_test_notifications_at_resource_group_level( # pylint: disable=name-too-long @@ -1313,12 +1216,11 @@ def get_test_notifications_at_resource_group_level( # pylint: disable=name-too- :type resource_group_name: str :param notification_id: The notification id. Required. :type notification_id: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: TestNotificationDetailsResponse or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_04_01.models.TestNotificationDetailsResponse :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1329,24 +1231,22 @@ def get_test_notifications_at_resource_group_level( # pylint: disable=name-too- _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-04-01")) cls: ClsType[_models.TestNotificationDetailsResponse] = kwargs.pop("cls", None) - request = build_get_test_notifications_at_resource_group_level_request( + _request = build_get_test_notifications_at_resource_group_level_request( resource_group_name=resource_group_name, notification_id=notification_id, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get_test_notifications_at_resource_group_level.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1356,22 +1256,17 @@ def get_test_notifications_at_resource_group_level( # pylint: disable=name-too- error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response) + deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get_test_notifications_at_resource_group_level.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/notificationStatus/{notificationId}" - } + return deserialized # type: ignore @distributed_trace def list_by_subscription_id(self, **kwargs: Any) -> Iterable["_models.ActionGroupResource"]: """Get a list of all action groups in a subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ActionGroupResource or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.monitor.v2022_04_01.models.ActionGroupResource] @@ -1380,10 +1275,10 @@ def list_by_subscription_id(self, **kwargs: Any) -> Iterable["_models.ActionGrou _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-04-01")) cls: ClsType[_models.ActionGroupList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1394,15 +1289,13 @@ def list_by_subscription_id(self, **kwargs: Any) -> Iterable["_models.ActionGrou def prepare_request(next_link=None): if not next_link: - request = build_list_by_subscription_id_request( + _request = build_list_by_subscription_id_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_subscription_id.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -1413,14 +1306,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("ActionGroupList", pipeline_response) @@ -1430,11 +1322,11 @@ def extract_data(pipeline_response): return None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1447,10 +1339,6 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_by_subscription_id.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/actionGroups" - } - @distributed_trace def list_by_resource_group( self, resource_group_name: str, **kwargs: Any @@ -1460,7 +1348,6 @@ def list_by_resource_group( :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ActionGroupResource or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.monitor.v2022_04_01.models.ActionGroupResource] @@ -1469,10 +1356,10 @@ def list_by_resource_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-04-01")) cls: ClsType[_models.ActionGroupList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1483,16 +1370,14 @@ 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_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -1503,14 +1388,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("ActionGroupList", pipeline_response) @@ -1520,11 +1404,11 @@ def extract_data(pipeline_response): return None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1537,12 +1421,8 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/actionGroups" - } - @overload - def enable_receiver( # pylint: disable=inconsistent-return-statements + def enable_receiver( self, resource_group_name: str, action_group_name: str, @@ -1564,18 +1444,17 @@ def enable_receiver( # pylint: disable=inconsistent-return-statements :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: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def enable_receiver( # pylint: disable=inconsistent-return-statements + def enable_receiver( self, resource_group_name: str, action_group_name: str, - enable_request: IO, + enable_request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -1589,11 +1468,10 @@ def enable_receiver( # pylint: disable=inconsistent-return-statements :param action_group_name: The name of the action group. Required. :type action_group_name: str :param enable_request: The receiver to re-enable. Required. - :type enable_request: IO + :type enable_request: 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: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1604,7 +1482,7 @@ def enable_receiver( # pylint: disable=inconsistent-return-statements self, resource_group_name: str, action_group_name: str, - enable_request: Union[_models.EnableRequest, IO], + enable_request: Union[_models.EnableRequest, IO[bytes]], **kwargs: Any ) -> None: """Enable a receiver in an action group. This changes the receiver's status from Disabled to @@ -1615,41 +1493,40 @@ def enable_receiver( # pylint: disable=inconsistent-return-statements :type resource_group_name: str :param action_group_name: The name of the action group. Required. :type action_group_name: str - :param enable_request: The receiver to re-enable. Is either a EnableRequest type or a IO type. - Required. - :type enable_request: ~azure.mgmt.monitor.v2022_04_01.models.EnableRequest 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 + :param enable_request: The receiver to re-enable. Is either a EnableRequest type or a IO[bytes] + type. Required. + :type enable_request: ~azure.mgmt.monitor.v2022_04_01.models.EnableRequest or IO[bytes] :return: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 304: ResourceNotModifiedError, - 409: lambda response: ResourceExistsError(response=response, error_format=ARMErrorFormat), + 409: cast( + Type[HttpResponseError], + lambda response: ResourceExistsError(response=response, error_format=ARMErrorFormat), + ), } 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: str = kwargs.pop("api_version", _params.pop("api-version", "2022-04-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-04-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[None] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(enable_request, (IO, bytes)): + if isinstance(enable_request, (IOBase, bytes)): _content = enable_request else: _json = self._serialize.body(enable_request, "EnableRequest") - request = build_enable_receiver_request( + _request = build_enable_receiver_request( resource_group_name=resource_group_name, action_group_name=action_group_name, subscription_id=self._config.subscription_id, @@ -1657,28 +1534,22 @@ def enable_receiver( # pylint: disable=inconsistent-return-statements content_type=content_type, json=_json, content=_content, - template_url=self.enable_receiver.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _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) + map_error(status_code=response.status_code, response=response, error_map=error_map) # type: ignore 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, {}) - - enable_receiver.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/actionGroups/{actionGroupName}/subscribe" - } + return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/__init__.py index 2c7733bfd566..42cc62301757 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/__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 ._monitor_management_client import MonitorManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._monitor_management_client import MonitorManagementClient # type: ignore from ._version import VERSION __version__ = VERSION try: from ._patch import __all__ as _patch_all - from ._patch import * # 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__ = [ "MonitorManagementClient", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/_configuration.py index 3f9c93c26b65..6901743eb88e 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/_configuration.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/_configuration.py @@ -8,18 +8,16 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy from ._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MonitorManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class MonitorManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for MonitorManagementClient. Note that all parameters used to create this instance are saved as instance @@ -35,7 +33,6 @@ class MonitorManagementClientConfiguration(Configuration): # pylint: disable=to """ def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: - super(MonitorManagementClientConfiguration, self).__init__(**kwargs) api_version: str = kwargs.pop("api_version", "2022-06-01") if credential is None: @@ -48,6 +45,7 @@ def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-monitor/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -56,9 +54,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.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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/_metadata.json b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/_metadata.json index 8b2e5676ece4..4b3efd837c19 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/_metadata.json +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/_metadata.json @@ -8,10 +8,10 @@ "host_value": "\"https://management.azure.com\"", "parameterized_host_template": null, "azure_arm": true, - "has_lro_operations": true, + "has_public_lro_operations": true, "client_side_validation": false, - "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"sdkcore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMAutoResourceProviderRegistrationPolicy\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}, \"stdlib\": {\"typing_extensions\": [\"Self\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"sdkcore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"AsyncARMAutoResourceProviderRegistrationPolicy\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}, \"stdlib\": {\"typing_extensions\": [\"Self\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "global_parameters": { "sync": { @@ -101,8 +101,8 @@ "credential_scopes": ["https://management.azure.com/.default"], "credential_call_sync": "ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", "credential_call_async": "AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", - "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "sync_imports": "{\"regular\": {\"sdkcore\": {\"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"regular\": {\"sdkcore\": {\"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "operation_groups": { "action_groups": "ActionGroupsOperations", diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/_monitor_management_client.py index bace8c7fbbe6..2d8d7ad08f12 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/_monitor_management_client.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/_monitor_management_client.py @@ -8,9 +8,12 @@ from copy import deepcopy from typing import Any, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient +from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy from . import models as _models from .._serialization import Deserializer, Serializer @@ -23,11 +26,10 @@ ) if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MonitorManagementClient: # pylint: disable=client-accepts-api-version-keyword +class MonitorManagementClient: """Monitor Management Client. :ivar action_groups: ActionGroupsOperations operations @@ -64,24 +66,44 @@ def __init__( self._config = MonitorManagementClientConfiguration( credential=credential, subscription_id=subscription_id, **kwargs ) - self._client: ARMPipelineClient = ARMPipelineClient(base_url=base_url, config=self._config, **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), + 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=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.action_groups = ActionGroupsOperations(self._client, self._config, self._serialize, self._deserialize) + self.action_groups = ActionGroupsOperations( + self._client, self._config, self._serialize, self._deserialize, "2022-06-01" + ) self.data_collection_endpoints = DataCollectionEndpointsOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2022-06-01" ) self.data_collection_rule_associations = DataCollectionRuleAssociationsOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2022-06-01" ) self.data_collection_rules = DataCollectionRulesOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2022-06-01" ) - 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 @@ -101,12 +123,12 @@ 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) -> None: self._client.close() - def __enter__(self) -> "MonitorManagementClient": + def __enter__(self) -> Self: self._client.__enter__() return self diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/_vendor.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/_vendor.py deleted file mode 100644 index bd0df84f5319..000000000000 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/_vendor.py +++ /dev/null @@ -1,30 +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 typing import List, cast - -from azure.core.pipeline.transport import HttpRequest - - -def _convert_request(request, files=None): - data = request.content if not files else None - request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) - if files: - request.set_formdata_body(files) - return request - - -def _format_url_section(template, **kwargs): - components = template.split("/") - while components: - try: - return template.format(**kwargs) - except KeyError as key: - # Need the cast, as for some reasons "split" is typed as list[str | Any] - formatted_components = cast(List[str], template.split("/")) - components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] - template = "/".join(components) diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/_version.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/_version.py index 394ee7c0c03c..e5754a47ce68 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/_version.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "6.0.2" +VERSION = "1.0.0b1" diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/aio/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/aio/__init__.py index 2c151bb41c19..3df30ff42149 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/aio/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/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 ._monitor_management_client import MonitorManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._monitor_management_client import MonitorManagementClient # type: ignore try: from ._patch import __all__ as _patch_all - from ._patch import * # 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__ = [ "MonitorManagementClient", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/aio/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/aio/_configuration.py index 233b355cd156..601a52a6a192 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/aio/_configuration.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/aio/_configuration.py @@ -8,18 +8,16 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy from .._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MonitorManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class MonitorManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for MonitorManagementClient. Note that all parameters used to create this instance are saved as instance @@ -35,7 +33,6 @@ class MonitorManagementClientConfiguration(Configuration): # pylint: disable=to """ def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: - super(MonitorManagementClientConfiguration, self).__init__(**kwargs) api_version: str = kwargs.pop("api_version", "2022-06-01") if credential is None: @@ -48,6 +45,7 @@ def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **k self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-monitor/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -56,9 +54,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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/aio/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/aio/_monitor_management_client.py index 628c870841c8..38b5eb08257b 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/aio/_monitor_management_client.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/aio/_monitor_management_client.py @@ -8,9 +8,12 @@ from copy import deepcopy from typing import Any, Awaitable, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient +from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy from .. import models as _models from ..._serialization import Deserializer, Serializer @@ -23,11 +26,10 @@ ) if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MonitorManagementClient: # pylint: disable=client-accepts-api-version-keyword +class MonitorManagementClient: """Monitor Management Client. :ivar action_groups: ActionGroupsOperations operations @@ -64,24 +66,46 @@ def __init__( self._config = MonitorManagementClientConfiguration( credential=credential, subscription_id=subscription_id, **kwargs ) - self._client: AsyncARMPipelineClient = AsyncARMPipelineClient(base_url=base_url, config=self._config, **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=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.action_groups = ActionGroupsOperations(self._client, self._config, self._serialize, self._deserialize) + self.action_groups = ActionGroupsOperations( + self._client, self._config, self._serialize, self._deserialize, "2022-06-01" + ) self.data_collection_endpoints = DataCollectionEndpointsOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2022-06-01" ) self.data_collection_rule_associations = DataCollectionRuleAssociationsOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2022-06-01" ) self.data_collection_rules = DataCollectionRulesOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2022-06-01" ) - 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 @@ -101,12 +125,12 @@ 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) -> "MonitorManagementClient": + async def __aenter__(self) -> Self: await self._client.__aenter__() return self diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/aio/operations/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/aio/operations/__init__.py index 134b182d222e..59365f23b2ca 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/aio/operations/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/aio/operations/__init__.py @@ -5,14 +5,20 @@ # 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 ._action_groups_operations import ActionGroupsOperations -from ._data_collection_endpoints_operations import DataCollectionEndpointsOperations -from ._data_collection_rule_associations_operations import DataCollectionRuleAssociationsOperations -from ._data_collection_rules_operations import DataCollectionRulesOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._action_groups_operations import ActionGroupsOperations # type: ignore +from ._data_collection_endpoints_operations import DataCollectionEndpointsOperations # type: ignore +from ._data_collection_rule_associations_operations import DataCollectionRuleAssociationsOperations # type: ignore +from ._data_collection_rules_operations import DataCollectionRulesOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ @@ -21,5 +27,5 @@ "DataCollectionRuleAssociationsOperations", "DataCollectionRulesOperations", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/aio/operations/_action_groups_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/aio/operations/_action_groups_operations.py index 6dddebf368bd..573eab50ff4a 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/aio/operations/_action_groups_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/aio/operations/_action_groups_operations.py @@ -6,7 +6,9 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload +from io import IOBase +import sys +from typing import Any, AsyncIterable, AsyncIterator, Callable, Dict, IO, Optional, Type, TypeVar, Union, cast, overload import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList @@ -16,12 +18,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 @@ -29,7 +32,6 @@ from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models -from ..._vendor import _convert_request from ...operations._action_groups_operations import ( build_create_notifications_at_action_group_resource_level_request, build_create_notifications_at_resource_group_level_request, @@ -46,6 +48,10 @@ build_update_request, ) +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -68,6 +74,7 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @overload async def create_or_update( @@ -91,7 +98,6 @@ async def create_or_update( :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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_06_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -102,7 +108,7 @@ async def create_or_update( self, resource_group_name: str, action_group_name: str, - action_group: IO, + action_group: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -115,11 +121,10 @@ async def create_or_update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group: The action group to create or use for the update. Required. - :type action_group: IO + :type action_group: 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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_06_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -130,7 +135,7 @@ async def create_or_update( self, resource_group_name: str, action_group_name: str, - action_group: Union[_models.ActionGroupResource, IO], + action_group: Union[_models.ActionGroupResource, IO[bytes]], **kwargs: Any ) -> _models.ActionGroupResource: """Create a new action group or update an existing one. @@ -141,17 +146,13 @@ async def create_or_update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group: The action group to create or use for the update. Is either a - ActionGroupResource type or a IO type. Required. - :type action_group: ~azure.mgmt.monitor.v2022_06_01.models.ActionGroupResource 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 + ActionGroupResource type or a IO[bytes] type. Required. + :type action_group: ~azure.mgmt.monitor.v2022_06_01.models.ActionGroupResource or IO[bytes] :return: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_06_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -162,19 +163,19 @@ async def create_or_update( _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", "2022-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-06-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ActionGroupResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(action_group, (IO, bytes)): + if isinstance(action_group, (IOBase, bytes)): _content = action_group else: _json = self._serialize.body(action_group, "ActionGroupResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, action_group_name=action_group_name, subscription_id=self._config.subscription_id, @@ -182,16 +183,14 @@ async def create_or_update( 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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -201,21 +200,13 @@ async def create_or_update( 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("ActionGroupResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("ActionGroupResource", pipeline_response) + deserialized = self._deserialize("ActionGroupResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/actionGroups/{actionGroupName}" - } - @distributed_trace_async async def get(self, resource_group_name: str, action_group_name: str, **kwargs: Any) -> _models.ActionGroupResource: """Get an action group. @@ -225,12 +216,11 @@ async def get(self, resource_group_name: str, action_group_name: str, **kwargs: :type resource_group_name: str :param action_group_name: The name of the action group. Required. :type action_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_06_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -241,24 +231,22 @@ async def get(self, resource_group_name: str, action_group_name: str, **kwargs: _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-06-01")) cls: ClsType[_models.ActionGroupResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, action_group_name=action_group_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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -268,21 +256,15 @@ async def get(self, resource_group_name: str, action_group_name: str, **kwargs: error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ActionGroupResource", pipeline_response) + deserialized = self._deserialize("ActionGroupResource", 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.Insights/actionGroups/{actionGroupName}" - } + return deserialized # type: ignore @distributed_trace_async - async def delete( # pylint: disable=inconsistent-return-statements - self, resource_group_name: str, action_group_name: str, **kwargs: Any - ) -> None: + async def delete(self, resource_group_name: str, action_group_name: str, **kwargs: Any) -> None: """Delete an action group. :param resource_group_name: The name of the resource group. The name is case insensitive. @@ -290,12 +272,11 @@ async def delete( # pylint: disable=inconsistent-return-statements :type resource_group_name: str :param action_group_name: The name of the action group. Required. :type action_group_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, @@ -306,24 +287,22 @@ async def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-06-01")) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, action_group_name=action_group_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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -334,11 +313,7 @@ async def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/actionGroups/{actionGroupName}" - } + return cls(pipeline_response, None, {}) # type: ignore @overload async def update( @@ -362,7 +337,6 @@ async def update( :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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_06_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -373,7 +347,7 @@ async def update( self, resource_group_name: str, action_group_name: str, - action_group_patch: IO, + action_group_patch: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -386,11 +360,10 @@ async def update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group_patch: Parameters supplied to the operation. Required. - :type action_group_patch: IO + :type action_group_patch: 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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_06_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -401,7 +374,7 @@ async def update( self, resource_group_name: str, action_group_name: str, - action_group_patch: Union[_models.ActionGroupPatchBody, IO], + action_group_patch: Union[_models.ActionGroupPatchBody, IO[bytes]], **kwargs: Any ) -> _models.ActionGroupResource: """Updates an existing action group's tags. To update other fields use the CreateOrUpdate method. @@ -412,17 +385,14 @@ async def update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group_patch: Parameters supplied to the operation. Is either a - ActionGroupPatchBody type or a IO type. Required. - :type action_group_patch: ~azure.mgmt.monitor.v2022_06_01.models.ActionGroupPatchBody 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 + ActionGroupPatchBody type or a IO[bytes] type. Required. + :type action_group_patch: ~azure.mgmt.monitor.v2022_06_01.models.ActionGroupPatchBody or + IO[bytes] :return: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_06_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -433,19 +403,19 @@ async def update( _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", "2022-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-06-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ActionGroupResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(action_group_patch, (IO, bytes)): + if isinstance(action_group_patch, (IOBase, bytes)): _content = action_group_patch else: _json = self._serialize.body(action_group_patch, "ActionGroupPatchBody") - request = build_update_request( + _request = build_update_request( resource_group_name=resource_group_name, action_group_name=action_group_name, subscription_id=self._config.subscription_id, @@ -453,16 +423,14 @@ async def update( 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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -472,21 +440,17 @@ async def update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ActionGroupResource", pipeline_response) + deserialized = self._deserialize("ActionGroupResource", 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.Insights/actionGroups/{actionGroupName}" - } + return deserialized # type: ignore async def _post_test_notifications_initial( - self, notification_request: Union[_models.NotificationRequestBody, IO], **kwargs: Any - ) -> Optional[_models.TestNotificationDetailsResponse]: - error_map = { + self, notification_request: Union[_models.NotificationRequestBody, IO[bytes]], **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -497,59 +461,56 @@ async def _post_test_notifications_initial( _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", "2022-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-06-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Optional[_models.TestNotificationDetailsResponse]] = kwargs.pop("cls", None) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(notification_request, (IO, bytes)): + if isinstance(notification_request, (IOBase, bytes)): _content = notification_request else: _json = self._serialize.body(notification_request, "NotificationRequestBody") - request = build_post_test_notifications_request( + _request = build_post_test_notifications_request( subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, content=_content, - template_url=self._post_test_notifications_initial.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: + 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 = None response_headers = {} - if response.status_code == 200: - deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response) - if response.status_code == 202: response_headers["location"] = self._deserialize("str", response.headers.get("location")) - if cls: - return cls(pipeline_response, deserialized, response_headers) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - return deserialized + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore - _post_test_notifications_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/createNotifications" - } + return deserialized # type: ignore @overload async def begin_post_test_notifications( @@ -567,14 +528,6 @@ async def begin_post_test_notifications( :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 TestNotificationDetailsResponse or the result of cls(response) :rtype: @@ -584,24 +537,16 @@ async def begin_post_test_notifications( @overload async def begin_post_test_notifications( - self, notification_request: IO, *, content_type: str = "application/json", **kwargs: Any + self, notification_request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.TestNotificationDetailsResponse]: """Send test notifications to a set of provided receivers. :param notification_request: The notification request body which includes the contact details. Required. - :type notification_request: IO + :type notification_request: 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 TestNotificationDetailsResponse or the result of cls(response) :rtype: @@ -611,25 +556,14 @@ async def begin_post_test_notifications( @distributed_trace_async async def begin_post_test_notifications( - self, notification_request: Union[_models.NotificationRequestBody, IO], **kwargs: Any + self, notification_request: Union[_models.NotificationRequestBody, IO[bytes]], **kwargs: Any ) -> AsyncLROPoller[_models.TestNotificationDetailsResponse]: """Send test notifications to a set of provided receivers. :param notification_request: The notification request body which includes the contact details. - Is either a NotificationRequestBody type or a IO type. Required. + Is either a NotificationRequestBody type or a IO[bytes] type. Required. :type notification_request: ~azure.mgmt.monitor.v2022_06_01.models.NotificationRequestBody 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. + IO[bytes] :return: An instance of AsyncLROPoller that returns either TestNotificationDetailsResponse or the result of cls(response) :rtype: @@ -639,7 +573,7 @@ async def begin_post_test_notifications( _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", "2022-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-06-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.TestNotificationDetailsResponse] = kwargs.pop("cls", None) polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) @@ -655,12 +589,13 @@ async def begin_post_test_notifications( 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("TestNotificationDetailsResponse", pipeline_response) + deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: @@ -672,22 +607,23 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return AsyncLROPoller.from_continuation_token( + return AsyncLROPoller[_models.TestNotificationDetailsResponse].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_post_test_notifications.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/createNotifications" - } + return AsyncLROPoller[_models.TestNotificationDetailsResponse]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) async def _create_notifications_at_resource_group_level_initial( # pylint: disable=name-too-long - self, resource_group_name: str, notification_request: Union[_models.NotificationRequestBody, IO], **kwargs: Any - ) -> Optional[_models.TestNotificationDetailsResponse]: - error_map = { + self, + resource_group_name: str, + notification_request: Union[_models.NotificationRequestBody, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -698,60 +634,57 @@ async def _create_notifications_at_resource_group_level_initial( # pylint: disa _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", "2022-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-06-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Optional[_models.TestNotificationDetailsResponse]] = kwargs.pop("cls", None) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(notification_request, (IO, bytes)): + if isinstance(notification_request, (IOBase, bytes)): _content = notification_request else: _json = self._serialize.body(notification_request, "NotificationRequestBody") - request = build_create_notifications_at_resource_group_level_request( + _request = build_create_notifications_at_resource_group_level_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, content=_content, - template_url=self._create_notifications_at_resource_group_level_initial.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: + 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 = None response_headers = {} - if response.status_code == 200: - deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response) - if response.status_code == 202: response_headers["location"] = self._deserialize("str", response.headers.get("location")) - if cls: - return cls(pipeline_response, deserialized, response_headers) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - return deserialized + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore - _create_notifications_at_resource_group_level_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/createNotifications" - } + return deserialized # type: ignore @overload async def begin_create_notifications_at_resource_group_level( # pylint: disable=name-too-long @@ -773,14 +706,6 @@ async def begin_create_notifications_at_resource_group_level( # pylint: disable :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 TestNotificationDetailsResponse or the result of cls(response) :rtype: @@ -792,7 +717,7 @@ async def begin_create_notifications_at_resource_group_level( # pylint: disable async def begin_create_notifications_at_resource_group_level( # pylint: disable=name-too-long self, resource_group_name: str, - notification_request: IO, + notification_request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -804,18 +729,10 @@ async def begin_create_notifications_at_resource_group_level( # pylint: disable :type resource_group_name: str :param notification_request: The notification request body which includes the contact details. Required. - :type notification_request: IO + :type notification_request: 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 TestNotificationDetailsResponse or the result of cls(response) :rtype: @@ -825,7 +742,10 @@ async def begin_create_notifications_at_resource_group_level( # pylint: disable @distributed_trace_async async def begin_create_notifications_at_resource_group_level( # pylint: disable=name-too-long - self, resource_group_name: str, notification_request: Union[_models.NotificationRequestBody, IO], **kwargs: Any + self, + resource_group_name: str, + notification_request: Union[_models.NotificationRequestBody, IO[bytes]], + **kwargs: Any ) -> AsyncLROPoller[_models.TestNotificationDetailsResponse]: """Send test notifications to a set of provided receivers. @@ -833,20 +753,9 @@ async def begin_create_notifications_at_resource_group_level( # pylint: disable Required. :type resource_group_name: str :param notification_request: The notification request body which includes the contact details. - Is either a NotificationRequestBody type or a IO type. Required. + Is either a NotificationRequestBody type or a IO[bytes] type. Required. :type notification_request: ~azure.mgmt.monitor.v2022_06_01.models.NotificationRequestBody 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. + IO[bytes] :return: An instance of AsyncLROPoller that returns either TestNotificationDetailsResponse or the result of cls(response) :rtype: @@ -856,7 +765,7 @@ async def begin_create_notifications_at_resource_group_level( # pylint: disable _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", "2022-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-06-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.TestNotificationDetailsResponse] = kwargs.pop("cls", None) polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) @@ -873,12 +782,13 @@ async def begin_create_notifications_at_resource_group_level( # pylint: disable 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("TestNotificationDetailsResponse", pipeline_response) + deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: @@ -890,26 +800,24 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return AsyncLROPoller.from_continuation_token( + return AsyncLROPoller[_models.TestNotificationDetailsResponse].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_create_notifications_at_resource_group_level.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/createNotifications" - } + return AsyncLROPoller[_models.TestNotificationDetailsResponse]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) async def _create_notifications_at_action_group_resource_level_initial( # pylint: disable=name-too-long self, resource_group_name: str, action_group_name: str, - notification_request: Union[_models.NotificationRequestBody, IO], + notification_request: Union[_models.NotificationRequestBody, IO[bytes]], **kwargs: Any - ) -> Optional[_models.TestNotificationDetailsResponse]: - error_map = { + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -920,19 +828,19 @@ async def _create_notifications_at_action_group_resource_level_initial( # pylin _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", "2022-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-06-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Optional[_models.TestNotificationDetailsResponse]] = kwargs.pop("cls", None) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(notification_request, (IO, bytes)): + if isinstance(notification_request, (IOBase, bytes)): _content = notification_request else: _json = self._serialize.body(notification_request, "NotificationRequestBody") - request = build_create_notifications_at_action_group_resource_level_request( + _request = build_create_notifications_at_action_group_resource_level_request( resource_group_name=resource_group_name, action_group_name=action_group_name, subscription_id=self._config.subscription_id, @@ -940,41 +848,38 @@ async def _create_notifications_at_action_group_resource_level_initial( # pylin content_type=content_type, json=_json, content=_content, - template_url=self._create_notifications_at_action_group_resource_level_initial.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: + 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 = None response_headers = {} - if response.status_code == 200: - deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response) - if response.status_code == 202: response_headers["location"] = self._deserialize("str", response.headers.get("location")) - if cls: - return cls(pipeline_response, deserialized, response_headers) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - return deserialized + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore - _create_notifications_at_action_group_resource_level_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/actionGroups/{actionGroupName}/createNotifications" - } + return deserialized # type: ignore @overload async def begin_create_notifications_at_action_group_resource_level( # pylint: disable=name-too-long @@ -999,14 +904,6 @@ async def begin_create_notifications_at_action_group_resource_level( # pylint: :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 TestNotificationDetailsResponse or the result of cls(response) :rtype: @@ -1019,7 +916,7 @@ async def begin_create_notifications_at_action_group_resource_level( # pylint: self, resource_group_name: str, action_group_name: str, - notification_request: IO, + notification_request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -1033,18 +930,10 @@ async def begin_create_notifications_at_action_group_resource_level( # pylint: :type action_group_name: str :param notification_request: The notification request body which includes the contact details. Required. - :type notification_request: IO + :type notification_request: 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 TestNotificationDetailsResponse or the result of cls(response) :rtype: @@ -1057,7 +946,7 @@ async def begin_create_notifications_at_action_group_resource_level( # pylint: self, resource_group_name: str, action_group_name: str, - notification_request: Union[_models.NotificationRequestBody, IO], + notification_request: Union[_models.NotificationRequestBody, IO[bytes]], **kwargs: Any ) -> AsyncLROPoller[_models.TestNotificationDetailsResponse]: """Send test notifications to a set of provided receivers. @@ -1068,20 +957,9 @@ async def begin_create_notifications_at_action_group_resource_level( # pylint: :param action_group_name: The name of the action group. Required. :type action_group_name: str :param notification_request: The notification request body which includes the contact details. - Is either a NotificationRequestBody type or a IO type. Required. + Is either a NotificationRequestBody type or a IO[bytes] type. Required. :type notification_request: ~azure.mgmt.monitor.v2022_06_01.models.NotificationRequestBody 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. + IO[bytes] :return: An instance of AsyncLROPoller that returns either TestNotificationDetailsResponse or the result of cls(response) :rtype: @@ -1091,7 +969,7 @@ async def begin_create_notifications_at_action_group_resource_level( # pylint: _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", "2022-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-06-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.TestNotificationDetailsResponse] = kwargs.pop("cls", None) polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) @@ -1109,12 +987,13 @@ async def begin_create_notifications_at_action_group_resource_level( # pylint: 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("TestNotificationDetailsResponse", pipeline_response) + deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: @@ -1126,17 +1005,15 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return AsyncLROPoller.from_continuation_token( + return AsyncLROPoller[_models.TestNotificationDetailsResponse].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_create_notifications_at_action_group_resource_level.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/actionGroups/{actionGroupName}/createNotifications" - } + return AsyncLROPoller[_models.TestNotificationDetailsResponse]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) @distributed_trace_async async def get_test_notifications( @@ -1146,12 +1023,11 @@ async def get_test_notifications( :param notification_id: The notification id. Required. :type notification_id: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: TestNotificationDetailsResponse or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_06_01.models.TestNotificationDetailsResponse :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1162,23 +1038,21 @@ async def get_test_notifications( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-06-01")) cls: ClsType[_models.TestNotificationDetailsResponse] = kwargs.pop("cls", None) - request = build_get_test_notifications_request( + _request = build_get_test_notifications_request( notification_id=notification_id, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get_test_notifications.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1188,16 +1062,12 @@ async def get_test_notifications( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response) + deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get_test_notifications.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/notificationStatus/{notificationId}" - } + return deserialized # type: ignore @distributed_trace_async async def get_test_notifications_at_resource_group_level( # pylint: disable=name-too-long @@ -1210,12 +1080,11 @@ async def get_test_notifications_at_resource_group_level( # pylint: disable=nam :type resource_group_name: str :param notification_id: The notification id. Required. :type notification_id: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: TestNotificationDetailsResponse or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_06_01.models.TestNotificationDetailsResponse :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1226,24 +1095,22 @@ async def get_test_notifications_at_resource_group_level( # pylint: disable=nam _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-06-01")) cls: ClsType[_models.TestNotificationDetailsResponse] = kwargs.pop("cls", None) - request = build_get_test_notifications_at_resource_group_level_request( + _request = build_get_test_notifications_at_resource_group_level_request( resource_group_name=resource_group_name, notification_id=notification_id, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get_test_notifications_at_resource_group_level.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1253,16 +1120,12 @@ async def get_test_notifications_at_resource_group_level( # pylint: disable=nam error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response) + deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get_test_notifications_at_resource_group_level.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/notificationStatus/{notificationId}" - } + return deserialized # type: ignore @distributed_trace_async async def get_test_notifications_at_action_group_resource_level( # pylint: disable=name-too-long @@ -1277,12 +1140,11 @@ async def get_test_notifications_at_action_group_resource_level( # pylint: disa :type action_group_name: str :param notification_id: The notification id. Required. :type notification_id: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: TestNotificationDetailsResponse or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_06_01.models.TestNotificationDetailsResponse :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1293,25 +1155,23 @@ async def get_test_notifications_at_action_group_resource_level( # pylint: disa _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-06-01")) cls: ClsType[_models.TestNotificationDetailsResponse] = kwargs.pop("cls", None) - request = build_get_test_notifications_at_action_group_resource_level_request( + _request = build_get_test_notifications_at_action_group_resource_level_request( resource_group_name=resource_group_name, action_group_name=action_group_name, notification_id=notification_id, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get_test_notifications_at_action_group_resource_level.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1321,22 +1181,17 @@ async def get_test_notifications_at_action_group_resource_level( # pylint: disa error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response) + deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get_test_notifications_at_action_group_resource_level.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/actionGroups/{actionGroupName}/notificationStatus/{notificationId}" - } + return deserialized # type: ignore @distributed_trace def list_by_subscription_id(self, **kwargs: Any) -> AsyncIterable["_models.ActionGroupResource"]: """Get a list of all action groups in a subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ActionGroupResource or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.monitor.v2022_06_01.models.ActionGroupResource] @@ -1345,10 +1200,10 @@ def list_by_subscription_id(self, **kwargs: Any) -> AsyncIterable["_models.Actio _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-06-01")) cls: ClsType[_models.ActionGroupList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1359,15 +1214,13 @@ def list_by_subscription_id(self, **kwargs: Any) -> AsyncIterable["_models.Actio def prepare_request(next_link=None): if not next_link: - request = build_list_by_subscription_id_request( + _request = build_list_by_subscription_id_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_subscription_id.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -1378,14 +1231,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("ActionGroupList", pipeline_response) @@ -1395,11 +1247,11 @@ async def extract_data(pipeline_response): return None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1412,10 +1264,6 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_by_subscription_id.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/actionGroups" - } - @distributed_trace def list_by_resource_group( self, resource_group_name: str, **kwargs: Any @@ -1425,7 +1273,6 @@ def list_by_resource_group( :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ActionGroupResource or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.monitor.v2022_06_01.models.ActionGroupResource] @@ -1434,10 +1281,10 @@ def list_by_resource_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-06-01")) cls: ClsType[_models.ActionGroupList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1448,16 +1295,14 @@ 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_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -1468,14 +1313,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("ActionGroupList", pipeline_response) @@ -1485,11 +1329,11 @@ async def extract_data(pipeline_response): return None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1502,12 +1346,8 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/actionGroups" - } - @overload - async def enable_receiver( # pylint: disable=inconsistent-return-statements + async def enable_receiver( self, resource_group_name: str, action_group_name: str, @@ -1529,18 +1369,17 @@ async def enable_receiver( # pylint: disable=inconsistent-return-statements :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: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def enable_receiver( # pylint: disable=inconsistent-return-statements + async def enable_receiver( self, resource_group_name: str, action_group_name: str, - enable_request: IO, + enable_request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -1554,22 +1393,21 @@ async def enable_receiver( # pylint: disable=inconsistent-return-statements :param action_group_name: The name of the action group. Required. :type action_group_name: str :param enable_request: The receiver to re-enable. Required. - :type enable_request: IO + :type enable_request: 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: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async - async def enable_receiver( # pylint: disable=inconsistent-return-statements + async def enable_receiver( self, resource_group_name: str, action_group_name: str, - enable_request: Union[_models.EnableRequest, IO], + enable_request: Union[_models.EnableRequest, IO[bytes]], **kwargs: Any ) -> None: """Enable a receiver in an action group. This changes the receiver's status from Disabled to @@ -1580,41 +1418,40 @@ async def enable_receiver( # pylint: disable=inconsistent-return-statements :type resource_group_name: str :param action_group_name: The name of the action group. Required. :type action_group_name: str - :param enable_request: The receiver to re-enable. Is either a EnableRequest type or a IO type. - Required. - :type enable_request: ~azure.mgmt.monitor.v2022_06_01.models.EnableRequest 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 + :param enable_request: The receiver to re-enable. Is either a EnableRequest type or a IO[bytes] + type. Required. + :type enable_request: ~azure.mgmt.monitor.v2022_06_01.models.EnableRequest or IO[bytes] :return: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 304: ResourceNotModifiedError, - 409: lambda response: ResourceExistsError(response=response, error_format=ARMErrorFormat), + 409: cast( + Type[HttpResponseError], + lambda response: ResourceExistsError(response=response, error_format=ARMErrorFormat), + ), } 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: str = kwargs.pop("api_version", _params.pop("api-version", "2022-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-06-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[None] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(enable_request, (IO, bytes)): + if isinstance(enable_request, (IOBase, bytes)): _content = enable_request else: _json = self._serialize.body(enable_request, "EnableRequest") - request = build_enable_receiver_request( + _request = build_enable_receiver_request( resource_group_name=resource_group_name, action_group_name=action_group_name, subscription_id=self._config.subscription_id, @@ -1622,28 +1459,22 @@ async def enable_receiver( # pylint: disable=inconsistent-return-statements content_type=content_type, json=_json, content=_content, - template_url=self.enable_receiver.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _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) + map_error(status_code=response.status_code, response=response, error_map=error_map) # type: ignore 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, {}) - - enable_receiver.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/actionGroups/{actionGroupName}/subscribe" - } + return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/aio/operations/_data_collection_endpoints_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/aio/operations/_data_collection_endpoints_operations.py index c35260518aa9..a14df90831bb 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/aio/operations/_data_collection_endpoints_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/aio/operations/_data_collection_endpoints_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload import urllib.parse @@ -19,15 +20,13 @@ 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 ...operations._data_collection_endpoints_operations import ( build_create_request, build_delete_request, @@ -37,6 +36,10 @@ build_update_request, ) +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -59,6 +62,7 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list_by_resource_group( @@ -71,7 +75,6 @@ def list_by_resource_group( :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either DataCollectionEndpointResource or the result of cls(response) :rtype: @@ -81,10 +84,10 @@ def list_by_resource_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-06-01")) cls: ClsType[_models.DataCollectionEndpointResourceListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -95,16 +98,14 @@ 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_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -115,14 +116,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("DataCollectionEndpointResourceListResult", pipeline_response) @@ -132,11 +132,11 @@ async def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -149,17 +149,12 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionEndpoints" - } - @distributed_trace def list_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.DataCollectionEndpointResource"]: """Lists all data collection endpoints in the specified subscription. Lists all data collection endpoints in the specified subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either DataCollectionEndpointResource or the result of cls(response) :rtype: @@ -169,10 +164,10 @@ def list_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.DataColl _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-06-01")) cls: ClsType[_models.DataCollectionEndpointResourceListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -183,15 +178,13 @@ def list_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.DataColl def prepare_request(next_link=None): if not next_link: - request = build_list_by_subscription_request( + _request = build_list_by_subscription_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_subscription.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -202,14 +195,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("DataCollectionEndpointResourceListResult", pipeline_response) @@ -219,11 +211,11 @@ async def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -236,10 +228,6 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_by_subscription.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/dataCollectionEndpoints" - } - @distributed_trace_async async def get( self, resource_group_name: str, data_collection_endpoint_name: str, **kwargs: Any @@ -254,12 +242,11 @@ async def get( :param data_collection_endpoint_name: The name of the data collection endpoint. The name is case insensitive. Required. :type data_collection_endpoint_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: DataCollectionEndpointResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_06_01.models.DataCollectionEndpointResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -270,24 +257,22 @@ async def get( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-06-01")) cls: ClsType[_models.DataCollectionEndpointResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, data_collection_endpoint_name=data_collection_endpoint_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -297,16 +282,12 @@ async def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponseCommonV2, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("DataCollectionEndpointResource", pipeline_response) + deserialized = self._deserialize("DataCollectionEndpointResource", 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.Insights/dataCollectionEndpoints/{dataCollectionEndpointName}" - } + return deserialized # type: ignore @overload async def create( @@ -333,7 +314,6 @@ async def create( :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: DataCollectionEndpointResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_06_01.models.DataCollectionEndpointResource :raises ~azure.core.exceptions.HttpResponseError: @@ -344,7 +324,7 @@ async def create( self, resource_group_name: str, data_collection_endpoint_name: str, - body: Optional[IO] = None, + body: Optional[IO[bytes]] = None, *, content_type: str = "application/json", **kwargs: Any @@ -360,11 +340,10 @@ async def create( case insensitive. Required. :type data_collection_endpoint_name: str :param body: The payload. Default value is None. - :type body: IO + :type body: 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: DataCollectionEndpointResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_06_01.models.DataCollectionEndpointResource :raises ~azure.core.exceptions.HttpResponseError: @@ -375,7 +354,7 @@ async def create( self, resource_group_name: str, data_collection_endpoint_name: str, - body: Optional[Union[_models.DataCollectionEndpointResource, IO]] = None, + body: Optional[Union[_models.DataCollectionEndpointResource, IO[bytes]]] = None, **kwargs: Any ) -> _models.DataCollectionEndpointResource: """Creates or updates a data collection endpoint. @@ -388,18 +367,14 @@ async def create( :param data_collection_endpoint_name: The name of the data collection endpoint. The name is case insensitive. Required. :type data_collection_endpoint_name: str - :param body: The payload. Is either a DataCollectionEndpointResource type or a IO type. Default - value is None. - :type body: ~azure.mgmt.monitor.v2022_06_01.models.DataCollectionEndpointResource or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + :param body: The payload. Is either a DataCollectionEndpointResource type or a IO[bytes] type. Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response + :type body: ~azure.mgmt.monitor.v2022_06_01.models.DataCollectionEndpointResource or IO[bytes] :return: DataCollectionEndpointResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_06_01.models.DataCollectionEndpointResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -410,14 +385,14 @@ async def create( _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", "2022-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-06-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.DataCollectionEndpointResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(body, (IO, bytes)): + if isinstance(body, (IOBase, bytes)): _content = body else: if body is not None: @@ -425,7 +400,7 @@ async def create( else: _json = None - request = build_create_request( + _request = build_create_request( resource_group_name=resource_group_name, data_collection_endpoint_name=data_collection_endpoint_name, subscription_id=self._config.subscription_id, @@ -433,16 +408,14 @@ async def create( content_type=content_type, json=_json, content=_content, - template_url=self.create.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -452,21 +425,13 @@ async def create( error = self._deserialize.failsafe_deserialize(_models.ErrorResponseCommonV2, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if response.status_code == 200: - deserialized = self._deserialize("DataCollectionEndpointResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("DataCollectionEndpointResource", pipeline_response) + deserialized = self._deserialize("DataCollectionEndpointResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionEndpoints/{dataCollectionEndpointName}" - } - @overload async def update( self, @@ -492,7 +457,6 @@ async def update( :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: DataCollectionEndpointResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_06_01.models.DataCollectionEndpointResource :raises ~azure.core.exceptions.HttpResponseError: @@ -503,7 +467,7 @@ async def update( self, resource_group_name: str, data_collection_endpoint_name: str, - body: Optional[IO] = None, + body: Optional[IO[bytes]] = None, *, content_type: str = "application/json", **kwargs: Any @@ -519,11 +483,10 @@ async def update( case insensitive. Required. :type data_collection_endpoint_name: str :param body: The payload. Default value is None. - :type body: IO + :type body: 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: DataCollectionEndpointResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_06_01.models.DataCollectionEndpointResource :raises ~azure.core.exceptions.HttpResponseError: @@ -534,7 +497,7 @@ async def update( self, resource_group_name: str, data_collection_endpoint_name: str, - body: Optional[Union[_models.ResourceForUpdate, IO]] = None, + body: Optional[Union[_models.ResourceForUpdate, IO[bytes]]] = None, **kwargs: Any ) -> _models.DataCollectionEndpointResource: """Updates part of a data collection endpoint. @@ -547,18 +510,14 @@ async def update( :param data_collection_endpoint_name: The name of the data collection endpoint. The name is case insensitive. Required. :type data_collection_endpoint_name: str - :param body: The payload. Is either a ResourceForUpdate type or a IO type. Default value is - None. - :type body: ~azure.mgmt.monitor.v2022_06_01.models.ResourceForUpdate 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 + :param body: The payload. Is either a ResourceForUpdate type or a IO[bytes] type. Default value + is None. + :type body: ~azure.mgmt.monitor.v2022_06_01.models.ResourceForUpdate or IO[bytes] :return: DataCollectionEndpointResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_06_01.models.DataCollectionEndpointResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -569,14 +528,14 @@ async def update( _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", "2022-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-06-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.DataCollectionEndpointResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(body, (IO, bytes)): + if isinstance(body, (IOBase, bytes)): _content = body else: if body is not None: @@ -584,7 +543,7 @@ async def update( else: _json = None - request = build_update_request( + _request = build_update_request( resource_group_name=resource_group_name, data_collection_endpoint_name=data_collection_endpoint_name, subscription_id=self._config.subscription_id, @@ -592,16 +551,14 @@ async def update( 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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -611,21 +568,15 @@ async def update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponseCommonV2, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("DataCollectionEndpointResource", pipeline_response) + deserialized = self._deserialize("DataCollectionEndpointResource", 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.Insights/dataCollectionEndpoints/{dataCollectionEndpointName}" - } + return deserialized # type: ignore @distributed_trace_async - async def delete( # pylint: disable=inconsistent-return-statements - self, resource_group_name: str, data_collection_endpoint_name: str, **kwargs: Any - ) -> None: + async def delete(self, resource_group_name: str, data_collection_endpoint_name: str, **kwargs: Any) -> None: """Deletes a data collection endpoint. Deletes a data collection endpoint. @@ -636,12 +587,11 @@ async def delete( # pylint: disable=inconsistent-return-statements :param data_collection_endpoint_name: The name of the data collection endpoint. The name is case insensitive. Required. :type data_collection_endpoint_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, @@ -652,24 +602,22 @@ async def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-06-01")) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, data_collection_endpoint_name=data_collection_endpoint_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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -680,8 +628,4 @@ async def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionEndpoints/{dataCollectionEndpointName}" - } + return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/aio/operations/_data_collection_rule_associations_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/aio/operations/_data_collection_rule_associations_operations.py index 985bffa7cbb0..44bf903364f3 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/aio/operations/_data_collection_rule_associations_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/aio/operations/_data_collection_rule_associations_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload import urllib.parse @@ -19,15 +20,13 @@ 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 ...operations._data_collection_rule_associations_operations import ( build_create_request, build_delete_request, @@ -37,6 +36,10 @@ build_list_by_rule_request, ) +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -59,18 +62,19 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list_by_resource( self, resource_uri: str, **kwargs: Any ) -> AsyncIterable["_models.DataCollectionRuleAssociationProxyOnlyResource"]: + # pylint: disable=line-too-long """Lists associations for the specified resource. Lists associations for the specified resource. :param resource_uri: The identifier of the resource. Required. :type resource_uri: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either DataCollectionRuleAssociationProxyOnlyResource or the result of cls(response) :rtype: @@ -80,10 +84,10 @@ def list_by_resource( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-06-01")) cls: ClsType[_models.DataCollectionRuleAssociationProxyOnlyResourceListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -94,15 +98,13 @@ def list_by_resource( def prepare_request(next_link=None): if not next_link: - request = build_list_by_resource_request( + _request = build_list_by_resource_request( resource_uri=resource_uri, api_version=api_version, - template_url=self.list_by_resource.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -113,14 +115,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize( @@ -132,11 +133,11 @@ async def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -149,12 +150,11 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_by_resource.metadata = {"url": "/{resourceUri}/providers/Microsoft.Insights/dataCollectionRuleAssociations"} - @distributed_trace def list_by_rule( self, resource_group_name: str, data_collection_rule_name: str, **kwargs: Any ) -> AsyncIterable["_models.DataCollectionRuleAssociationProxyOnlyResource"]: + # pylint: disable=line-too-long """Lists associations for the specified data collection rule. Lists associations for the specified data collection rule. @@ -165,7 +165,6 @@ def list_by_rule( :param data_collection_rule_name: The name of the data collection rule. The name is case insensitive. Required. :type data_collection_rule_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either DataCollectionRuleAssociationProxyOnlyResource or the result of cls(response) :rtype: @@ -175,10 +174,10 @@ def list_by_rule( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-06-01")) cls: ClsType[_models.DataCollectionRuleAssociationProxyOnlyResourceListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -189,17 +188,15 @@ def list_by_rule( def prepare_request(next_link=None): if not next_link: - request = build_list_by_rule_request( + _request = build_list_by_rule_request( resource_group_name=resource_group_name, data_collection_rule_name=data_collection_rule_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_rule.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -210,14 +207,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize( @@ -229,11 +225,11 @@ async def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -246,14 +242,11 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_by_rule.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionRules/{dataCollectionRuleName}/associations" - } - @distributed_trace def list_by_data_collection_endpoint( self, resource_group_name: str, data_collection_endpoint_name: str, **kwargs: Any ) -> AsyncIterable["_models.DataCollectionRuleAssociationProxyOnlyResource"]: + # pylint: disable=line-too-long """Lists associations for the specified data collection endpoint. Lists associations for the specified data collection endpoint. @@ -264,7 +257,6 @@ def list_by_data_collection_endpoint( :param data_collection_endpoint_name: The name of the data collection endpoint. The name is case insensitive. Required. :type data_collection_endpoint_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either DataCollectionRuleAssociationProxyOnlyResource or the result of cls(response) :rtype: @@ -274,10 +266,10 @@ def list_by_data_collection_endpoint( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-06-01")) cls: ClsType[_models.DataCollectionRuleAssociationProxyOnlyResourceListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -288,17 +280,15 @@ def list_by_data_collection_endpoint( def prepare_request(next_link=None): if not next_link: - request = build_list_by_data_collection_endpoint_request( + _request = build_list_by_data_collection_endpoint_request( resource_group_name=resource_group_name, data_collection_endpoint_name=data_collection_endpoint_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_data_collection_endpoint.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -309,14 +299,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize( @@ -328,11 +317,11 @@ async def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -345,10 +334,6 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_by_data_collection_endpoint.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionEndpoints/{dataCollectionEndpointName}/associations" - } - @distributed_trace_async async def get( self, resource_uri: str, association_name: str, **kwargs: Any @@ -361,12 +346,11 @@ async def get( :type resource_uri: str :param association_name: The name of the association. The name is case insensitive. Required. :type association_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: DataCollectionRuleAssociationProxyOnlyResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_06_01.models.DataCollectionRuleAssociationProxyOnlyResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -377,23 +361,21 @@ async def get( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-06-01")) cls: ClsType[_models.DataCollectionRuleAssociationProxyOnlyResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_uri=resource_uri, association_name=association_name, api_version=api_version, - template_url=self.get.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -403,16 +385,14 @@ async def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponseCommonV2, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("DataCollectionRuleAssociationProxyOnlyResource", pipeline_response) + deserialized = self._deserialize( + "DataCollectionRuleAssociationProxyOnlyResource", pipeline_response.http_response + ) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get.metadata = { - "url": "/{resourceUri}/providers/Microsoft.Insights/dataCollectionRuleAssociations/{associationName}" - } + return deserialized # type: ignore @overload async def create( @@ -438,7 +418,6 @@ async def create( :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: DataCollectionRuleAssociationProxyOnlyResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_06_01.models.DataCollectionRuleAssociationProxyOnlyResource :raises ~azure.core.exceptions.HttpResponseError: @@ -449,7 +428,7 @@ async def create( self, resource_uri: str, association_name: str, - body: Optional[IO] = None, + body: Optional[IO[bytes]] = None, *, content_type: str = "application/json", **kwargs: Any @@ -463,11 +442,10 @@ async def create( :param association_name: The name of the association. The name is case insensitive. Required. :type association_name: str :param body: The payload. Default value is None. - :type body: IO + :type body: 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: DataCollectionRuleAssociationProxyOnlyResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_06_01.models.DataCollectionRuleAssociationProxyOnlyResource :raises ~azure.core.exceptions.HttpResponseError: @@ -478,7 +456,7 @@ async def create( self, resource_uri: str, association_name: str, - body: Optional[Union[_models.DataCollectionRuleAssociationProxyOnlyResource, IO]] = None, + body: Optional[Union[_models.DataCollectionRuleAssociationProxyOnlyResource, IO[bytes]]] = None, **kwargs: Any ) -> _models.DataCollectionRuleAssociationProxyOnlyResource: """Creates or updates an association. @@ -490,18 +468,15 @@ async def create( :param association_name: The name of the association. The name is case insensitive. Required. :type association_name: str :param body: The payload. Is either a DataCollectionRuleAssociationProxyOnlyResource type or a - IO type. Default value is None. + IO[bytes] type. Default value is None. :type body: - ~azure.mgmt.monitor.v2022_06_01.models.DataCollectionRuleAssociationProxyOnlyResource 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 + ~azure.mgmt.monitor.v2022_06_01.models.DataCollectionRuleAssociationProxyOnlyResource or + IO[bytes] :return: DataCollectionRuleAssociationProxyOnlyResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_06_01.models.DataCollectionRuleAssociationProxyOnlyResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -512,14 +487,14 @@ async def create( _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", "2022-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-06-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.DataCollectionRuleAssociationProxyOnlyResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(body, (IO, bytes)): + if isinstance(body, (IOBase, bytes)): _content = body else: if body is not None: @@ -527,23 +502,21 @@ async def create( else: _json = None - request = build_create_request( + _request = build_create_request( resource_uri=resource_uri, association_name=association_name, api_version=api_version, content_type=content_type, json=_json, content=_content, - template_url=self.create.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -553,25 +526,17 @@ async def create( error = self._deserialize.failsafe_deserialize(_models.ErrorResponseCommonV2, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if response.status_code == 200: - deserialized = self._deserialize("DataCollectionRuleAssociationProxyOnlyResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("DataCollectionRuleAssociationProxyOnlyResource", pipeline_response) + deserialized = self._deserialize( + "DataCollectionRuleAssociationProxyOnlyResource", pipeline_response.http_response + ) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create.metadata = { - "url": "/{resourceUri}/providers/Microsoft.Insights/dataCollectionRuleAssociations/{associationName}" - } - @distributed_trace_async - async def delete( # pylint: disable=inconsistent-return-statements - self, resource_uri: str, association_name: str, **kwargs: Any - ) -> None: + async def delete(self, resource_uri: str, association_name: str, **kwargs: Any) -> None: """Deletes an association. Deletes an association. @@ -580,12 +545,11 @@ async def delete( # pylint: disable=inconsistent-return-statements :type resource_uri: str :param association_name: The name of the association. The name is case insensitive. Required. :type association_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, @@ -596,23 +560,21 @@ async def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-06-01")) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_uri=resource_uri, association_name=association_name, api_version=api_version, - template_url=self.delete.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -623,8 +585,4 @@ async def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/{resourceUri}/providers/Microsoft.Insights/dataCollectionRuleAssociations/{associationName}" - } + return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/aio/operations/_data_collection_rules_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/aio/operations/_data_collection_rules_operations.py index 3e861dea15bc..04e23fb51d9c 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/aio/operations/_data_collection_rules_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/aio/operations/_data_collection_rules_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload import urllib.parse @@ -19,15 +20,13 @@ 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 ...operations._data_collection_rules_operations import ( build_create_request, build_delete_request, @@ -37,6 +36,10 @@ build_update_request, ) +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -59,6 +62,7 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list_by_resource_group( @@ -71,7 +75,6 @@ def list_by_resource_group( :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either DataCollectionRuleResource or the result of cls(response) :rtype: @@ -81,10 +84,10 @@ def list_by_resource_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-06-01")) cls: ClsType[_models.DataCollectionRuleResourceListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -95,16 +98,14 @@ 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_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -115,14 +116,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("DataCollectionRuleResourceListResult", pipeline_response) @@ -132,11 +132,11 @@ async def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -149,17 +149,12 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionRules" - } - @distributed_trace def list_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.DataCollectionRuleResource"]: """Lists all data collection rules in the specified subscription. Lists all data collection rules in the specified subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either DataCollectionRuleResource or the result of cls(response) :rtype: @@ -169,10 +164,10 @@ def list_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.DataColl _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-06-01")) cls: ClsType[_models.DataCollectionRuleResourceListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -183,15 +178,13 @@ def list_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.DataColl def prepare_request(next_link=None): if not next_link: - request = build_list_by_subscription_request( + _request = build_list_by_subscription_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_subscription.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -202,14 +195,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("DataCollectionRuleResourceListResult", pipeline_response) @@ -219,11 +211,11 @@ async def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -236,10 +228,6 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_by_subscription.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/dataCollectionRules" - } - @distributed_trace_async async def get( self, resource_group_name: str, data_collection_rule_name: str, **kwargs: Any @@ -254,12 +242,11 @@ async def get( :param data_collection_rule_name: The name of the data collection rule. The name is case insensitive. Required. :type data_collection_rule_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: DataCollectionRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_06_01.models.DataCollectionRuleResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -270,24 +257,22 @@ async def get( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-06-01")) cls: ClsType[_models.DataCollectionRuleResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, data_collection_rule_name=data_collection_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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -297,16 +282,12 @@ async def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponseCommonV2, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("DataCollectionRuleResource", pipeline_response) + deserialized = self._deserialize("DataCollectionRuleResource", 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.Insights/dataCollectionRules/{dataCollectionRuleName}" - } + return deserialized # type: ignore @overload async def create( @@ -333,7 +314,6 @@ async def create( :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: DataCollectionRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_06_01.models.DataCollectionRuleResource :raises ~azure.core.exceptions.HttpResponseError: @@ -344,7 +324,7 @@ async def create( self, resource_group_name: str, data_collection_rule_name: str, - body: Optional[IO] = None, + body: Optional[IO[bytes]] = None, *, content_type: str = "application/json", **kwargs: Any @@ -360,11 +340,10 @@ async def create( insensitive. Required. :type data_collection_rule_name: str :param body: The payload. Default value is None. - :type body: IO + :type body: 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: DataCollectionRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_06_01.models.DataCollectionRuleResource :raises ~azure.core.exceptions.HttpResponseError: @@ -375,7 +354,7 @@ async def create( self, resource_group_name: str, data_collection_rule_name: str, - body: Optional[Union[_models.DataCollectionRuleResource, IO]] = None, + body: Optional[Union[_models.DataCollectionRuleResource, IO[bytes]]] = None, **kwargs: Any ) -> _models.DataCollectionRuleResource: """Creates or updates a data collection rule. @@ -388,18 +367,14 @@ async def create( :param data_collection_rule_name: The name of the data collection rule. The name is case insensitive. Required. :type data_collection_rule_name: str - :param body: The payload. Is either a DataCollectionRuleResource type or a IO type. Default - value is None. - :type body: ~azure.mgmt.monitor.v2022_06_01.models.DataCollectionRuleResource or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + :param body: The payload. Is either a DataCollectionRuleResource type or a IO[bytes] type. Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response + :type body: ~azure.mgmt.monitor.v2022_06_01.models.DataCollectionRuleResource or IO[bytes] :return: DataCollectionRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_06_01.models.DataCollectionRuleResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -410,14 +385,14 @@ async def create( _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", "2022-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-06-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.DataCollectionRuleResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(body, (IO, bytes)): + if isinstance(body, (IOBase, bytes)): _content = body else: if body is not None: @@ -425,7 +400,7 @@ async def create( else: _json = None - request = build_create_request( + _request = build_create_request( resource_group_name=resource_group_name, data_collection_rule_name=data_collection_rule_name, subscription_id=self._config.subscription_id, @@ -433,16 +408,14 @@ async def create( content_type=content_type, json=_json, content=_content, - template_url=self.create.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -452,21 +425,13 @@ async def create( error = self._deserialize.failsafe_deserialize(_models.ErrorResponseCommonV2, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if response.status_code == 200: - deserialized = self._deserialize("DataCollectionRuleResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("DataCollectionRuleResource", pipeline_response) + deserialized = self._deserialize("DataCollectionRuleResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionRules/{dataCollectionRuleName}" - } - @overload async def update( self, @@ -492,7 +457,6 @@ async def update( :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: DataCollectionRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_06_01.models.DataCollectionRuleResource :raises ~azure.core.exceptions.HttpResponseError: @@ -503,7 +467,7 @@ async def update( self, resource_group_name: str, data_collection_rule_name: str, - body: Optional[IO] = None, + body: Optional[IO[bytes]] = None, *, content_type: str = "application/json", **kwargs: Any @@ -519,11 +483,10 @@ async def update( insensitive. Required. :type data_collection_rule_name: str :param body: The payload. Default value is None. - :type body: IO + :type body: 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: DataCollectionRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_06_01.models.DataCollectionRuleResource :raises ~azure.core.exceptions.HttpResponseError: @@ -534,7 +497,7 @@ async def update( self, resource_group_name: str, data_collection_rule_name: str, - body: Optional[Union[_models.ResourceForUpdate, IO]] = None, + body: Optional[Union[_models.ResourceForUpdate, IO[bytes]]] = None, **kwargs: Any ) -> _models.DataCollectionRuleResource: """Updates part of a data collection rule. @@ -547,18 +510,14 @@ async def update( :param data_collection_rule_name: The name of the data collection rule. The name is case insensitive. Required. :type data_collection_rule_name: str - :param body: The payload. Is either a ResourceForUpdate type or a IO type. Default value is - None. - :type body: ~azure.mgmt.monitor.v2022_06_01.models.ResourceForUpdate 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 + :param body: The payload. Is either a ResourceForUpdate type or a IO[bytes] type. Default value + is None. + :type body: ~azure.mgmt.monitor.v2022_06_01.models.ResourceForUpdate or IO[bytes] :return: DataCollectionRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_06_01.models.DataCollectionRuleResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -569,14 +528,14 @@ async def update( _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", "2022-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-06-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.DataCollectionRuleResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(body, (IO, bytes)): + if isinstance(body, (IOBase, bytes)): _content = body else: if body is not None: @@ -584,7 +543,7 @@ async def update( else: _json = None - request = build_update_request( + _request = build_update_request( resource_group_name=resource_group_name, data_collection_rule_name=data_collection_rule_name, subscription_id=self._config.subscription_id, @@ -592,16 +551,14 @@ async def update( 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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -611,21 +568,15 @@ async def update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponseCommonV2, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("DataCollectionRuleResource", pipeline_response) + deserialized = self._deserialize("DataCollectionRuleResource", 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.Insights/dataCollectionRules/{dataCollectionRuleName}" - } + return deserialized # type: ignore @distributed_trace_async - async def delete( # pylint: disable=inconsistent-return-statements - self, resource_group_name: str, data_collection_rule_name: str, **kwargs: Any - ) -> None: + async def delete(self, resource_group_name: str, data_collection_rule_name: str, **kwargs: Any) -> None: """Deletes a data collection rule. Deletes a data collection rule. @@ -636,12 +587,11 @@ async def delete( # pylint: disable=inconsistent-return-statements :param data_collection_rule_name: The name of the data collection rule. The name is case insensitive. Required. :type data_collection_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, @@ -652,24 +602,22 @@ async def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-06-01")) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, data_collection_rule_name=data_collection_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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -680,8 +628,4 @@ async def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionRules/{dataCollectionRuleName}" - } + return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/models/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/models/__init__.py index 10260a1c0f48..1a5c4f47f77d 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/models/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/models/__init__.py @@ -5,125 +5,136 @@ # 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 ActionDetail -from ._models_py3 import ActionGroupList -from ._models_py3 import ActionGroupPatchBody -from ._models_py3 import ActionGroupResource -from ._models_py3 import ArmRoleReceiver -from ._models_py3 import AutomationRunbookReceiver -from ._models_py3 import AzureAppPushReceiver -from ._models_py3 import AzureFunctionReceiver -from ._models_py3 import AzureMonitorMetricsDestination -from ._models_py3 import AzureResource -from ._models_py3 import ColumnDefinition -from ._models_py3 import ConfigurationAccessEndpointSpec -from ._models_py3 import Context -from ._models_py3 import DataCollectionEndpoint -from ._models_py3 import DataCollectionEndpointConfigurationAccess -from ._models_py3 import DataCollectionEndpointFailoverConfiguration -from ._models_py3 import DataCollectionEndpointLogsIngestion -from ._models_py3 import DataCollectionEndpointMetadata -from ._models_py3 import DataCollectionEndpointMetricsIngestion -from ._models_py3 import DataCollectionEndpointNetworkAcls -from ._models_py3 import DataCollectionEndpointResource -from ._models_py3 import DataCollectionEndpointResourceIdentity -from ._models_py3 import DataCollectionEndpointResourceListResult -from ._models_py3 import DataCollectionEndpointResourceProperties -from ._models_py3 import DataCollectionEndpointResourceSystemData -from ._models_py3 import DataCollectionRule -from ._models_py3 import DataCollectionRuleAssociation -from ._models_py3 import DataCollectionRuleAssociationMetadata -from ._models_py3 import DataCollectionRuleAssociationProxyOnlyResource -from ._models_py3 import DataCollectionRuleAssociationProxyOnlyResourceListResult -from ._models_py3 import DataCollectionRuleAssociationProxyOnlyResourceProperties -from ._models_py3 import DataCollectionRuleAssociationProxyOnlyResourceSystemData -from ._models_py3 import DataCollectionRuleDataSources -from ._models_py3 import DataCollectionRuleDestinations -from ._models_py3 import DataCollectionRuleMetadata -from ._models_py3 import DataCollectionRuleResource -from ._models_py3 import DataCollectionRuleResourceIdentity -from ._models_py3 import DataCollectionRuleResourceListResult -from ._models_py3 import DataCollectionRuleResourceProperties -from ._models_py3 import DataCollectionRuleResourceSystemData -from ._models_py3 import DataFlow -from ._models_py3 import DataImportSources -from ._models_py3 import DataImportSourcesEventHub -from ._models_py3 import DataSourcesSpec -from ._models_py3 import DataSourcesSpecDataImports -from ._models_py3 import DestinationsSpec -from ._models_py3 import DestinationsSpecAzureMonitorMetrics -from ._models_py3 import EmailReceiver -from ._models_py3 import EnableRequest -from ._models_py3 import ErrorAdditionalInfo -from ._models_py3 import ErrorDetail -from ._models_py3 import ErrorResponse -from ._models_py3 import ErrorResponseCommonV2 -from ._models_py3 import EventHubDataSource -from ._models_py3 import EventHubDestination -from ._models_py3 import EventHubDirectDestination -from ._models_py3 import EventHubReceiver -from ._models_py3 import ExtensionDataSource -from ._models_py3 import FailoverConfigurationSpec -from ._models_py3 import IisLogsDataSource -from ._models_py3 import ItsmReceiver -from ._models_py3 import LocationSpec -from ._models_py3 import LogAnalyticsDestination -from ._models_py3 import LogFileSettings -from ._models_py3 import LogFileSettingsText -from ._models_py3 import LogFileTextSettings -from ._models_py3 import LogFilesDataSource -from ._models_py3 import LogFilesDataSourceSettings -from ._models_py3 import LogicAppReceiver -from ._models_py3 import LogsIngestionEndpointSpec -from ._models_py3 import ManagedServiceIdentity -from ._models_py3 import Metadata -from ._models_py3 import MetricsIngestionEndpointSpec -from ._models_py3 import MonitoringAccountDestination -from ._models_py3 import NetworkRuleSet -from ._models_py3 import NotificationRequestBody -from ._models_py3 import PerfCounterDataSource -from ._models_py3 import PlatformTelemetryDataSource -from ._models_py3 import PrivateLinkScopedResource -from ._models_py3 import PrometheusForwarderDataSource -from ._models_py3 import ResourceForUpdate -from ._models_py3 import ResourceForUpdateIdentity -from ._models_py3 import SmsReceiver -from ._models_py3 import StorageBlobDestination -from ._models_py3 import StorageTableDestination -from ._models_py3 import StreamDeclaration -from ._models_py3 import SyslogDataSource -from ._models_py3 import SystemData -from ._models_py3 import TestNotificationDetailsResponse -from ._models_py3 import UserAssignedIdentity -from ._models_py3 import VoiceReceiver -from ._models_py3 import WebhookReceiver -from ._models_py3 import WindowsEventLogDataSource -from ._models_py3 import WindowsFirewallLogsDataSource +from typing import TYPE_CHECKING -from ._monitor_management_client_enums import CreatedByType -from ._monitor_management_client_enums import KnownColumnDefinitionType -from ._monitor_management_client_enums import KnownDataCollectionEndpointProvisioningState -from ._monitor_management_client_enums import KnownDataCollectionEndpointResourceKind -from ._monitor_management_client_enums import KnownDataCollectionRuleAssociationProvisioningState -from ._monitor_management_client_enums import KnownDataCollectionRuleProvisioningState -from ._monitor_management_client_enums import KnownDataCollectionRuleResourceKind -from ._monitor_management_client_enums import KnownDataFlowStreams -from ._monitor_management_client_enums import KnownExtensionDataSourceStreams -from ._monitor_management_client_enums import KnownLocationSpecProvisioningStatus -from ._monitor_management_client_enums import KnownLogFileTextSettingsRecordStartTimestampFormat -from ._monitor_management_client_enums import KnownLogFilesDataSourceFormat -from ._monitor_management_client_enums import KnownPerfCounterDataSourceStreams -from ._monitor_management_client_enums import KnownPrometheusForwarderDataSourceStreams -from ._monitor_management_client_enums import KnownPublicNetworkAccessOptions -from ._monitor_management_client_enums import KnownSyslogDataSourceFacilityNames -from ._monitor_management_client_enums import KnownSyslogDataSourceLogLevels -from ._monitor_management_client_enums import KnownSyslogDataSourceStreams -from ._monitor_management_client_enums import KnownWindowsEventLogDataSourceStreams -from ._monitor_management_client_enums import ManagedServiceIdentityType -from ._monitor_management_client_enums import ReceiverStatus +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models_py3 import ( # type: ignore + ActionDetail, + ActionGroupList, + ActionGroupPatchBody, + ActionGroupResource, + ArmRoleReceiver, + AutomationRunbookReceiver, + AzureAppPushReceiver, + AzureFunctionReceiver, + AzureMonitorMetricsDestination, + AzureResource, + ColumnDefinition, + ConfigurationAccessEndpointSpec, + Context, + DataCollectionEndpoint, + DataCollectionEndpointConfigurationAccess, + DataCollectionEndpointFailoverConfiguration, + DataCollectionEndpointLogsIngestion, + DataCollectionEndpointMetadata, + DataCollectionEndpointMetricsIngestion, + DataCollectionEndpointNetworkAcls, + DataCollectionEndpointResource, + DataCollectionEndpointResourceIdentity, + DataCollectionEndpointResourceListResult, + DataCollectionEndpointResourceProperties, + DataCollectionEndpointResourceSystemData, + DataCollectionRule, + DataCollectionRuleAssociation, + DataCollectionRuleAssociationMetadata, + DataCollectionRuleAssociationProxyOnlyResource, + DataCollectionRuleAssociationProxyOnlyResourceListResult, + DataCollectionRuleAssociationProxyOnlyResourceProperties, + DataCollectionRuleAssociationProxyOnlyResourceSystemData, + DataCollectionRuleDataSources, + DataCollectionRuleDestinations, + DataCollectionRuleMetadata, + DataCollectionRuleResource, + DataCollectionRuleResourceIdentity, + DataCollectionRuleResourceListResult, + DataCollectionRuleResourceProperties, + DataCollectionRuleResourceSystemData, + DataFlow, + DataImportSources, + DataImportSourcesEventHub, + DataSourcesSpec, + DataSourcesSpecDataImports, + DestinationsSpec, + DestinationsSpecAzureMonitorMetrics, + EmailReceiver, + EnableRequest, + ErrorAdditionalInfo, + ErrorDetail, + ErrorResponse, + ErrorResponseCommonV2, + EventHubDataSource, + EventHubDestination, + EventHubDirectDestination, + EventHubReceiver, + ExtensionDataSource, + FailoverConfigurationSpec, + IisLogsDataSource, + ItsmReceiver, + LocationSpec, + LogAnalyticsDestination, + LogFileSettings, + LogFileSettingsText, + LogFileTextSettings, + LogFilesDataSource, + LogFilesDataSourceSettings, + LogicAppReceiver, + LogsIngestionEndpointSpec, + ManagedServiceIdentity, + Metadata, + MetricsIngestionEndpointSpec, + MonitoringAccountDestination, + NetworkRuleSet, + NotificationRequestBody, + PerfCounterDataSource, + PlatformTelemetryDataSource, + PrivateLinkScopedResource, + PrometheusForwarderDataSource, + ResourceForUpdate, + ResourceForUpdateIdentity, + SmsReceiver, + StorageBlobDestination, + StorageTableDestination, + StreamDeclaration, + SyslogDataSource, + SystemData, + TestNotificationDetailsResponse, + UserAssignedIdentity, + VoiceReceiver, + WebhookReceiver, + WindowsEventLogDataSource, + WindowsFirewallLogsDataSource, +) + +from ._monitor_management_client_enums import ( # type: ignore + CreatedByType, + KnownColumnDefinitionType, + KnownDataCollectionEndpointProvisioningState, + KnownDataCollectionEndpointResourceKind, + KnownDataCollectionRuleAssociationProvisioningState, + KnownDataCollectionRuleProvisioningState, + KnownDataCollectionRuleResourceKind, + KnownDataFlowStreams, + KnownExtensionDataSourceStreams, + KnownLocationSpecProvisioningStatus, + KnownLogFileTextSettingsRecordStartTimestampFormat, + KnownLogFilesDataSourceFormat, + KnownPerfCounterDataSourceStreams, + KnownPrometheusForwarderDataSourceStreams, + KnownPublicNetworkAccessOptions, + KnownSyslogDataSourceFacilityNames, + KnownSyslogDataSourceLogLevels, + KnownSyslogDataSourceStreams, + KnownWindowsEventLogDataSourceStreams, + ManagedServiceIdentityType, + ReceiverStatus, +) from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ @@ -243,5 +254,5 @@ "ManagedServiceIdentityType", "ReceiverStatus", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/models/_models_py3.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/models/_models_py3.py index 2b564b89bfb0..5b60d47a8217 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/models/_models_py3.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/models/_models_py3.py @@ -1,5 +1,5 @@ -# coding=utf-8 # 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. @@ -16,10 +16,9 @@ if sys.version_info >= (3, 9): from collections.abc import MutableMapping else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports + from typing import MutableMapping # type: ignore if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from .. import models as _models JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object @@ -149,7 +148,7 @@ class AzureResource(_serialization.Model): 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: Azure resource Id. :vartype id: str @@ -193,12 +192,12 @@ def __init__(self, *, location: str, tags: Optional[Dict[str, str]] = None, **kw self.tags = tags -class ActionGroupResource(AzureResource): # pylint: disable=too-many-instance-attributes +class ActionGroupResource(AzureResource): """An action group 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: Azure resource Id. :vartype id: str @@ -360,7 +359,7 @@ def __init__( class ArmRoleReceiver(_serialization.Model): """An arm role receiver. - 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 name of the arm role receiver. Names must be unique across all receivers within an action group. Required. @@ -401,7 +400,7 @@ def __init__(self, *, name: str, role_id: str, use_common_alert_schema: bool = F class AutomationRunbookReceiver(_serialization.Model): """The Azure Automation Runbook notification receiver. - 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 automation_account_id: The Azure automation account Id which holds this runbook and authenticate to Azure resource. Required. @@ -479,7 +478,7 @@ def __init__( class AzureAppPushReceiver(_serialization.Model): """The Azure mobile App push notification receiver. - 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 name of the Azure mobile app push receiver. Names must be unique across all receivers within an action group. Required. @@ -514,7 +513,7 @@ def __init__(self, *, name: str, email_address: str, **kwargs: Any) -> None: class AzureFunctionReceiver(_serialization.Model): """An azure function receiver. - 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 name of the azure function receiver. Names must be unique across all receivers within an action group. Required. @@ -605,7 +604,7 @@ class ColumnDefinition(_serialization.Model): :ivar name: The name of the column. :vartype name: str :ivar type: The type of the column data. Known values are: "string", "int", "long", "real", - "boolean", "datetime", and "dynamic". + "boolean", "datetime", "dynamic", and "int". :vartype type: str or ~azure.mgmt.monitor.v2022_06_01.models.KnownColumnDefinitionType """ @@ -625,7 +624,7 @@ def __init__( :keyword name: The name of the column. :paramtype name: str :keyword type: The type of the column data. Known values are: "string", "int", "long", "real", - "boolean", "datetime", and "dynamic". + "boolean", "datetime", "dynamic", and "int". :paramtype type: str or ~azure.mgmt.monitor.v2022_06_01.models.KnownColumnDefinitionType """ super().__init__(**kwargs) @@ -787,7 +786,7 @@ def __init__( self.metadata = None -class DataCollectionEndpointConfigurationAccess(ConfigurationAccessEndpointSpec): +class DataCollectionEndpointConfigurationAccess(ConfigurationAccessEndpointSpec): # pylint: disable=name-too-long """The endpoint used by clients to access their configuration. Variables are only populated by the server, and will be ignored when sending a request. @@ -796,18 +795,6 @@ class DataCollectionEndpointConfigurationAccess(ConfigurationAccessEndpointSpec) :vartype endpoint: str """ - _validation = { - "endpoint": {"readonly": True}, - } - - _attribute_map = { - "endpoint": {"key": "endpoint", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - class FailoverConfigurationSpec(_serialization.Model): """FailoverConfigurationSpec. @@ -841,7 +828,7 @@ def __init__( self.locations = locations -class DataCollectionEndpointFailoverConfiguration(FailoverConfigurationSpec): +class DataCollectionEndpointFailoverConfiguration(FailoverConfigurationSpec): # pylint: disable=name-too-long """Failover configuration on this endpoint. This property is READ-ONLY. :ivar active_location: Active location where data flow will occur. @@ -850,26 +837,6 @@ class DataCollectionEndpointFailoverConfiguration(FailoverConfigurationSpec): :vartype locations: list[~azure.mgmt.monitor.v2022_06_01.models.LocationSpec] """ - _attribute_map = { - "active_location": {"key": "activeLocation", "type": "str"}, - "locations": {"key": "locations", "type": "[LocationSpec]"}, - } - - def __init__( - self, - *, - active_location: Optional[str] = None, - locations: Optional[List["_models.LocationSpec"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword active_location: Active location where data flow will occur. - :paramtype active_location: str - :keyword locations: Locations that are configured for failover. - :paramtype locations: list[~azure.mgmt.monitor.v2022_06_01.models.LocationSpec] - """ - super().__init__(active_location=active_location, locations=locations, **kwargs) - class LogsIngestionEndpointSpec(_serialization.Model): """Definition of the endpoint used for ingesting logs. @@ -903,18 +870,6 @@ class DataCollectionEndpointLogsIngestion(LogsIngestionEndpointSpec): :vartype endpoint: str """ - _validation = { - "endpoint": {"readonly": True}, - } - - _attribute_map = { - "endpoint": {"key": "endpoint", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - class Metadata(_serialization.Model): """Metadata about the resource. @@ -957,20 +912,6 @@ class DataCollectionEndpointMetadata(Metadata): :vartype provisioned_by_resource_id: str """ - _validation = { - "provisioned_by": {"readonly": True}, - "provisioned_by_resource_id": {"readonly": True}, - } - - _attribute_map = { - "provisioned_by": {"key": "provisionedBy", "type": "str"}, - "provisioned_by_resource_id": {"key": "provisionedByResourceId", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - class MetricsIngestionEndpointSpec(_serialization.Model): """Definition of the endpoint used for ingesting metrics. @@ -1004,18 +945,6 @@ class DataCollectionEndpointMetricsIngestion(MetricsIngestionEndpointSpec): :vartype endpoint: str """ - _validation = { - "endpoint": {"readonly": True}, - } - - _attribute_map = { - "endpoint": {"key": "endpoint", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - class NetworkRuleSet(_serialization.Model): """Definition of the network rules. @@ -1058,32 +987,13 @@ class DataCollectionEndpointNetworkAcls(NetworkRuleSet): ~azure.mgmt.monitor.v2022_06_01.models.KnownPublicNetworkAccessOptions """ - _attribute_map = { - "public_network_access": {"key": "publicNetworkAccess", "type": "str"}, - } - - def __init__( - self, - *, - public_network_access: Optional[Union[str, "_models.KnownPublicNetworkAccessOptions"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword public_network_access: The configuration to set whether network access from public - internet to the endpoints are allowed. Known values are: "Enabled", "Disabled", and - "SecuredByPerimeter". - :paramtype public_network_access: str or - ~azure.mgmt.monitor.v2022_06_01.models.KnownPublicNetworkAccessOptions - """ - super().__init__(public_network_access=public_network_access, **kwargs) - -class DataCollectionEndpointResource(_serialization.Model): # pylint: disable=too-many-instance-attributes +class DataCollectionEndpointResource(_serialization.Model): """Definition of ARM tracked top level 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 location: The geo-location where the resource lives. Required. :vartype location: str @@ -1253,7 +1163,7 @@ class ManagedServiceIdentity(_serialization.Model): 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 principal_id: The service principal ID of the system assigned identity. This property will only be provided for a system assigned identity. @@ -1267,7 +1177,7 @@ class ManagedServiceIdentity(_serialization.Model): :vartype type: str or ~azure.mgmt.monitor.v2022_06_01.models.ManagedServiceIdentityType :ivar user_assigned_identities: The set of user assigned identities associated with the resource. The userAssignedIdentities dictionary keys will be ARM resource ids in the form: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}. + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}. # pylint: disable=line-too-long The dictionary values can be empty objects ({}) in requests. :vartype user_assigned_identities: dict[str, ~azure.mgmt.monitor.v2022_06_01.models.UserAssignedIdentity] @@ -1300,7 +1210,7 @@ def __init__( :paramtype type: str or ~azure.mgmt.monitor.v2022_06_01.models.ManagedServiceIdentityType :keyword user_assigned_identities: The set of user assigned identities associated with the resource. The userAssignedIdentities dictionary keys will be ARM resource ids in the form: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}. + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}. # pylint: disable=line-too-long The dictionary values can be empty objects ({}) in requests. :paramtype user_assigned_identities: dict[str, ~azure.mgmt.monitor.v2022_06_01.models.UserAssignedIdentity] @@ -1317,7 +1227,7 @@ class DataCollectionEndpointResourceIdentity(ManagedServiceIdentity): 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 principal_id: The service principal ID of the system assigned identity. This property will only be provided for a system assigned identity. @@ -1331,51 +1241,17 @@ class DataCollectionEndpointResourceIdentity(ManagedServiceIdentity): :vartype type: str or ~azure.mgmt.monitor.v2022_06_01.models.ManagedServiceIdentityType :ivar user_assigned_identities: The set of user assigned identities associated with the resource. The userAssignedIdentities dictionary keys will be ARM resource ids in the form: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}. + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}. # pylint: disable=line-too-long The dictionary values can be empty objects ({}) in requests. :vartype user_assigned_identities: dict[str, ~azure.mgmt.monitor.v2022_06_01.models.UserAssignedIdentity] """ - _validation = { - "principal_id": {"readonly": True}, - "tenant_id": {"readonly": True}, - "type": {"required": True}, - } - - _attribute_map = { - "principal_id": {"key": "principalId", "type": "str"}, - "tenant_id": {"key": "tenantId", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "user_assigned_identities": {"key": "userAssignedIdentities", "type": "{UserAssignedIdentity}"}, - } - - def __init__( - self, - *, - type: Union[str, "_models.ManagedServiceIdentityType"], - user_assigned_identities: Optional[Dict[str, "_models.UserAssignedIdentity"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword type: Type of managed service identity (where both SystemAssigned and UserAssigned - types are allowed). Required. Known values are: "None", "SystemAssigned", "UserAssigned", and - "SystemAssigned,UserAssigned". - :paramtype type: str or ~azure.mgmt.monitor.v2022_06_01.models.ManagedServiceIdentityType - :keyword user_assigned_identities: The set of user assigned identities associated with the - resource. The userAssignedIdentities dictionary keys will be ARM resource ids in the form: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}. - The dictionary values can be empty objects ({}) in requests. - :paramtype user_assigned_identities: dict[str, - ~azure.mgmt.monitor.v2022_06_01.models.UserAssignedIdentity] - """ - super().__init__(type=type, user_assigned_identities=user_assigned_identities, **kwargs) - class DataCollectionEndpointResourceListResult(_serialization.Model): """A pageable list of resources. - 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 value: A list of resources. Required. :vartype value: list[~azure.mgmt.monitor.v2022_06_01.models.DataCollectionEndpointResource] @@ -1443,69 +1319,6 @@ class DataCollectionEndpointResourceProperties(DataCollectionEndpoint): :vartype metadata: ~azure.mgmt.monitor.v2022_06_01.models.DataCollectionEndpointMetadata """ - _validation = { - "provisioning_state": {"readonly": True}, - "private_link_scoped_resources": {"readonly": True}, - "failover_configuration": {"readonly": True}, - "metadata": {"readonly": True}, - } - - _attribute_map = { - "description": {"key": "description", "type": "str"}, - "immutable_id": {"key": "immutableId", "type": "str"}, - "configuration_access": {"key": "configurationAccess", "type": "DataCollectionEndpointConfigurationAccess"}, - "logs_ingestion": {"key": "logsIngestion", "type": "DataCollectionEndpointLogsIngestion"}, - "metrics_ingestion": {"key": "metricsIngestion", "type": "DataCollectionEndpointMetricsIngestion"}, - "network_acls": {"key": "networkAcls", "type": "DataCollectionEndpointNetworkAcls"}, - "provisioning_state": {"key": "provisioningState", "type": "str"}, - "private_link_scoped_resources": {"key": "privateLinkScopedResources", "type": "[PrivateLinkScopedResource]"}, - "failover_configuration": { - "key": "failoverConfiguration", - "type": "DataCollectionEndpointFailoverConfiguration", - }, - "metadata": {"key": "metadata", "type": "DataCollectionEndpointMetadata"}, - } - - def __init__( - self, - *, - description: Optional[str] = None, - immutable_id: Optional[str] = None, - configuration_access: Optional["_models.DataCollectionEndpointConfigurationAccess"] = None, - logs_ingestion: Optional["_models.DataCollectionEndpointLogsIngestion"] = None, - metrics_ingestion: Optional["_models.DataCollectionEndpointMetricsIngestion"] = None, - network_acls: Optional["_models.DataCollectionEndpointNetworkAcls"] = None, - **kwargs: Any - ) -> None: - """ - :keyword description: Description of the data collection endpoint. - :paramtype description: str - :keyword immutable_id: The immutable ID of this data collection endpoint resource. This - property is READ-ONLY. - :paramtype immutable_id: str - :keyword configuration_access: The endpoint used by clients to access their configuration. - :paramtype configuration_access: - ~azure.mgmt.monitor.v2022_06_01.models.DataCollectionEndpointConfigurationAccess - :keyword logs_ingestion: The endpoint used by clients to ingest logs. - :paramtype logs_ingestion: - ~azure.mgmt.monitor.v2022_06_01.models.DataCollectionEndpointLogsIngestion - :keyword metrics_ingestion: The endpoint used by clients to ingest metrics. - :paramtype metrics_ingestion: - ~azure.mgmt.monitor.v2022_06_01.models.DataCollectionEndpointMetricsIngestion - :keyword network_acls: Network access control rules for the endpoints. - :paramtype network_acls: - ~azure.mgmt.monitor.v2022_06_01.models.DataCollectionEndpointNetworkAcls - """ - super().__init__( - description=description, - immutable_id=immutable_id, - configuration_access=configuration_access, - logs_ingestion=logs_ingestion, - metrics_ingestion=metrics_ingestion, - network_acls=network_acls, - **kwargs - ) - class SystemData(_serialization.Model): """Metadata pertaining to creation and last modification of the resource. @@ -1590,52 +1403,6 @@ class DataCollectionEndpointResourceSystemData(SystemData): :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: 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.monitor.v2022_06_01.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.monitor.v2022_06_01.models.CreatedByType - :keyword last_modified_at: The timestamp of resource last modification (UTC). - :paramtype last_modified_at: ~datetime.datetime - """ - super().__init__( - created_by=created_by, - created_by_type=created_by_type, - created_at=created_at, - last_modified_by=last_modified_by, - last_modified_by_type=last_modified_by_type, - last_modified_at=last_modified_at, - **kwargs - ) - class DataCollectionRule(_serialization.Model): """Definition of what monitoring data to collect and where that data should be sent. @@ -1799,22 +1566,8 @@ class DataCollectionRuleAssociationMetadata(Metadata): :vartype provisioned_by_resource_id: str """ - _validation = { - "provisioned_by": {"readonly": True}, - "provisioned_by_resource_id": {"readonly": True}, - } - - _attribute_map = { - "provisioned_by": {"key": "provisionedBy", "type": "str"}, - "provisioned_by_resource_id": {"key": "provisionedByResourceId", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - -class DataCollectionRuleAssociationProxyOnlyResource(_serialization.Model): +class DataCollectionRuleAssociationProxyOnlyResource(_serialization.Model): # pylint: disable=name-too-long """Definition of generic ARM proxy resource. Variables are only populated by the server, and will be ignored when sending a request. @@ -1900,10 +1653,10 @@ def __init__( self.metadata = None -class DataCollectionRuleAssociationProxyOnlyResourceListResult(_serialization.Model): +class DataCollectionRuleAssociationProxyOnlyResourceListResult(_serialization.Model): # pylint: disable=name-too-long """A pageable list of resources. - 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 value: A list of resources. Required. :vartype value: @@ -1940,7 +1693,9 @@ def __init__( self.next_link = next_link -class DataCollectionRuleAssociationProxyOnlyResourceProperties(DataCollectionRuleAssociation): +class DataCollectionRuleAssociationProxyOnlyResourceProperties( + DataCollectionRuleAssociation +): # pylint: disable=name-too-long """Resource properties. Variables are only populated by the server, and will be ignored when sending a request. @@ -1961,47 +1716,9 @@ class DataCollectionRuleAssociationProxyOnlyResourceProperties(DataCollectionRul :vartype metadata: ~azure.mgmt.monitor.v2022_06_01.models.DataCollectionRuleAssociationMetadata """ - _validation = { - "provisioning_state": {"readonly": True}, - "metadata": {"readonly": True}, - } - _attribute_map = { - "description": {"key": "description", "type": "str"}, - "data_collection_rule_id": {"key": "dataCollectionRuleId", "type": "str"}, - "data_collection_endpoint_id": {"key": "dataCollectionEndpointId", "type": "str"}, - "provisioning_state": {"key": "provisioningState", "type": "str"}, - "metadata": {"key": "metadata", "type": "DataCollectionRuleAssociationMetadata"}, - } - - def __init__( - self, - *, - description: Optional[str] = None, - data_collection_rule_id: Optional[str] = None, - data_collection_endpoint_id: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword description: Description of the association. - :paramtype description: str - :keyword data_collection_rule_id: The resource ID of the data collection rule that is to be - associated. - :paramtype data_collection_rule_id: str - :keyword data_collection_endpoint_id: The resource ID of the data collection endpoint that is - to be associated. - :paramtype data_collection_endpoint_id: str - """ - super().__init__( - description=description, - data_collection_rule_id=data_collection_rule_id, - data_collection_endpoint_id=data_collection_endpoint_id, - **kwargs - ) - - -class DataCollectionRuleAssociationProxyOnlyResourceSystemData(SystemData): - """Metadata pertaining to creation and last modification of the resource. +class DataCollectionRuleAssociationProxyOnlyResourceSystemData(SystemData): # pylint: disable=name-too-long + """Metadata pertaining to creation and last modification of the resource. :ivar created_by: The identity that created the resource. :vartype created_by: str @@ -2019,52 +1736,6 @@ class DataCollectionRuleAssociationProxyOnlyResourceSystemData(SystemData): :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: 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.monitor.v2022_06_01.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.monitor.v2022_06_01.models.CreatedByType - :keyword last_modified_at: The timestamp of resource last modification (UTC). - :paramtype last_modified_at: ~datetime.datetime - """ - super().__init__( - created_by=created_by, - created_by_type=created_by_type, - created_at=created_at, - last_modified_by=last_modified_by, - last_modified_by_type=last_modified_by_type, - last_modified_at=last_modified_at, - **kwargs - ) - class DataSourcesSpec(_serialization.Model): """Specification of data sources that will be collected. @@ -2196,75 +1867,6 @@ class DataCollectionRuleDataSources(DataSourcesSpec): :vartype data_imports: ~azure.mgmt.monitor.v2022_06_01.models.DataSourcesSpecDataImports """ - _attribute_map = { - "performance_counters": {"key": "performanceCounters", "type": "[PerfCounterDataSource]"}, - "windows_event_logs": {"key": "windowsEventLogs", "type": "[WindowsEventLogDataSource]"}, - "syslog": {"key": "syslog", "type": "[SyslogDataSource]"}, - "extensions": {"key": "extensions", "type": "[ExtensionDataSource]"}, - "log_files": {"key": "logFiles", "type": "[LogFilesDataSource]"}, - "iis_logs": {"key": "iisLogs", "type": "[IisLogsDataSource]"}, - "windows_firewall_logs": {"key": "windowsFirewallLogs", "type": "[WindowsFirewallLogsDataSource]"}, - "prometheus_forwarder": {"key": "prometheusForwarder", "type": "[PrometheusForwarderDataSource]"}, - "platform_telemetry": {"key": "platformTelemetry", "type": "[PlatformTelemetryDataSource]"}, - "data_imports": {"key": "dataImports", "type": "DataSourcesSpecDataImports"}, - } - - def __init__( - self, - *, - performance_counters: Optional[List["_models.PerfCounterDataSource"]] = None, - windows_event_logs: Optional[List["_models.WindowsEventLogDataSource"]] = None, - syslog: Optional[List["_models.SyslogDataSource"]] = None, - extensions: Optional[List["_models.ExtensionDataSource"]] = None, - log_files: Optional[List["_models.LogFilesDataSource"]] = None, - iis_logs: Optional[List["_models.IisLogsDataSource"]] = None, - windows_firewall_logs: Optional[List["_models.WindowsFirewallLogsDataSource"]] = None, - prometheus_forwarder: Optional[List["_models.PrometheusForwarderDataSource"]] = None, - platform_telemetry: Optional[List["_models.PlatformTelemetryDataSource"]] = None, - data_imports: Optional["_models.DataSourcesSpecDataImports"] = None, - **kwargs: Any - ) -> None: - """ - :keyword performance_counters: The list of performance counter data source configurations. - :paramtype performance_counters: - list[~azure.mgmt.monitor.v2022_06_01.models.PerfCounterDataSource] - :keyword windows_event_logs: The list of Windows Event Log data source configurations. - :paramtype windows_event_logs: - list[~azure.mgmt.monitor.v2022_06_01.models.WindowsEventLogDataSource] - :keyword syslog: The list of Syslog data source configurations. - :paramtype syslog: list[~azure.mgmt.monitor.v2022_06_01.models.SyslogDataSource] - :keyword extensions: The list of Azure VM extension data source configurations. - :paramtype extensions: list[~azure.mgmt.monitor.v2022_06_01.models.ExtensionDataSource] - :keyword log_files: The list of Log files source configurations. - :paramtype log_files: list[~azure.mgmt.monitor.v2022_06_01.models.LogFilesDataSource] - :keyword iis_logs: The list of IIS logs source configurations. - :paramtype iis_logs: list[~azure.mgmt.monitor.v2022_06_01.models.IisLogsDataSource] - :keyword windows_firewall_logs: The list of Windows Firewall logs source configurations. - :paramtype windows_firewall_logs: - list[~azure.mgmt.monitor.v2022_06_01.models.WindowsFirewallLogsDataSource] - :keyword prometheus_forwarder: The list of Prometheus forwarder data source configurations. - :paramtype prometheus_forwarder: - list[~azure.mgmt.monitor.v2022_06_01.models.PrometheusForwarderDataSource] - :keyword platform_telemetry: The list of platform telemetry configurations. - :paramtype platform_telemetry: - list[~azure.mgmt.monitor.v2022_06_01.models.PlatformTelemetryDataSource] - :keyword data_imports: Specifications of pull based data sources. - :paramtype data_imports: ~azure.mgmt.monitor.v2022_06_01.models.DataSourcesSpecDataImports - """ - super().__init__( - performance_counters=performance_counters, - windows_event_logs=windows_event_logs, - syslog=syslog, - extensions=extensions, - log_files=log_files, - iis_logs=iis_logs, - windows_firewall_logs=windows_firewall_logs, - prometheus_forwarder=prometheus_forwarder, - platform_telemetry=platform_telemetry, - data_imports=data_imports, - **kwargs - ) - class DestinationsSpec(_serialization.Model): """Specification of destinations that can be used in data flows. @@ -2380,67 +1982,6 @@ class DataCollectionRuleDestinations(DestinationsSpec): :vartype storage_accounts: list[~azure.mgmt.monitor.v2022_06_01.models.StorageBlobDestination] """ - _attribute_map = { - "log_analytics": {"key": "logAnalytics", "type": "[LogAnalyticsDestination]"}, - "monitoring_accounts": {"key": "monitoringAccounts", "type": "[MonitoringAccountDestination]"}, - "azure_monitor_metrics": {"key": "azureMonitorMetrics", "type": "DestinationsSpecAzureMonitorMetrics"}, - "event_hubs": {"key": "eventHubs", "type": "[EventHubDestination]"}, - "event_hubs_direct": {"key": "eventHubsDirect", "type": "[EventHubDirectDestination]"}, - "storage_blobs_direct": {"key": "storageBlobsDirect", "type": "[StorageBlobDestination]"}, - "storage_tables_direct": {"key": "storageTablesDirect", "type": "[StorageTableDestination]"}, - "storage_accounts": {"key": "storageAccounts", "type": "[StorageBlobDestination]"}, - } - - def __init__( - self, - *, - log_analytics: Optional[List["_models.LogAnalyticsDestination"]] = None, - monitoring_accounts: Optional[List["_models.MonitoringAccountDestination"]] = None, - azure_monitor_metrics: Optional["_models.DestinationsSpecAzureMonitorMetrics"] = None, - event_hubs: Optional[List["_models.EventHubDestination"]] = None, - event_hubs_direct: Optional[List["_models.EventHubDirectDestination"]] = None, - storage_blobs_direct: Optional[List["_models.StorageBlobDestination"]] = None, - storage_tables_direct: Optional[List["_models.StorageTableDestination"]] = None, - storage_accounts: Optional[List["_models.StorageBlobDestination"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword log_analytics: List of Log Analytics destinations. - :paramtype log_analytics: list[~azure.mgmt.monitor.v2022_06_01.models.LogAnalyticsDestination] - :keyword monitoring_accounts: List of monitoring account destinations. - :paramtype monitoring_accounts: - list[~azure.mgmt.monitor.v2022_06_01.models.MonitoringAccountDestination] - :keyword azure_monitor_metrics: Azure Monitor Metrics destination. - :paramtype azure_monitor_metrics: - ~azure.mgmt.monitor.v2022_06_01.models.DestinationsSpecAzureMonitorMetrics - :keyword event_hubs: List of Event Hubs destinations. - :paramtype event_hubs: list[~azure.mgmt.monitor.v2022_06_01.models.EventHubDestination] - :keyword event_hubs_direct: List of Event Hubs Direct destinations. - :paramtype event_hubs_direct: - list[~azure.mgmt.monitor.v2022_06_01.models.EventHubDirectDestination] - :keyword storage_blobs_direct: List of Storage Blob Direct destinations. To be used only for - sending data directly to store from the agent. - :paramtype storage_blobs_direct: - list[~azure.mgmt.monitor.v2022_06_01.models.StorageBlobDestination] - :keyword storage_tables_direct: List of Storage Table Direct destinations. - :paramtype storage_tables_direct: - list[~azure.mgmt.monitor.v2022_06_01.models.StorageTableDestination] - :keyword storage_accounts: List of storage accounts destinations. - :paramtype storage_accounts: - list[~azure.mgmt.monitor.v2022_06_01.models.StorageBlobDestination] - """ - super().__init__( - log_analytics=log_analytics, - monitoring_accounts=monitoring_accounts, - azure_monitor_metrics=azure_monitor_metrics, - event_hubs=event_hubs, - event_hubs_direct=event_hubs_direct, - storage_blobs_direct=storage_blobs_direct, - storage_tables_direct=storage_tables_direct, - storage_accounts=storage_accounts, - **kwargs - ) - class DataCollectionRuleMetadata(Metadata): """Metadata about the resource. @@ -2454,27 +1995,13 @@ class DataCollectionRuleMetadata(Metadata): :vartype provisioned_by_resource_id: str """ - _validation = { - "provisioned_by": {"readonly": True}, - "provisioned_by_resource_id": {"readonly": True}, - } - - _attribute_map = { - "provisioned_by": {"key": "provisionedBy", "type": "str"}, - "provisioned_by_resource_id": {"key": "provisionedByResourceId", "type": "str"}, - } - - def __init__(self, **kwargs: Any) -> None: - """ """ - super().__init__(**kwargs) - -class DataCollectionRuleResource(_serialization.Model): # pylint: disable=too-many-instance-attributes +class DataCollectionRuleResource(_serialization.Model): """Definition of ARM tracked top level 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 location: The geo-location where the resource lives. Required. :vartype location: str @@ -2623,7 +2150,7 @@ class DataCollectionRuleResourceIdentity(ManagedServiceIdentity): 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 principal_id: The service principal ID of the system assigned identity. This property will only be provided for a system assigned identity. @@ -2637,51 +2164,17 @@ class DataCollectionRuleResourceIdentity(ManagedServiceIdentity): :vartype type: str or ~azure.mgmt.monitor.v2022_06_01.models.ManagedServiceIdentityType :ivar user_assigned_identities: The set of user assigned identities associated with the resource. The userAssignedIdentities dictionary keys will be ARM resource ids in the form: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}. + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}. # pylint: disable=line-too-long The dictionary values can be empty objects ({}) in requests. :vartype user_assigned_identities: dict[str, ~azure.mgmt.monitor.v2022_06_01.models.UserAssignedIdentity] """ - _validation = { - "principal_id": {"readonly": True}, - "tenant_id": {"readonly": True}, - "type": {"required": True}, - } - - _attribute_map = { - "principal_id": {"key": "principalId", "type": "str"}, - "tenant_id": {"key": "tenantId", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "user_assigned_identities": {"key": "userAssignedIdentities", "type": "{UserAssignedIdentity}"}, - } - - def __init__( - self, - *, - type: Union[str, "_models.ManagedServiceIdentityType"], - user_assigned_identities: Optional[Dict[str, "_models.UserAssignedIdentity"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword type: Type of managed service identity (where both SystemAssigned and UserAssigned - types are allowed). Required. Known values are: "None", "SystemAssigned", "UserAssigned", and - "SystemAssigned,UserAssigned". - :paramtype type: str or ~azure.mgmt.monitor.v2022_06_01.models.ManagedServiceIdentityType - :keyword user_assigned_identities: The set of user assigned identities associated with the - resource. The userAssignedIdentities dictionary keys will be ARM resource ids in the form: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}. - The dictionary values can be empty objects ({}) in requests. - :paramtype user_assigned_identities: dict[str, - ~azure.mgmt.monitor.v2022_06_01.models.UserAssignedIdentity] - """ - super().__init__(type=type, user_assigned_identities=user_assigned_identities, **kwargs) - class DataCollectionRuleResourceListResult(_serialization.Model): """A pageable list of resources. - 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 value: A list of resources. Required. :vartype value: list[~azure.mgmt.monitor.v2022_06_01.models.DataCollectionRuleResource] @@ -2743,63 +2236,6 @@ class DataCollectionRuleResourceProperties(DataCollectionRule): ~azure.mgmt.monitor.v2022_06_01.models.KnownDataCollectionRuleProvisioningState """ - _validation = { - "immutable_id": {"readonly": True}, - "metadata": {"readonly": True}, - "provisioning_state": {"readonly": True}, - } - - _attribute_map = { - "description": {"key": "description", "type": "str"}, - "immutable_id": {"key": "immutableId", "type": "str"}, - "data_collection_endpoint_id": {"key": "dataCollectionEndpointId", "type": "str"}, - "metadata": {"key": "metadata", "type": "DataCollectionRuleMetadata"}, - "stream_declarations": {"key": "streamDeclarations", "type": "{StreamDeclaration}"}, - "data_sources": {"key": "dataSources", "type": "DataCollectionRuleDataSources"}, - "destinations": {"key": "destinations", "type": "DataCollectionRuleDestinations"}, - "data_flows": {"key": "dataFlows", "type": "[DataFlow]"}, - "provisioning_state": {"key": "provisioningState", "type": "str"}, - } - - def __init__( - self, - *, - description: Optional[str] = None, - data_collection_endpoint_id: Optional[str] = None, - stream_declarations: Optional[Dict[str, "_models.StreamDeclaration"]] = None, - data_sources: Optional["_models.DataCollectionRuleDataSources"] = None, - destinations: Optional["_models.DataCollectionRuleDestinations"] = None, - data_flows: Optional[List["_models.DataFlow"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword description: Description of the data collection rule. - :paramtype description: str - :keyword data_collection_endpoint_id: The resource ID of the data collection endpoint that this - rule can be used with. - :paramtype data_collection_endpoint_id: str - :keyword stream_declarations: Declaration of custom streams used in this rule. - :paramtype stream_declarations: dict[str, - ~azure.mgmt.monitor.v2022_06_01.models.StreamDeclaration] - :keyword data_sources: The specification of data sources. - This property is optional and can be omitted if the rule is meant to be used via direct calls - to the provisioned endpoint. - :paramtype data_sources: ~azure.mgmt.monitor.v2022_06_01.models.DataCollectionRuleDataSources - :keyword destinations: The specification of destinations. - :paramtype destinations: ~azure.mgmt.monitor.v2022_06_01.models.DataCollectionRuleDestinations - :keyword data_flows: The specification of data flows. - :paramtype data_flows: list[~azure.mgmt.monitor.v2022_06_01.models.DataFlow] - """ - super().__init__( - description=description, - data_collection_endpoint_id=data_collection_endpoint_id, - stream_declarations=stream_declarations, - data_sources=data_sources, - destinations=destinations, - data_flows=data_flows, - **kwargs - ) - class DataCollectionRuleResourceSystemData(SystemData): """Metadata pertaining to creation and last modification of the resource. @@ -2820,52 +2256,6 @@ class DataCollectionRuleResourceSystemData(SystemData): :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: 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.monitor.v2022_06_01.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.monitor.v2022_06_01.models.CreatedByType - :keyword last_modified_at: The timestamp of resource last modification (UTC). - :paramtype last_modified_at: ~datetime.datetime - """ - super().__init__( - created_by=created_by, - created_by_type=created_by_type, - created_at=created_at, - last_modified_by=last_modified_by, - last_modified_by_type=last_modified_by_type, - last_modified_at=last_modified_at, - **kwargs - ) - class DataFlow(_serialization.Model): """Definition of which streams are sent to which destinations. @@ -2998,32 +2388,6 @@ class DataImportSourcesEventHub(EventHubDataSource): :vartype stream: str """ - _attribute_map = { - "name": {"key": "name", "type": "str"}, - "consumer_group": {"key": "consumerGroup", "type": "str"}, - "stream": {"key": "stream", "type": "str"}, - } - - def __init__( - self, - *, - name: Optional[str] = None, - consumer_group: Optional[str] = None, - stream: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: A friendly name for the data source. - This name should be unique across all data sources (regardless of type) within the data - collection rule. - :paramtype name: str - :keyword consumer_group: Event Hub consumer group name. - :paramtype consumer_group: str - :keyword stream: The stream to collect from EventHub. - :paramtype stream: str - """ - super().__init__(name=name, consumer_group=consumer_group, stream=stream, **kwargs) - class DataSourcesSpecDataImports(DataImportSources): """Specifications of pull based data sources. @@ -3032,17 +2396,6 @@ class DataSourcesSpecDataImports(DataImportSources): :vartype event_hub: ~azure.mgmt.monitor.v2022_06_01.models.DataImportSourcesEventHub """ - _attribute_map = { - "event_hub": {"key": "eventHub", "type": "DataImportSourcesEventHub"}, - } - - def __init__(self, *, event_hub: Optional["_models.DataImportSourcesEventHub"] = None, **kwargs: Any) -> None: - """ - :keyword event_hub: Definition of Event Hub configuration. - :paramtype event_hub: ~azure.mgmt.monitor.v2022_06_01.models.DataImportSourcesEventHub - """ - super().__init__(event_hub=event_hub, **kwargs) - class DestinationsSpecAzureMonitorMetrics(AzureMonitorMetricsDestination): """Azure Monitor Metrics destination. @@ -3053,26 +2406,13 @@ class DestinationsSpecAzureMonitorMetrics(AzureMonitorMetricsDestination): :vartype name: str """ - _attribute_map = { - "name": {"key": "name", "type": "str"}, - } - - def __init__(self, *, name: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword name: A friendly name for the destination. - This name should be unique across all destinations (regardless of type) within the data - collection rule. - :paramtype name: str - """ - super().__init__(name=name, **kwargs) - class EmailReceiver(_serialization.Model): """An email receiver. 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 name: The name of the email receiver. Names must be unique across all receivers within an action group. Required. @@ -3119,7 +2459,7 @@ def __init__(self, *, name: str, email_address: str, use_common_alert_schema: bo class EnableRequest(_serialization.Model): """Describes a receiver that should be resubscribed. - 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 receiver_name: The name of the receiver to resubscribe. Required. :vartype receiver_name: str @@ -3327,7 +2667,7 @@ def __init__( class EventHubReceiver(_serialization.Model): """An Event hub receiver. - 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 name of the Event hub receiver. Names must be unique across all receivers within an action group. Required. @@ -3400,7 +2740,7 @@ class ExtensionDataSource(_serialization.Model): the Azure Monitor Agent. Collected from either Windows and Linux machines, depending on which extension is defined. - 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 streams: List of streams that this data source will be sent to. A stream indicates what schema will be used for this data and usually what table in Log @@ -3471,7 +2811,7 @@ def __init__( class IisLogsDataSource(_serialization.Model): """Enables IIS logs to be collected by this data collection rule. - 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 streams: IIS streams. Required. :vartype streams: list[str] @@ -3520,7 +2860,7 @@ def __init__( class ItsmReceiver(_serialization.Model): """An Itsm receiver. - 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 name of the Itsm receiver. Names must be unique across all receivers within an action group. Required. @@ -3534,7 +2874,7 @@ class ItsmReceiver(_serialization.Model): CreateMultipleWorkItems option will be part of this blob as well. Required. :vartype ticket_configuration: str :ivar region: Region in which workspace resides. Supported - values:'centralindia','japaneast','southeastasia','australiasoutheast','uksouth','westcentralus','canadacentral','eastus','westeurope'. + values:'centralindia','japaneast','southeastasia','australiasoutheast','uksouth','westcentralus','canadacentral','eastus','westeurope'. # pylint: disable=line-too-long Required. :vartype region: str """ @@ -3571,7 +2911,7 @@ def __init__( CreateMultipleWorkItems option will be part of this blob as well. Required. :paramtype ticket_configuration: str :keyword region: Region in which workspace resides. Supported - values:'centralindia','japaneast','southeastasia','australiasoutheast','uksouth','westcentralus','canadacentral','eastus','westeurope'. + values:'centralindia','japaneast','southeastasia','australiasoutheast','uksouth','westcentralus','canadacentral','eastus','westeurope'. # pylint: disable=line-too-long Required. :paramtype region: str """ @@ -3664,7 +3004,7 @@ def __init__( class LogFilesDataSource(_serialization.Model): """Definition of which custom log files will be collected by this data collection rule. - 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 streams: List of streams that this data source will be sent to. A stream indicates what schema will be used for this data source. Required. @@ -3755,22 +3095,11 @@ class LogFilesDataSourceSettings(LogFileSettings): :vartype text: ~azure.mgmt.monitor.v2022_06_01.models.LogFileSettingsText """ - _attribute_map = { - "text": {"key": "text", "type": "LogFileSettingsText"}, - } - - def __init__(self, *, text: Optional["_models.LogFileSettingsText"] = None, **kwargs: Any) -> None: - """ - :keyword text: Text settings. - :paramtype text: ~azure.mgmt.monitor.v2022_06_01.models.LogFileSettingsText - """ - super().__init__(text=text, **kwargs) - class LogFileTextSettings(_serialization.Model): """Settings for text log files. - 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 record_start_timestamp_format: One of the supported timestamp formats. Required. Known values are: "ISO 8601", "YYYY-MM-DD HH:MM:SS", "M/D/YYYY HH:MM:SS AM/PM", "Mon DD, YYYY @@ -3809,7 +3138,7 @@ def __init__( class LogFileSettingsText(LogFileTextSettings): """Text settings. - 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 record_start_timestamp_format: One of the supported timestamp formats. Required. Known values are: "ISO 8601", "YYYY-MM-DD HH:MM:SS", "M/D/YYYY HH:MM:SS AM/PM", "Mon DD, YYYY @@ -3819,35 +3148,11 @@ class LogFileSettingsText(LogFileTextSettings): ~azure.mgmt.monitor.v2022_06_01.models.KnownLogFileTextSettingsRecordStartTimestampFormat """ - _validation = { - "record_start_timestamp_format": {"required": True}, - } - - _attribute_map = { - "record_start_timestamp_format": {"key": "recordStartTimestampFormat", "type": "str"}, - } - - def __init__( - self, - *, - record_start_timestamp_format: Union[str, "_models.KnownLogFileTextSettingsRecordStartTimestampFormat"], - **kwargs: Any - ) -> None: - """ - :keyword record_start_timestamp_format: One of the supported timestamp formats. Required. Known - values are: "ISO 8601", "YYYY-MM-DD HH:MM:SS", "M/D/YYYY HH:MM:SS AM/PM", "Mon DD, YYYY - HH:MM:SS", "yyMMdd HH:mm:ss", "ddMMyy HH:mm:ss", "MMM d hh:mm:ss", "dd/MMM/yyyy:HH:mm:ss zzz", - and "yyyy-MM-ddTHH:mm:ssK". - :paramtype record_start_timestamp_format: str or - ~azure.mgmt.monitor.v2022_06_01.models.KnownLogFileTextSettingsRecordStartTimestampFormat - """ - super().__init__(record_start_timestamp_format=record_start_timestamp_format, **kwargs) - class LogicAppReceiver(_serialization.Model): """A logic app receiver. - 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 name of the logic app receiver. Names must be unique across all receivers within an action group. Required. @@ -3934,10 +3239,10 @@ def __init__(self, *, account_resource_id: Optional[str] = None, name: Optional[ self.name = name -class NotificationRequestBody(_serialization.Model): # pylint: disable=too-many-instance-attributes +class NotificationRequestBody(_serialization.Model): """The request body which contain contact detail metadata. - 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 alert_type: The value of the supported alert type. Supported alert type values are: servicehealth, metricstaticthreshold, metricsdynamicthreshold, logalertv2, smartalert, @@ -4133,7 +3438,7 @@ def __init__( class PlatformTelemetryDataSource(_serialization.Model): """Definition of platform telemetry data source configuration. - 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 streams: List of platform telemetry streams to collect. Required. :vartype streams: list[str] @@ -4284,7 +3589,7 @@ class ResourceForUpdateIdentity(ManagedServiceIdentity): 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 principal_id: The service principal ID of the system assigned identity. This property will only be provided for a system assigned identity. @@ -4298,53 +3603,19 @@ class ResourceForUpdateIdentity(ManagedServiceIdentity): :vartype type: str or ~azure.mgmt.monitor.v2022_06_01.models.ManagedServiceIdentityType :ivar user_assigned_identities: The set of user assigned identities associated with the resource. The userAssignedIdentities dictionary keys will be ARM resource ids in the form: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}. + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}. # pylint: disable=line-too-long The dictionary values can be empty objects ({}) in requests. :vartype user_assigned_identities: dict[str, ~azure.mgmt.monitor.v2022_06_01.models.UserAssignedIdentity] """ - _validation = { - "principal_id": {"readonly": True}, - "tenant_id": {"readonly": True}, - "type": {"required": True}, - } - - _attribute_map = { - "principal_id": {"key": "principalId", "type": "str"}, - "tenant_id": {"key": "tenantId", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "user_assigned_identities": {"key": "userAssignedIdentities", "type": "{UserAssignedIdentity}"}, - } - - def __init__( - self, - *, - type: Union[str, "_models.ManagedServiceIdentityType"], - user_assigned_identities: Optional[Dict[str, "_models.UserAssignedIdentity"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword type: Type of managed service identity (where both SystemAssigned and UserAssigned - types are allowed). Required. Known values are: "None", "SystemAssigned", "UserAssigned", and - "SystemAssigned,UserAssigned". - :paramtype type: str or ~azure.mgmt.monitor.v2022_06_01.models.ManagedServiceIdentityType - :keyword user_assigned_identities: The set of user assigned identities associated with the - resource. The userAssignedIdentities dictionary keys will be ARM resource ids in the form: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}. - The dictionary values can be empty objects ({}) in requests. - :paramtype user_assigned_identities: dict[str, - ~azure.mgmt.monitor.v2022_06_01.models.UserAssignedIdentity] - """ - super().__init__(type=type, user_assigned_identities=user_assigned_identities, **kwargs) - class SmsReceiver(_serialization.Model): """An SMS receiver. 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 name: The name of the SMS receiver. Names must be unique across all receivers within an action group. Required. @@ -4559,7 +3830,7 @@ def __init__( class TestNotificationDetailsResponse(_serialization.Model): """The details of the test notification results. - 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 context: The context info. :vartype context: ~azure.mgmt.monitor.v2022_06_01.models.Context @@ -4646,7 +3917,7 @@ def __init__(self, **kwargs: Any) -> None: class VoiceReceiver(_serialization.Model): """A voice receiver. - 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 name of the voice receiver. Names must be unique across all receivers within an action group. Required. @@ -4688,7 +3959,7 @@ def __init__(self, *, name: str, country_code: str, phone_number: str, **kwargs: class WebhookReceiver(_serialization.Model): """A webhook receiver. - 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 name of the webhook receiver. Names must be unique across all receivers within an action group. Required. @@ -4814,7 +4085,7 @@ def __init__( class WindowsFirewallLogsDataSource(_serialization.Model): """Enables Firewall logs to be collected by this data collection rule. - 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 streams: Firewall logs streams. Required. :vartype streams: list[str] diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/models/_monitor_management_client_enums.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/models/_monitor_management_client_enums.py index 7ee89f8ba833..687b1ea59aea 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/models/_monitor_management_client_enums.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/models/_monitor_management_client_enums.py @@ -29,6 +29,7 @@ class KnownColumnDefinitionType(str, Enum, metaclass=CaseInsensitiveEnumMeta): BOOLEAN = "boolean" DATETIME = "datetime" DYNAMIC = "dynamic" + INT_ENUM = "int" class KnownDataCollectionEndpointProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -155,15 +156,21 @@ class KnownPublicNetworkAccessOptions(str, Enum, metaclass=CaseInsensitiveEnumMe class KnownSyslogDataSourceFacilityNames(str, Enum, metaclass=CaseInsensitiveEnumMeta): """KnownSyslogDataSourceFacilityNames.""" + ALERT = "alert" + AUDIT = "audit" AUTH = "auth" AUTHPRIV = "authpriv" + CLOCK = "clock" CRON = "cron" DAEMON = "daemon" + FTP = "ftp" KERN = "kern" LPR = "lpr" MAIL = "mail" MARK = "mark" NEWS = "news" + NOPRI = "nopri" + NTP = "ntp" SYSLOG = "syslog" USER = "user" UUCP = "uucp" diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/operations/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/operations/__init__.py index 134b182d222e..59365f23b2ca 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/operations/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/operations/__init__.py @@ -5,14 +5,20 @@ # 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 ._action_groups_operations import ActionGroupsOperations -from ._data_collection_endpoints_operations import DataCollectionEndpointsOperations -from ._data_collection_rule_associations_operations import DataCollectionRuleAssociationsOperations -from ._data_collection_rules_operations import DataCollectionRulesOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._action_groups_operations import ActionGroupsOperations # type: ignore +from ._data_collection_endpoints_operations import DataCollectionEndpointsOperations # type: ignore +from ._data_collection_rule_associations_operations import DataCollectionRuleAssociationsOperations # type: ignore +from ._data_collection_rules_operations import DataCollectionRulesOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ @@ -21,5 +27,5 @@ "DataCollectionRuleAssociationsOperations", "DataCollectionRulesOperations", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/operations/_action_groups_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/operations/_action_groups_operations.py index f9f641901280..b6113e194533 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/operations/_action_groups_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/operations/_action_groups_operations.py @@ -6,7 +6,9 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload +from io import IOBase +import sys +from typing import Any, Callable, Dict, IO, Iterable, Iterator, Optional, Type, TypeVar, Union, cast, overload import urllib.parse from azure.core.exceptions import ( @@ -15,13 +17,14 @@ 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 @@ -29,8 +32,11 @@ from .. import models as _models from ..._serialization import Serializer -from .._vendor import _convert_request, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -61,7 +67,7 @@ def build_create_or_update_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -96,7 +102,7 @@ def build_get_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -129,7 +135,7 @@ def build_delete_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -163,7 +169,7 @@ def build_update_request( "actionGroupName": _SERIALIZER.url("action_group_name", action_group_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -192,7 +198,7 @@ def build_post_test_notifications_request(subscription_id: str, **kwargs: Any) - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -227,7 +233,7 @@ def build_create_notifications_at_resource_group_level_request( # pylint: disab ), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -263,7 +269,7 @@ def build_create_notifications_at_action_group_resource_level_request( # pylint "actionGroupName": _SERIALIZER.url("action_group_name", action_group_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -293,7 +299,7 @@ def build_get_test_notifications_request(notification_id: str, subscription_id: "notificationId": _SERIALIZER.url("notification_id", notification_id, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -326,7 +332,7 @@ def build_get_test_notifications_at_resource_group_level_request( # pylint: dis "notificationId": _SERIALIZER.url("notification_id", notification_id, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -360,7 +366,7 @@ def build_get_test_notifications_at_action_group_resource_level_request( # pyli "notificationId": _SERIALIZER.url("notification_id", notification_id, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -384,7 +390,7 @@ def build_list_by_subscription_id_request(subscription_id: str, **kwargs: Any) - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -414,7 +420,7 @@ def build_list_by_resource_group_request(resource_group_name: str, subscription_ "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -448,7 +454,7 @@ def build_enable_receiver_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -479,6 +485,7 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @overload def create_or_update( @@ -502,7 +509,6 @@ def create_or_update( :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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_06_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -513,7 +519,7 @@ def create_or_update( self, resource_group_name: str, action_group_name: str, - action_group: IO, + action_group: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -526,11 +532,10 @@ def create_or_update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group: The action group to create or use for the update. Required. - :type action_group: IO + :type action_group: 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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_06_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -541,7 +546,7 @@ def create_or_update( self, resource_group_name: str, action_group_name: str, - action_group: Union[_models.ActionGroupResource, IO], + action_group: Union[_models.ActionGroupResource, IO[bytes]], **kwargs: Any ) -> _models.ActionGroupResource: """Create a new action group or update an existing one. @@ -552,17 +557,13 @@ def create_or_update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group: The action group to create or use for the update. Is either a - ActionGroupResource type or a IO type. Required. - :type action_group: ~azure.mgmt.monitor.v2022_06_01.models.ActionGroupResource 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 + ActionGroupResource type or a IO[bytes] type. Required. + :type action_group: ~azure.mgmt.monitor.v2022_06_01.models.ActionGroupResource or IO[bytes] :return: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_06_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -573,19 +574,19 @@ def create_or_update( _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", "2022-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-06-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ActionGroupResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(action_group, (IO, bytes)): + if isinstance(action_group, (IOBase, bytes)): _content = action_group else: _json = self._serialize.body(action_group, "ActionGroupResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, action_group_name=action_group_name, subscription_id=self._config.subscription_id, @@ -593,16 +594,14 @@ def create_or_update( 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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -612,21 +611,13 @@ def create_or_update( 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("ActionGroupResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("ActionGroupResource", pipeline_response) + deserialized = self._deserialize("ActionGroupResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/actionGroups/{actionGroupName}" - } - @distributed_trace def get(self, resource_group_name: str, action_group_name: str, **kwargs: Any) -> _models.ActionGroupResource: """Get an action group. @@ -636,12 +627,11 @@ def get(self, resource_group_name: str, action_group_name: str, **kwargs: Any) - :type resource_group_name: str :param action_group_name: The name of the action group. Required. :type action_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_06_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -652,24 +642,22 @@ def get(self, resource_group_name: str, action_group_name: str, **kwargs: Any) - _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-06-01")) cls: ClsType[_models.ActionGroupResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, action_group_name=action_group_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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -679,16 +667,12 @@ def get(self, resource_group_name: str, action_group_name: str, **kwargs: Any) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ActionGroupResource", pipeline_response) + deserialized = self._deserialize("ActionGroupResource", 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.Insights/actionGroups/{actionGroupName}" - } + return deserialized # type: ignore @distributed_trace def delete( # pylint: disable=inconsistent-return-statements @@ -701,12 +685,11 @@ def delete( # pylint: disable=inconsistent-return-statements :type resource_group_name: str :param action_group_name: The name of the action group. Required. :type action_group_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, @@ -717,24 +700,22 @@ def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-06-01")) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, action_group_name=action_group_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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -745,11 +726,7 @@ def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/actionGroups/{actionGroupName}" - } + return cls(pipeline_response, None, {}) # type: ignore @overload def update( @@ -773,7 +750,6 @@ def update( :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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_06_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -784,7 +760,7 @@ def update( self, resource_group_name: str, action_group_name: str, - action_group_patch: IO, + action_group_patch: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -797,11 +773,10 @@ def update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group_patch: Parameters supplied to the operation. Required. - :type action_group_patch: IO + :type action_group_patch: 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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_06_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -812,7 +787,7 @@ def update( self, resource_group_name: str, action_group_name: str, - action_group_patch: Union[_models.ActionGroupPatchBody, IO], + action_group_patch: Union[_models.ActionGroupPatchBody, IO[bytes]], **kwargs: Any ) -> _models.ActionGroupResource: """Updates an existing action group's tags. To update other fields use the CreateOrUpdate method. @@ -823,17 +798,14 @@ def update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group_patch: Parameters supplied to the operation. Is either a - ActionGroupPatchBody type or a IO type. Required. - :type action_group_patch: ~azure.mgmt.monitor.v2022_06_01.models.ActionGroupPatchBody 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 + ActionGroupPatchBody type or a IO[bytes] type. Required. + :type action_group_patch: ~azure.mgmt.monitor.v2022_06_01.models.ActionGroupPatchBody or + IO[bytes] :return: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_06_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -844,19 +816,19 @@ def update( _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", "2022-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-06-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ActionGroupResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(action_group_patch, (IO, bytes)): + if isinstance(action_group_patch, (IOBase, bytes)): _content = action_group_patch else: _json = self._serialize.body(action_group_patch, "ActionGroupPatchBody") - request = build_update_request( + _request = build_update_request( resource_group_name=resource_group_name, action_group_name=action_group_name, subscription_id=self._config.subscription_id, @@ -864,16 +836,14 @@ def update( 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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -883,21 +853,17 @@ def update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ActionGroupResource", pipeline_response) + deserialized = self._deserialize("ActionGroupResource", 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.Insights/actionGroups/{actionGroupName}" - } + return deserialized # type: ignore def _post_test_notifications_initial( - self, notification_request: Union[_models.NotificationRequestBody, IO], **kwargs: Any - ) -> Optional[_models.TestNotificationDetailsResponse]: - error_map = { + self, notification_request: Union[_models.NotificationRequestBody, IO[bytes]], **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -908,59 +874,56 @@ def _post_test_notifications_initial( _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", "2022-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-06-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Optional[_models.TestNotificationDetailsResponse]] = kwargs.pop("cls", None) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(notification_request, (IO, bytes)): + if isinstance(notification_request, (IOBase, bytes)): _content = notification_request else: _json = self._serialize.body(notification_request, "NotificationRequestBody") - request = build_post_test_notifications_request( + _request = build_post_test_notifications_request( subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, content=_content, - template_url=self._post_test_notifications_initial.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: + 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) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = None response_headers = {} - if response.status_code == 200: - deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response) - if response.status_code == 202: response_headers["location"] = self._deserialize("str", response.headers.get("location")) - if cls: - return cls(pipeline_response, deserialized, response_headers) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - return deserialized + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore - _post_test_notifications_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/createNotifications" - } + return deserialized # type: ignore @overload def begin_post_test_notifications( @@ -978,14 +941,6 @@ def begin_post_test_notifications( :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 TestNotificationDetailsResponse or the result of cls(response) :rtype: @@ -995,24 +950,16 @@ def begin_post_test_notifications( @overload def begin_post_test_notifications( - self, notification_request: IO, *, content_type: str = "application/json", **kwargs: Any + self, notification_request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.TestNotificationDetailsResponse]: """Send test notifications to a set of provided receivers. :param notification_request: The notification request body which includes the contact details. Required. - :type notification_request: IO + :type notification_request: 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 TestNotificationDetailsResponse or the result of cls(response) :rtype: @@ -1022,25 +969,14 @@ def begin_post_test_notifications( @distributed_trace def begin_post_test_notifications( - self, notification_request: Union[_models.NotificationRequestBody, IO], **kwargs: Any + self, notification_request: Union[_models.NotificationRequestBody, IO[bytes]], **kwargs: Any ) -> LROPoller[_models.TestNotificationDetailsResponse]: """Send test notifications to a set of provided receivers. :param notification_request: The notification request body which includes the contact details. - Is either a NotificationRequestBody type or a IO type. Required. + Is either a NotificationRequestBody type or a IO[bytes] type. Required. :type notification_request: ~azure.mgmt.monitor.v2022_06_01.models.NotificationRequestBody 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. + IO[bytes] :return: An instance of LROPoller that returns either TestNotificationDetailsResponse or the result of cls(response) :rtype: @@ -1050,7 +986,7 @@ def begin_post_test_notifications( _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", "2022-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-06-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.TestNotificationDetailsResponse] = kwargs.pop("cls", None) polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) @@ -1066,12 +1002,13 @@ def begin_post_test_notifications( 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("TestNotificationDetailsResponse", pipeline_response) + deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: @@ -1083,22 +1020,23 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return LROPoller.from_continuation_token( + return LROPoller[_models.TestNotificationDetailsResponse].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_post_test_notifications.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/createNotifications" - } + return LROPoller[_models.TestNotificationDetailsResponse]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) def _create_notifications_at_resource_group_level_initial( # pylint: disable=name-too-long - self, resource_group_name: str, notification_request: Union[_models.NotificationRequestBody, IO], **kwargs: Any - ) -> Optional[_models.TestNotificationDetailsResponse]: - error_map = { + self, + resource_group_name: str, + notification_request: Union[_models.NotificationRequestBody, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1109,60 +1047,57 @@ def _create_notifications_at_resource_group_level_initial( # pylint: disable=na _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", "2022-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-06-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Optional[_models.TestNotificationDetailsResponse]] = kwargs.pop("cls", None) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(notification_request, (IO, bytes)): + if isinstance(notification_request, (IOBase, bytes)): _content = notification_request else: _json = self._serialize.body(notification_request, "NotificationRequestBody") - request = build_create_notifications_at_resource_group_level_request( + _request = build_create_notifications_at_resource_group_level_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, content=_content, - template_url=self._create_notifications_at_resource_group_level_initial.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: + 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) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = None response_headers = {} - if response.status_code == 200: - deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response) - if response.status_code == 202: response_headers["location"] = self._deserialize("str", response.headers.get("location")) - if cls: - return cls(pipeline_response, deserialized, response_headers) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - return deserialized + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore - _create_notifications_at_resource_group_level_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/createNotifications" - } + return deserialized # type: ignore @overload def begin_create_notifications_at_resource_group_level( # pylint: disable=name-too-long @@ -1184,14 +1119,6 @@ def begin_create_notifications_at_resource_group_level( # pylint: disable=name- :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 TestNotificationDetailsResponse or the result of cls(response) :rtype: @@ -1203,7 +1130,7 @@ def begin_create_notifications_at_resource_group_level( # pylint: disable=name- def begin_create_notifications_at_resource_group_level( # pylint: disable=name-too-long self, resource_group_name: str, - notification_request: IO, + notification_request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -1215,18 +1142,10 @@ def begin_create_notifications_at_resource_group_level( # pylint: disable=name- :type resource_group_name: str :param notification_request: The notification request body which includes the contact details. Required. - :type notification_request: IO + :type notification_request: 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 TestNotificationDetailsResponse or the result of cls(response) :rtype: @@ -1236,7 +1155,10 @@ def begin_create_notifications_at_resource_group_level( # pylint: disable=name- @distributed_trace def begin_create_notifications_at_resource_group_level( # pylint: disable=name-too-long - self, resource_group_name: str, notification_request: Union[_models.NotificationRequestBody, IO], **kwargs: Any + self, + resource_group_name: str, + notification_request: Union[_models.NotificationRequestBody, IO[bytes]], + **kwargs: Any ) -> LROPoller[_models.TestNotificationDetailsResponse]: """Send test notifications to a set of provided receivers. @@ -1244,20 +1166,9 @@ def begin_create_notifications_at_resource_group_level( # pylint: disable=name- Required. :type resource_group_name: str :param notification_request: The notification request body which includes the contact details. - Is either a NotificationRequestBody type or a IO type. Required. + Is either a NotificationRequestBody type or a IO[bytes] type. Required. :type notification_request: ~azure.mgmt.monitor.v2022_06_01.models.NotificationRequestBody 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. + IO[bytes] :return: An instance of LROPoller that returns either TestNotificationDetailsResponse or the result of cls(response) :rtype: @@ -1267,7 +1178,7 @@ def begin_create_notifications_at_resource_group_level( # pylint: disable=name- _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", "2022-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-06-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.TestNotificationDetailsResponse] = kwargs.pop("cls", None) polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) @@ -1284,12 +1195,13 @@ def begin_create_notifications_at_resource_group_level( # pylint: disable=name- 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("TestNotificationDetailsResponse", pipeline_response) + deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: @@ -1301,26 +1213,24 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return LROPoller.from_continuation_token( + return LROPoller[_models.TestNotificationDetailsResponse].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_create_notifications_at_resource_group_level.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/createNotifications" - } + return LROPoller[_models.TestNotificationDetailsResponse]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) def _create_notifications_at_action_group_resource_level_initial( # pylint: disable=name-too-long self, resource_group_name: str, action_group_name: str, - notification_request: Union[_models.NotificationRequestBody, IO], + notification_request: Union[_models.NotificationRequestBody, IO[bytes]], **kwargs: Any - ) -> Optional[_models.TestNotificationDetailsResponse]: - error_map = { + ) -> Iterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1331,19 +1241,19 @@ def _create_notifications_at_action_group_resource_level_initial( # pylint: dis _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", "2022-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-06-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Optional[_models.TestNotificationDetailsResponse]] = kwargs.pop("cls", None) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(notification_request, (IO, bytes)): + if isinstance(notification_request, (IOBase, bytes)): _content = notification_request else: _json = self._serialize.body(notification_request, "NotificationRequestBody") - request = build_create_notifications_at_action_group_resource_level_request( + _request = build_create_notifications_at_action_group_resource_level_request( resource_group_name=resource_group_name, action_group_name=action_group_name, subscription_id=self._config.subscription_id, @@ -1351,41 +1261,38 @@ def _create_notifications_at_action_group_resource_level_initial( # pylint: dis content_type=content_type, json=_json, content=_content, - template_url=self._create_notifications_at_action_group_resource_level_initial.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: + 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) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = None response_headers = {} - if response.status_code == 200: - deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response) - if response.status_code == 202: response_headers["location"] = self._deserialize("str", response.headers.get("location")) - if cls: - return cls(pipeline_response, deserialized, response_headers) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - return deserialized + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore - _create_notifications_at_action_group_resource_level_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/actionGroups/{actionGroupName}/createNotifications" - } + return deserialized # type: ignore @overload def begin_create_notifications_at_action_group_resource_level( # pylint: disable=name-too-long @@ -1410,14 +1317,6 @@ def begin_create_notifications_at_action_group_resource_level( # pylint: disabl :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 TestNotificationDetailsResponse or the result of cls(response) :rtype: @@ -1430,7 +1329,7 @@ def begin_create_notifications_at_action_group_resource_level( # pylint: disabl self, resource_group_name: str, action_group_name: str, - notification_request: IO, + notification_request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -1444,18 +1343,10 @@ def begin_create_notifications_at_action_group_resource_level( # pylint: disabl :type action_group_name: str :param notification_request: The notification request body which includes the contact details. Required. - :type notification_request: IO + :type notification_request: 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 TestNotificationDetailsResponse or the result of cls(response) :rtype: @@ -1468,7 +1359,7 @@ def begin_create_notifications_at_action_group_resource_level( # pylint: disabl self, resource_group_name: str, action_group_name: str, - notification_request: Union[_models.NotificationRequestBody, IO], + notification_request: Union[_models.NotificationRequestBody, IO[bytes]], **kwargs: Any ) -> LROPoller[_models.TestNotificationDetailsResponse]: """Send test notifications to a set of provided receivers. @@ -1479,20 +1370,9 @@ def begin_create_notifications_at_action_group_resource_level( # pylint: disabl :param action_group_name: The name of the action group. Required. :type action_group_name: str :param notification_request: The notification request body which includes the contact details. - Is either a NotificationRequestBody type or a IO type. Required. + Is either a NotificationRequestBody type or a IO[bytes] type. Required. :type notification_request: ~azure.mgmt.monitor.v2022_06_01.models.NotificationRequestBody 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. + IO[bytes] :return: An instance of LROPoller that returns either TestNotificationDetailsResponse or the result of cls(response) :rtype: @@ -1502,7 +1382,7 @@ def begin_create_notifications_at_action_group_resource_level( # pylint: disabl _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", "2022-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-06-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.TestNotificationDetailsResponse] = kwargs.pop("cls", None) polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) @@ -1520,12 +1400,13 @@ def begin_create_notifications_at_action_group_resource_level( # pylint: disabl 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("TestNotificationDetailsResponse", pipeline_response) + deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: @@ -1537,17 +1418,15 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return LROPoller.from_continuation_token( + return LROPoller[_models.TestNotificationDetailsResponse].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_create_notifications_at_action_group_resource_level.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/actionGroups/{actionGroupName}/createNotifications" - } + return LROPoller[_models.TestNotificationDetailsResponse]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) @distributed_trace def get_test_notifications(self, notification_id: str, **kwargs: Any) -> _models.TestNotificationDetailsResponse: @@ -1555,12 +1434,11 @@ def get_test_notifications(self, notification_id: str, **kwargs: Any) -> _models :param notification_id: The notification id. Required. :type notification_id: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: TestNotificationDetailsResponse or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_06_01.models.TestNotificationDetailsResponse :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1571,23 +1449,21 @@ def get_test_notifications(self, notification_id: str, **kwargs: Any) -> _models _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-06-01")) cls: ClsType[_models.TestNotificationDetailsResponse] = kwargs.pop("cls", None) - request = build_get_test_notifications_request( + _request = build_get_test_notifications_request( notification_id=notification_id, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get_test_notifications.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1597,16 +1473,12 @@ def get_test_notifications(self, notification_id: str, **kwargs: Any) -> _models error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response) + deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get_test_notifications.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/notificationStatus/{notificationId}" - } + return deserialized # type: ignore @distributed_trace def get_test_notifications_at_resource_group_level( # pylint: disable=name-too-long @@ -1619,12 +1491,11 @@ def get_test_notifications_at_resource_group_level( # pylint: disable=name-too- :type resource_group_name: str :param notification_id: The notification id. Required. :type notification_id: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: TestNotificationDetailsResponse or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_06_01.models.TestNotificationDetailsResponse :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1635,24 +1506,22 @@ def get_test_notifications_at_resource_group_level( # pylint: disable=name-too- _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-06-01")) cls: ClsType[_models.TestNotificationDetailsResponse] = kwargs.pop("cls", None) - request = build_get_test_notifications_at_resource_group_level_request( + _request = build_get_test_notifications_at_resource_group_level_request( resource_group_name=resource_group_name, notification_id=notification_id, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get_test_notifications_at_resource_group_level.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1662,16 +1531,12 @@ def get_test_notifications_at_resource_group_level( # pylint: disable=name-too- error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response) + deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get_test_notifications_at_resource_group_level.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/notificationStatus/{notificationId}" - } + return deserialized # type: ignore @distributed_trace def get_test_notifications_at_action_group_resource_level( # pylint: disable=name-too-long @@ -1686,12 +1551,11 @@ def get_test_notifications_at_action_group_resource_level( # pylint: disable=na :type action_group_name: str :param notification_id: The notification id. Required. :type notification_id: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: TestNotificationDetailsResponse or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_06_01.models.TestNotificationDetailsResponse :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1702,25 +1566,23 @@ def get_test_notifications_at_action_group_resource_level( # pylint: disable=na _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-06-01")) cls: ClsType[_models.TestNotificationDetailsResponse] = kwargs.pop("cls", None) - request = build_get_test_notifications_at_action_group_resource_level_request( + _request = build_get_test_notifications_at_action_group_resource_level_request( resource_group_name=resource_group_name, action_group_name=action_group_name, notification_id=notification_id, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get_test_notifications_at_action_group_resource_level.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1730,22 +1592,17 @@ def get_test_notifications_at_action_group_resource_level( # pylint: disable=na error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response) + deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get_test_notifications_at_action_group_resource_level.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/actionGroups/{actionGroupName}/notificationStatus/{notificationId}" - } + return deserialized # type: ignore @distributed_trace def list_by_subscription_id(self, **kwargs: Any) -> Iterable["_models.ActionGroupResource"]: """Get a list of all action groups in a subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ActionGroupResource or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.monitor.v2022_06_01.models.ActionGroupResource] @@ -1754,10 +1611,10 @@ def list_by_subscription_id(self, **kwargs: Any) -> Iterable["_models.ActionGrou _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-06-01")) cls: ClsType[_models.ActionGroupList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1768,15 +1625,13 @@ def list_by_subscription_id(self, **kwargs: Any) -> Iterable["_models.ActionGrou def prepare_request(next_link=None): if not next_link: - request = build_list_by_subscription_id_request( + _request = build_list_by_subscription_id_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_subscription_id.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -1787,14 +1642,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("ActionGroupList", pipeline_response) @@ -1804,11 +1658,11 @@ def extract_data(pipeline_response): return None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1821,10 +1675,6 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_by_subscription_id.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/actionGroups" - } - @distributed_trace def list_by_resource_group( self, resource_group_name: str, **kwargs: Any @@ -1834,7 +1684,6 @@ def list_by_resource_group( :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ActionGroupResource or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.monitor.v2022_06_01.models.ActionGroupResource] @@ -1843,10 +1692,10 @@ def list_by_resource_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-06-01")) cls: ClsType[_models.ActionGroupList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1857,16 +1706,14 @@ 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_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -1877,14 +1724,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("ActionGroupList", pipeline_response) @@ -1894,11 +1740,11 @@ def extract_data(pipeline_response): return None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1911,12 +1757,8 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/actionGroups" - } - @overload - def enable_receiver( # pylint: disable=inconsistent-return-statements + def enable_receiver( self, resource_group_name: str, action_group_name: str, @@ -1938,18 +1780,17 @@ def enable_receiver( # pylint: disable=inconsistent-return-statements :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: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def enable_receiver( # pylint: disable=inconsistent-return-statements + def enable_receiver( self, resource_group_name: str, action_group_name: str, - enable_request: IO, + enable_request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -1963,11 +1804,10 @@ def enable_receiver( # pylint: disable=inconsistent-return-statements :param action_group_name: The name of the action group. Required. :type action_group_name: str :param enable_request: The receiver to re-enable. Required. - :type enable_request: IO + :type enable_request: 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: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1978,7 +1818,7 @@ def enable_receiver( # pylint: disable=inconsistent-return-statements self, resource_group_name: str, action_group_name: str, - enable_request: Union[_models.EnableRequest, IO], + enable_request: Union[_models.EnableRequest, IO[bytes]], **kwargs: Any ) -> None: """Enable a receiver in an action group. This changes the receiver's status from Disabled to @@ -1989,41 +1829,40 @@ def enable_receiver( # pylint: disable=inconsistent-return-statements :type resource_group_name: str :param action_group_name: The name of the action group. Required. :type action_group_name: str - :param enable_request: The receiver to re-enable. Is either a EnableRequest type or a IO type. - Required. - :type enable_request: ~azure.mgmt.monitor.v2022_06_01.models.EnableRequest 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 + :param enable_request: The receiver to re-enable. Is either a EnableRequest type or a IO[bytes] + type. Required. + :type enable_request: ~azure.mgmt.monitor.v2022_06_01.models.EnableRequest or IO[bytes] :return: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 304: ResourceNotModifiedError, - 409: lambda response: ResourceExistsError(response=response, error_format=ARMErrorFormat), + 409: cast( + Type[HttpResponseError], + lambda response: ResourceExistsError(response=response, error_format=ARMErrorFormat), + ), } 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: str = kwargs.pop("api_version", _params.pop("api-version", "2022-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-06-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[None] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(enable_request, (IO, bytes)): + if isinstance(enable_request, (IOBase, bytes)): _content = enable_request else: _json = self._serialize.body(enable_request, "EnableRequest") - request = build_enable_receiver_request( + _request = build_enable_receiver_request( resource_group_name=resource_group_name, action_group_name=action_group_name, subscription_id=self._config.subscription_id, @@ -2031,28 +1870,22 @@ def enable_receiver( # pylint: disable=inconsistent-return-statements content_type=content_type, json=_json, content=_content, - template_url=self.enable_receiver.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _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) + map_error(status_code=response.status_code, response=response, error_map=error_map) # type: ignore 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, {}) - - enable_receiver.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/actionGroups/{actionGroupName}/subscribe" - } + return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/operations/_data_collection_endpoints_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/operations/_data_collection_endpoints_operations.py index 8eeb833bdda9..c91474a9cdb2 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/operations/_data_collection_endpoints_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/operations/_data_collection_endpoints_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload import urllib.parse @@ -19,16 +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, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -55,7 +58,7 @@ def build_list_by_resource_group_request(resource_group_name: str, subscription_ ), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -81,7 +84,7 @@ def build_list_by_subscription_request(subscription_id: str, **kwargs: Any) -> H "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -116,7 +119,7 @@ def build_get_request( ), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -152,7 +155,7 @@ def build_create_request( ), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -190,7 +193,7 @@ def build_update_request( ), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -227,7 +230,7 @@ def build_delete_request( ), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -256,6 +259,7 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list_by_resource_group( @@ -268,7 +272,6 @@ def list_by_resource_group( :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either DataCollectionEndpointResource or the result of cls(response) :rtype: @@ -278,10 +281,10 @@ def list_by_resource_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-06-01")) cls: ClsType[_models.DataCollectionEndpointResourceListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -292,16 +295,14 @@ 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_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -312,14 +313,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("DataCollectionEndpointResourceListResult", pipeline_response) @@ -329,11 +329,11 @@ def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -346,17 +346,12 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionEndpoints" - } - @distributed_trace def list_by_subscription(self, **kwargs: Any) -> Iterable["_models.DataCollectionEndpointResource"]: """Lists all data collection endpoints in the specified subscription. Lists all data collection endpoints in the specified subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either DataCollectionEndpointResource or the result of cls(response) :rtype: @@ -366,10 +361,10 @@ def list_by_subscription(self, **kwargs: Any) -> Iterable["_models.DataCollectio _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-06-01")) cls: ClsType[_models.DataCollectionEndpointResourceListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -380,15 +375,13 @@ def list_by_subscription(self, **kwargs: Any) -> Iterable["_models.DataCollectio def prepare_request(next_link=None): if not next_link: - request = build_list_by_subscription_request( + _request = build_list_by_subscription_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_subscription.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -399,14 +392,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("DataCollectionEndpointResourceListResult", pipeline_response) @@ -416,11 +408,11 @@ def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -433,10 +425,6 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_by_subscription.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/dataCollectionEndpoints" - } - @distributed_trace def get( self, resource_group_name: str, data_collection_endpoint_name: str, **kwargs: Any @@ -451,12 +439,11 @@ def get( :param data_collection_endpoint_name: The name of the data collection endpoint. The name is case insensitive. Required. :type data_collection_endpoint_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: DataCollectionEndpointResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_06_01.models.DataCollectionEndpointResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -467,24 +454,22 @@ def get( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-06-01")) cls: ClsType[_models.DataCollectionEndpointResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, data_collection_endpoint_name=data_collection_endpoint_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -494,16 +479,12 @@ def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponseCommonV2, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("DataCollectionEndpointResource", pipeline_response) + deserialized = self._deserialize("DataCollectionEndpointResource", 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.Insights/dataCollectionEndpoints/{dataCollectionEndpointName}" - } + return deserialized # type: ignore @overload def create( @@ -530,7 +511,6 @@ def create( :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: DataCollectionEndpointResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_06_01.models.DataCollectionEndpointResource :raises ~azure.core.exceptions.HttpResponseError: @@ -541,7 +521,7 @@ def create( self, resource_group_name: str, data_collection_endpoint_name: str, - body: Optional[IO] = None, + body: Optional[IO[bytes]] = None, *, content_type: str = "application/json", **kwargs: Any @@ -557,11 +537,10 @@ def create( case insensitive. Required. :type data_collection_endpoint_name: str :param body: The payload. Default value is None. - :type body: IO + :type body: 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: DataCollectionEndpointResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_06_01.models.DataCollectionEndpointResource :raises ~azure.core.exceptions.HttpResponseError: @@ -572,7 +551,7 @@ def create( self, resource_group_name: str, data_collection_endpoint_name: str, - body: Optional[Union[_models.DataCollectionEndpointResource, IO]] = None, + body: Optional[Union[_models.DataCollectionEndpointResource, IO[bytes]]] = None, **kwargs: Any ) -> _models.DataCollectionEndpointResource: """Creates or updates a data collection endpoint. @@ -585,18 +564,14 @@ def create( :param data_collection_endpoint_name: The name of the data collection endpoint. The name is case insensitive. Required. :type data_collection_endpoint_name: str - :param body: The payload. Is either a DataCollectionEndpointResource type or a IO type. Default - value is None. - :type body: ~azure.mgmt.monitor.v2022_06_01.models.DataCollectionEndpointResource or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + :param body: The payload. Is either a DataCollectionEndpointResource type or a IO[bytes] type. Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response + :type body: ~azure.mgmt.monitor.v2022_06_01.models.DataCollectionEndpointResource or IO[bytes] :return: DataCollectionEndpointResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_06_01.models.DataCollectionEndpointResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -607,14 +582,14 @@ def create( _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", "2022-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-06-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.DataCollectionEndpointResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(body, (IO, bytes)): + if isinstance(body, (IOBase, bytes)): _content = body else: if body is not None: @@ -622,7 +597,7 @@ def create( else: _json = None - request = build_create_request( + _request = build_create_request( resource_group_name=resource_group_name, data_collection_endpoint_name=data_collection_endpoint_name, subscription_id=self._config.subscription_id, @@ -630,16 +605,14 @@ def create( content_type=content_type, json=_json, content=_content, - template_url=self.create.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -649,21 +622,13 @@ def create( error = self._deserialize.failsafe_deserialize(_models.ErrorResponseCommonV2, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if response.status_code == 200: - deserialized = self._deserialize("DataCollectionEndpointResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("DataCollectionEndpointResource", pipeline_response) + deserialized = self._deserialize("DataCollectionEndpointResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionEndpoints/{dataCollectionEndpointName}" - } - @overload def update( self, @@ -689,7 +654,6 @@ def update( :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: DataCollectionEndpointResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_06_01.models.DataCollectionEndpointResource :raises ~azure.core.exceptions.HttpResponseError: @@ -700,7 +664,7 @@ def update( self, resource_group_name: str, data_collection_endpoint_name: str, - body: Optional[IO] = None, + body: Optional[IO[bytes]] = None, *, content_type: str = "application/json", **kwargs: Any @@ -716,11 +680,10 @@ def update( case insensitive. Required. :type data_collection_endpoint_name: str :param body: The payload. Default value is None. - :type body: IO + :type body: 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: DataCollectionEndpointResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_06_01.models.DataCollectionEndpointResource :raises ~azure.core.exceptions.HttpResponseError: @@ -731,7 +694,7 @@ def update( self, resource_group_name: str, data_collection_endpoint_name: str, - body: Optional[Union[_models.ResourceForUpdate, IO]] = None, + body: Optional[Union[_models.ResourceForUpdate, IO[bytes]]] = None, **kwargs: Any ) -> _models.DataCollectionEndpointResource: """Updates part of a data collection endpoint. @@ -744,18 +707,14 @@ def update( :param data_collection_endpoint_name: The name of the data collection endpoint. The name is case insensitive. Required. :type data_collection_endpoint_name: str - :param body: The payload. Is either a ResourceForUpdate type or a IO type. Default value is - None. - :type body: ~azure.mgmt.monitor.v2022_06_01.models.ResourceForUpdate 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 + :param body: The payload. Is either a ResourceForUpdate type or a IO[bytes] type. Default value + is None. + :type body: ~azure.mgmt.monitor.v2022_06_01.models.ResourceForUpdate or IO[bytes] :return: DataCollectionEndpointResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_06_01.models.DataCollectionEndpointResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -766,14 +725,14 @@ def update( _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", "2022-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-06-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.DataCollectionEndpointResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(body, (IO, bytes)): + if isinstance(body, (IOBase, bytes)): _content = body else: if body is not None: @@ -781,7 +740,7 @@ def update( else: _json = None - request = build_update_request( + _request = build_update_request( resource_group_name=resource_group_name, data_collection_endpoint_name=data_collection_endpoint_name, subscription_id=self._config.subscription_id, @@ -789,16 +748,14 @@ def update( 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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -808,16 +765,12 @@ def update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponseCommonV2, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("DataCollectionEndpointResource", pipeline_response) + deserialized = self._deserialize("DataCollectionEndpointResource", 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.Insights/dataCollectionEndpoints/{dataCollectionEndpointName}" - } + return deserialized # type: ignore @distributed_trace def delete( # pylint: disable=inconsistent-return-statements @@ -833,12 +786,11 @@ def delete( # pylint: disable=inconsistent-return-statements :param data_collection_endpoint_name: The name of the data collection endpoint. The name is case insensitive. Required. :type data_collection_endpoint_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, @@ -849,24 +801,22 @@ def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-06-01")) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, data_collection_endpoint_name=data_collection_endpoint_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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -877,8 +827,4 @@ def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionEndpoints/{dataCollectionEndpointName}" - } + return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/operations/_data_collection_rule_associations_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/operations/_data_collection_rule_associations_operations.py index 1a5da1e93321..a8cf0d55adfd 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/operations/_data_collection_rule_associations_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/operations/_data_collection_rule_associations_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload import urllib.parse @@ -19,16 +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, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -49,7 +52,7 @@ def build_list_by_resource_request(resource_uri: str, **kwargs: Any) -> HttpRequ "resourceUri": _SERIALIZER.url("resource_uri", resource_uri, "str", skip_quote=True, min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -82,7 +85,7 @@ def build_list_by_rule_request( "dataCollectionRuleName": _SERIALIZER.url("data_collection_rule_name", data_collection_rule_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -117,7 +120,7 @@ def build_list_by_data_collection_endpoint_request( # pylint: disable=name-too- ), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -144,7 +147,7 @@ def build_get_request(resource_uri: str, association_name: str, **kwargs: Any) - "associationName": _SERIALIZER.url("association_name", association_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -172,7 +175,7 @@ def build_create_request(resource_uri: str, association_name: str, **kwargs: Any "associationName": _SERIALIZER.url("association_name", association_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -201,7 +204,7 @@ def build_delete_request(resource_uri: str, association_name: str, **kwargs: Any "associationName": _SERIALIZER.url("association_name", association_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -230,18 +233,19 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list_by_resource( self, resource_uri: str, **kwargs: Any ) -> Iterable["_models.DataCollectionRuleAssociationProxyOnlyResource"]: + # pylint: disable=line-too-long """Lists associations for the specified resource. Lists associations for the specified resource. :param resource_uri: The identifier of the resource. Required. :type resource_uri: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either DataCollectionRuleAssociationProxyOnlyResource or the result of cls(response) :rtype: @@ -251,10 +255,10 @@ def list_by_resource( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-06-01")) cls: ClsType[_models.DataCollectionRuleAssociationProxyOnlyResourceListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -265,15 +269,13 @@ def list_by_resource( def prepare_request(next_link=None): if not next_link: - request = build_list_by_resource_request( + _request = build_list_by_resource_request( resource_uri=resource_uri, api_version=api_version, - template_url=self.list_by_resource.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -284,14 +286,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize( @@ -303,11 +304,11 @@ def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -320,12 +321,11 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_by_resource.metadata = {"url": "/{resourceUri}/providers/Microsoft.Insights/dataCollectionRuleAssociations"} - @distributed_trace def list_by_rule( self, resource_group_name: str, data_collection_rule_name: str, **kwargs: Any ) -> Iterable["_models.DataCollectionRuleAssociationProxyOnlyResource"]: + # pylint: disable=line-too-long """Lists associations for the specified data collection rule. Lists associations for the specified data collection rule. @@ -336,7 +336,6 @@ def list_by_rule( :param data_collection_rule_name: The name of the data collection rule. The name is case insensitive. Required. :type data_collection_rule_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either DataCollectionRuleAssociationProxyOnlyResource or the result of cls(response) :rtype: @@ -346,10 +345,10 @@ def list_by_rule( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-06-01")) cls: ClsType[_models.DataCollectionRuleAssociationProxyOnlyResourceListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -360,17 +359,15 @@ def list_by_rule( def prepare_request(next_link=None): if not next_link: - request = build_list_by_rule_request( + _request = build_list_by_rule_request( resource_group_name=resource_group_name, data_collection_rule_name=data_collection_rule_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_rule.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -381,14 +378,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize( @@ -400,11 +396,11 @@ def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -417,14 +413,11 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_by_rule.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionRules/{dataCollectionRuleName}/associations" - } - @distributed_trace def list_by_data_collection_endpoint( self, resource_group_name: str, data_collection_endpoint_name: str, **kwargs: Any ) -> Iterable["_models.DataCollectionRuleAssociationProxyOnlyResource"]: + # pylint: disable=line-too-long """Lists associations for the specified data collection endpoint. Lists associations for the specified data collection endpoint. @@ -435,7 +428,6 @@ def list_by_data_collection_endpoint( :param data_collection_endpoint_name: The name of the data collection endpoint. The name is case insensitive. Required. :type data_collection_endpoint_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either DataCollectionRuleAssociationProxyOnlyResource or the result of cls(response) :rtype: @@ -445,10 +437,10 @@ def list_by_data_collection_endpoint( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-06-01")) cls: ClsType[_models.DataCollectionRuleAssociationProxyOnlyResourceListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -459,17 +451,15 @@ def list_by_data_collection_endpoint( def prepare_request(next_link=None): if not next_link: - request = build_list_by_data_collection_endpoint_request( + _request = build_list_by_data_collection_endpoint_request( resource_group_name=resource_group_name, data_collection_endpoint_name=data_collection_endpoint_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_data_collection_endpoint.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -480,14 +470,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize( @@ -499,11 +488,11 @@ def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -516,10 +505,6 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_by_data_collection_endpoint.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionEndpoints/{dataCollectionEndpointName}/associations" - } - @distributed_trace def get( self, resource_uri: str, association_name: str, **kwargs: Any @@ -532,12 +517,11 @@ def get( :type resource_uri: str :param association_name: The name of the association. The name is case insensitive. Required. :type association_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: DataCollectionRuleAssociationProxyOnlyResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_06_01.models.DataCollectionRuleAssociationProxyOnlyResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -548,23 +532,21 @@ def get( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-06-01")) cls: ClsType[_models.DataCollectionRuleAssociationProxyOnlyResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_uri=resource_uri, association_name=association_name, api_version=api_version, - template_url=self.get.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -574,16 +556,14 @@ def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponseCommonV2, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("DataCollectionRuleAssociationProxyOnlyResource", pipeline_response) + deserialized = self._deserialize( + "DataCollectionRuleAssociationProxyOnlyResource", pipeline_response.http_response + ) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get.metadata = { - "url": "/{resourceUri}/providers/Microsoft.Insights/dataCollectionRuleAssociations/{associationName}" - } + return deserialized # type: ignore @overload def create( @@ -609,7 +589,6 @@ def create( :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: DataCollectionRuleAssociationProxyOnlyResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_06_01.models.DataCollectionRuleAssociationProxyOnlyResource :raises ~azure.core.exceptions.HttpResponseError: @@ -620,7 +599,7 @@ def create( self, resource_uri: str, association_name: str, - body: Optional[IO] = None, + body: Optional[IO[bytes]] = None, *, content_type: str = "application/json", **kwargs: Any @@ -634,11 +613,10 @@ def create( :param association_name: The name of the association. The name is case insensitive. Required. :type association_name: str :param body: The payload. Default value is None. - :type body: IO + :type body: 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: DataCollectionRuleAssociationProxyOnlyResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_06_01.models.DataCollectionRuleAssociationProxyOnlyResource :raises ~azure.core.exceptions.HttpResponseError: @@ -649,7 +627,7 @@ def create( self, resource_uri: str, association_name: str, - body: Optional[Union[_models.DataCollectionRuleAssociationProxyOnlyResource, IO]] = None, + body: Optional[Union[_models.DataCollectionRuleAssociationProxyOnlyResource, IO[bytes]]] = None, **kwargs: Any ) -> _models.DataCollectionRuleAssociationProxyOnlyResource: """Creates or updates an association. @@ -661,18 +639,15 @@ def create( :param association_name: The name of the association. The name is case insensitive. Required. :type association_name: str :param body: The payload. Is either a DataCollectionRuleAssociationProxyOnlyResource type or a - IO type. Default value is None. + IO[bytes] type. Default value is None. :type body: - ~azure.mgmt.monitor.v2022_06_01.models.DataCollectionRuleAssociationProxyOnlyResource 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 + ~azure.mgmt.monitor.v2022_06_01.models.DataCollectionRuleAssociationProxyOnlyResource or + IO[bytes] :return: DataCollectionRuleAssociationProxyOnlyResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_06_01.models.DataCollectionRuleAssociationProxyOnlyResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -683,14 +658,14 @@ def create( _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", "2022-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-06-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.DataCollectionRuleAssociationProxyOnlyResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(body, (IO, bytes)): + if isinstance(body, (IOBase, bytes)): _content = body else: if body is not None: @@ -698,23 +673,21 @@ def create( else: _json = None - request = build_create_request( + _request = build_create_request( resource_uri=resource_uri, association_name=association_name, api_version=api_version, content_type=content_type, json=_json, content=_content, - template_url=self.create.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -724,21 +697,15 @@ def create( error = self._deserialize.failsafe_deserialize(_models.ErrorResponseCommonV2, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if response.status_code == 200: - deserialized = self._deserialize("DataCollectionRuleAssociationProxyOnlyResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("DataCollectionRuleAssociationProxyOnlyResource", pipeline_response) + deserialized = self._deserialize( + "DataCollectionRuleAssociationProxyOnlyResource", pipeline_response.http_response + ) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create.metadata = { - "url": "/{resourceUri}/providers/Microsoft.Insights/dataCollectionRuleAssociations/{associationName}" - } - @distributed_trace def delete( # pylint: disable=inconsistent-return-statements self, resource_uri: str, association_name: str, **kwargs: Any @@ -751,12 +718,11 @@ def delete( # pylint: disable=inconsistent-return-statements :type resource_uri: str :param association_name: The name of the association. The name is case insensitive. Required. :type association_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, @@ -767,23 +733,21 @@ def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-06-01")) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_uri=resource_uri, association_name=association_name, api_version=api_version, - template_url=self.delete.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -794,8 +758,4 @@ def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/{resourceUri}/providers/Microsoft.Insights/dataCollectionRuleAssociations/{associationName}" - } + return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/operations/_data_collection_rules_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/operations/_data_collection_rules_operations.py index 178b4924c8f0..74202fa3fad3 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/operations/_data_collection_rules_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_06_01/operations/_data_collection_rules_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload import urllib.parse @@ -19,16 +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, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -55,7 +58,7 @@ def build_list_by_resource_group_request(resource_group_name: str, subscription_ ), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -81,7 +84,7 @@ def build_list_by_subscription_request(subscription_id: str, **kwargs: Any) -> H "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -114,7 +117,7 @@ def build_get_request( "dataCollectionRuleName": _SERIALIZER.url("data_collection_rule_name", data_collection_rule_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -148,7 +151,7 @@ def build_create_request( "dataCollectionRuleName": _SERIALIZER.url("data_collection_rule_name", data_collection_rule_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -184,7 +187,7 @@ def build_update_request( "dataCollectionRuleName": _SERIALIZER.url("data_collection_rule_name", data_collection_rule_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -219,7 +222,7 @@ def build_delete_request( "dataCollectionRuleName": _SERIALIZER.url("data_collection_rule_name", data_collection_rule_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -248,6 +251,7 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list_by_resource_group( @@ -260,7 +264,6 @@ def list_by_resource_group( :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either DataCollectionRuleResource or the result of cls(response) :rtype: @@ -270,10 +273,10 @@ def list_by_resource_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-06-01")) cls: ClsType[_models.DataCollectionRuleResourceListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -284,16 +287,14 @@ 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_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -304,14 +305,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("DataCollectionRuleResourceListResult", pipeline_response) @@ -321,11 +321,11 @@ def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -338,17 +338,12 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionRules" - } - @distributed_trace def list_by_subscription(self, **kwargs: Any) -> Iterable["_models.DataCollectionRuleResource"]: """Lists all data collection rules in the specified subscription. Lists all data collection rules in the specified subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either DataCollectionRuleResource or the result of cls(response) :rtype: @@ -358,10 +353,10 @@ def list_by_subscription(self, **kwargs: Any) -> Iterable["_models.DataCollectio _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-06-01")) cls: ClsType[_models.DataCollectionRuleResourceListResult] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -372,15 +367,13 @@ def list_by_subscription(self, **kwargs: Any) -> Iterable["_models.DataCollectio def prepare_request(next_link=None): if not next_link: - request = build_list_by_subscription_request( + _request = build_list_by_subscription_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_subscription.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -391,14 +384,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("DataCollectionRuleResourceListResult", pipeline_response) @@ -408,11 +400,11 @@ def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -425,10 +417,6 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_by_subscription.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/dataCollectionRules" - } - @distributed_trace def get( self, resource_group_name: str, data_collection_rule_name: str, **kwargs: Any @@ -443,12 +431,11 @@ def get( :param data_collection_rule_name: The name of the data collection rule. The name is case insensitive. Required. :type data_collection_rule_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: DataCollectionRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_06_01.models.DataCollectionRuleResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -459,24 +446,22 @@ def get( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-06-01")) cls: ClsType[_models.DataCollectionRuleResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, data_collection_rule_name=data_collection_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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -486,16 +471,12 @@ def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponseCommonV2, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("DataCollectionRuleResource", pipeline_response) + deserialized = self._deserialize("DataCollectionRuleResource", 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.Insights/dataCollectionRules/{dataCollectionRuleName}" - } + return deserialized # type: ignore @overload def create( @@ -522,7 +503,6 @@ def create( :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: DataCollectionRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_06_01.models.DataCollectionRuleResource :raises ~azure.core.exceptions.HttpResponseError: @@ -533,7 +513,7 @@ def create( self, resource_group_name: str, data_collection_rule_name: str, - body: Optional[IO] = None, + body: Optional[IO[bytes]] = None, *, content_type: str = "application/json", **kwargs: Any @@ -549,11 +529,10 @@ def create( insensitive. Required. :type data_collection_rule_name: str :param body: The payload. Default value is None. - :type body: IO + :type body: 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: DataCollectionRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_06_01.models.DataCollectionRuleResource :raises ~azure.core.exceptions.HttpResponseError: @@ -564,7 +543,7 @@ def create( self, resource_group_name: str, data_collection_rule_name: str, - body: Optional[Union[_models.DataCollectionRuleResource, IO]] = None, + body: Optional[Union[_models.DataCollectionRuleResource, IO[bytes]]] = None, **kwargs: Any ) -> _models.DataCollectionRuleResource: """Creates or updates a data collection rule. @@ -577,18 +556,14 @@ def create( :param data_collection_rule_name: The name of the data collection rule. The name is case insensitive. Required. :type data_collection_rule_name: str - :param body: The payload. Is either a DataCollectionRuleResource type or a IO type. Default - value is None. - :type body: ~azure.mgmt.monitor.v2022_06_01.models.DataCollectionRuleResource or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + :param body: The payload. Is either a DataCollectionRuleResource type or a IO[bytes] type. Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response + :type body: ~azure.mgmt.monitor.v2022_06_01.models.DataCollectionRuleResource or IO[bytes] :return: DataCollectionRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_06_01.models.DataCollectionRuleResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -599,14 +574,14 @@ def create( _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", "2022-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-06-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.DataCollectionRuleResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(body, (IO, bytes)): + if isinstance(body, (IOBase, bytes)): _content = body else: if body is not None: @@ -614,7 +589,7 @@ def create( else: _json = None - request = build_create_request( + _request = build_create_request( resource_group_name=resource_group_name, data_collection_rule_name=data_collection_rule_name, subscription_id=self._config.subscription_id, @@ -622,16 +597,14 @@ def create( content_type=content_type, json=_json, content=_content, - template_url=self.create.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -641,21 +614,13 @@ def create( error = self._deserialize.failsafe_deserialize(_models.ErrorResponseCommonV2, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if response.status_code == 200: - deserialized = self._deserialize("DataCollectionRuleResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("DataCollectionRuleResource", pipeline_response) + deserialized = self._deserialize("DataCollectionRuleResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionRules/{dataCollectionRuleName}" - } - @overload def update( self, @@ -681,7 +646,6 @@ def update( :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: DataCollectionRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_06_01.models.DataCollectionRuleResource :raises ~azure.core.exceptions.HttpResponseError: @@ -692,7 +656,7 @@ def update( self, resource_group_name: str, data_collection_rule_name: str, - body: Optional[IO] = None, + body: Optional[IO[bytes]] = None, *, content_type: str = "application/json", **kwargs: Any @@ -708,11 +672,10 @@ def update( insensitive. Required. :type data_collection_rule_name: str :param body: The payload. Default value is None. - :type body: IO + :type body: 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: DataCollectionRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_06_01.models.DataCollectionRuleResource :raises ~azure.core.exceptions.HttpResponseError: @@ -723,7 +686,7 @@ def update( self, resource_group_name: str, data_collection_rule_name: str, - body: Optional[Union[_models.ResourceForUpdate, IO]] = None, + body: Optional[Union[_models.ResourceForUpdate, IO[bytes]]] = None, **kwargs: Any ) -> _models.DataCollectionRuleResource: """Updates part of a data collection rule. @@ -736,18 +699,14 @@ def update( :param data_collection_rule_name: The name of the data collection rule. The name is case insensitive. Required. :type data_collection_rule_name: str - :param body: The payload. Is either a ResourceForUpdate type or a IO type. Default value is - None. - :type body: ~azure.mgmt.monitor.v2022_06_01.models.ResourceForUpdate 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 + :param body: The payload. Is either a ResourceForUpdate type or a IO[bytes] type. Default value + is None. + :type body: ~azure.mgmt.monitor.v2022_06_01.models.ResourceForUpdate or IO[bytes] :return: DataCollectionRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_06_01.models.DataCollectionRuleResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -758,14 +717,14 @@ def update( _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", "2022-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-06-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.DataCollectionRuleResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(body, (IO, bytes)): + if isinstance(body, (IOBase, bytes)): _content = body else: if body is not None: @@ -773,7 +732,7 @@ def update( else: _json = None - request = build_update_request( + _request = build_update_request( resource_group_name=resource_group_name, data_collection_rule_name=data_collection_rule_name, subscription_id=self._config.subscription_id, @@ -781,16 +740,14 @@ def update( 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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -800,16 +757,12 @@ def update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponseCommonV2, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("DataCollectionRuleResource", pipeline_response) + deserialized = self._deserialize("DataCollectionRuleResource", 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.Insights/dataCollectionRules/{dataCollectionRuleName}" - } + return deserialized # type: ignore @distributed_trace def delete( # pylint: disable=inconsistent-return-statements @@ -825,12 +778,11 @@ def delete( # pylint: disable=inconsistent-return-statements :param data_collection_rule_name: The name of the data collection rule. The name is case insensitive. Required. :type data_collection_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, @@ -841,24 +793,22 @@ def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-06-01")) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, data_collection_rule_name=data_collection_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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -869,8 +819,4 @@ def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionRules/{dataCollectionRuleName}" - } + return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_08_01_preview/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_08_01_preview/__init__.py index 2c7733bfd566..42cc62301757 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_08_01_preview/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_08_01_preview/__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 ._monitor_management_client import MonitorManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._monitor_management_client import MonitorManagementClient # type: ignore from ._version import VERSION __version__ = VERSION try: from ._patch import __all__ as _patch_all - from ._patch import * # 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__ = [ "MonitorManagementClient", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_08_01_preview/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_08_01_preview/_configuration.py index d1bf2062b24c..a093853b3632 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_08_01_preview/_configuration.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_08_01_preview/_configuration.py @@ -8,18 +8,16 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy from ._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MonitorManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class MonitorManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for MonitorManagementClient. Note that all parameters used to create this instance are saved as instance @@ -35,7 +33,6 @@ class MonitorManagementClientConfiguration(Configuration): # pylint: disable=to """ def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: - super(MonitorManagementClientConfiguration, self).__init__(**kwargs) api_version: str = kwargs.pop("api_version", "2022-08-01-preview") if credential is None: @@ -48,6 +45,7 @@ def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-monitor/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -56,9 +54,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.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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_08_01_preview/_metadata.json b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_08_01_preview/_metadata.json index c6ef20d862a8..7d3d9ea77a8c 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_08_01_preview/_metadata.json +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_08_01_preview/_metadata.json @@ -8,10 +8,10 @@ "host_value": "\"https://management.azure.com\"", "parameterized_host_template": null, "azure_arm": true, - "has_lro_operations": false, + "has_public_lro_operations": false, "client_side_validation": false, - "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"sdkcore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMAutoResourceProviderRegistrationPolicy\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}, \"stdlib\": {\"typing_extensions\": [\"Self\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"sdkcore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"AsyncARMAutoResourceProviderRegistrationPolicy\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}, \"stdlib\": {\"typing_extensions\": [\"Self\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "global_parameters": { "sync": { @@ -101,8 +101,8 @@ "credential_scopes": ["https://management.azure.com/.default"], "credential_call_sync": "ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", "credential_call_async": "AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", - "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "sync_imports": "{\"regular\": {\"sdkcore\": {\"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"regular\": {\"sdkcore\": {\"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "operation_groups": { "scheduled_query_rules": "ScheduledQueryRulesOperations" diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_08_01_preview/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_08_01_preview/_monitor_management_client.py index 8d9eabf0b3ee..8dca60974b69 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_08_01_preview/_monitor_management_client.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_08_01_preview/_monitor_management_client.py @@ -8,9 +8,12 @@ from copy import deepcopy from typing import Any, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient +from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy from . import models as _models from .._serialization import Deserializer, Serializer @@ -18,11 +21,10 @@ from .operations import ScheduledQueryRulesOperations if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MonitorManagementClient: # pylint: disable=client-accepts-api-version-keyword +class MonitorManagementClient: """Monitor Management Client. :ivar scheduled_query_rules: ScheduledQueryRulesOperations operations @@ -49,17 +51,35 @@ def __init__( self._config = MonitorManagementClientConfiguration( credential=credential, subscription_id=subscription_id, **kwargs ) - self._client: ARMPipelineClient = ARMPipelineClient(base_url=base_url, config=self._config, **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), + 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=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.scheduled_query_rules = ScheduledQueryRulesOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2022-08-01-preview" ) - 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 @@ -79,12 +99,12 @@ 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) -> None: self._client.close() - def __enter__(self) -> "MonitorManagementClient": + def __enter__(self) -> Self: self._client.__enter__() return self diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_08_01_preview/_vendor.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_08_01_preview/_vendor.py deleted file mode 100644 index bd0df84f5319..000000000000 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_08_01_preview/_vendor.py +++ /dev/null @@ -1,30 +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 typing import List, cast - -from azure.core.pipeline.transport import HttpRequest - - -def _convert_request(request, files=None): - data = request.content if not files else None - request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) - if files: - request.set_formdata_body(files) - return request - - -def _format_url_section(template, **kwargs): - components = template.split("/") - while components: - try: - return template.format(**kwargs) - except KeyError as key: - # Need the cast, as for some reasons "split" is typed as list[str | Any] - formatted_components = cast(List[str], template.split("/")) - components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] - template = "/".join(components) diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_08_01_preview/_version.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_08_01_preview/_version.py index 394ee7c0c03c..e5754a47ce68 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_08_01_preview/_version.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_08_01_preview/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "6.0.2" +VERSION = "1.0.0b1" diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_08_01_preview/aio/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_08_01_preview/aio/__init__.py index 2c151bb41c19..3df30ff42149 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_08_01_preview/aio/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_08_01_preview/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 ._monitor_management_client import MonitorManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._monitor_management_client import MonitorManagementClient # type: ignore try: from ._patch import __all__ as _patch_all - from ._patch import * # 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__ = [ "MonitorManagementClient", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_08_01_preview/aio/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_08_01_preview/aio/_configuration.py index 3a679591e323..6e071ecded71 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_08_01_preview/aio/_configuration.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_08_01_preview/aio/_configuration.py @@ -8,18 +8,16 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy from .._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MonitorManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class MonitorManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for MonitorManagementClient. Note that all parameters used to create this instance are saved as instance @@ -35,7 +33,6 @@ class MonitorManagementClientConfiguration(Configuration): # pylint: disable=to """ def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: - super(MonitorManagementClientConfiguration, self).__init__(**kwargs) api_version: str = kwargs.pop("api_version", "2022-08-01-preview") if credential is None: @@ -48,6 +45,7 @@ def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **k self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-monitor/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -56,9 +54,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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_08_01_preview/aio/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_08_01_preview/aio/_monitor_management_client.py index 927cae76b99e..cfbd4262615c 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_08_01_preview/aio/_monitor_management_client.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_08_01_preview/aio/_monitor_management_client.py @@ -8,9 +8,12 @@ from copy import deepcopy from typing import Any, Awaitable, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient +from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy from .. import models as _models from ..._serialization import Deserializer, Serializer @@ -18,11 +21,10 @@ from .operations import ScheduledQueryRulesOperations if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MonitorManagementClient: # pylint: disable=client-accepts-api-version-keyword +class MonitorManagementClient: """Monitor Management Client. :ivar scheduled_query_rules: ScheduledQueryRulesOperations operations @@ -49,17 +51,37 @@ def __init__( self._config = MonitorManagementClientConfiguration( credential=credential, subscription_id=subscription_id, **kwargs ) - self._client: AsyncARMPipelineClient = AsyncARMPipelineClient(base_url=base_url, config=self._config, **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=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.scheduled_query_rules = ScheduledQueryRulesOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2022-08-01-preview" ) - 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 @@ -79,12 +101,12 @@ 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) -> "MonitorManagementClient": + async def __aenter__(self) -> Self: await self._client.__aenter__() return self diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_08_01_preview/aio/operations/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_08_01_preview/aio/operations/__init__.py index e010c281d4fc..795e91ef6843 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_08_01_preview/aio/operations/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_08_01_preview/aio/operations/__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 ._scheduled_query_rules_operations import ScheduledQueryRulesOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._scheduled_query_rules_operations import ScheduledQueryRulesOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ "ScheduledQueryRulesOperations", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_08_01_preview/aio/operations/_scheduled_query_rules_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_08_01_preview/aio/operations/_scheduled_query_rules_operations.py index 3118e7bc5af8..d0308b7dbe3b 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_08_01_preview/aio/operations/_scheduled_query_rules_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_08_01_preview/aio/operations/_scheduled_query_rules_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload import urllib.parse @@ -19,15 +20,13 @@ 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 ...operations._scheduled_query_rules_operations import ( build_create_or_update_request, build_delete_request, @@ -37,6 +36,10 @@ build_update_request, ) +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -59,12 +62,13 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.ScheduledQueryRuleResource"]: + # pylint: disable=line-too-long """Retrieve a scheduled query rule definitions in a subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ScheduledQueryRuleResource or the result of cls(response) :rtype: @@ -74,10 +78,12 @@ def list_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.Schedule _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2022-08-01-preview") + ) cls: ClsType[_models.ScheduledQueryRuleResourceCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -88,15 +94,13 @@ def list_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.Schedule def prepare_request(next_link=None): if not next_link: - request = build_list_by_subscription_request( + _request = build_list_by_subscription_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_subscription.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -107,14 +111,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("ScheduledQueryRuleResourceCollection", pipeline_response) @@ -124,11 +127,11 @@ async def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -141,20 +144,16 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_by_subscription.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/scheduledQueryRules" - } - @distributed_trace def list_by_resource_group( self, resource_group_name: str, **kwargs: Any ) -> AsyncIterable["_models.ScheduledQueryRuleResource"]: + # pylint: disable=line-too-long """Retrieve scheduled query rule definitions in a resource group. :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ScheduledQueryRuleResource or the result of cls(response) :rtype: @@ -164,10 +163,12 @@ def list_by_resource_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2022-08-01-preview") + ) cls: ClsType[_models.ScheduledQueryRuleResourceCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -178,16 +179,14 @@ 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_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -198,14 +197,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("ScheduledQueryRuleResourceCollection", pipeline_response) @@ -215,11 +213,11 @@ async def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -232,10 +230,6 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/scheduledQueryRules" - } - @distributed_trace_async async def get(self, resource_group_name: str, rule_name: str, **kwargs: Any) -> _models.ScheduledQueryRuleResource: """Retrieve an scheduled query rule definition. @@ -245,12 +239,11 @@ async def get(self, resource_group_name: str, rule_name: str, **kwargs: Any) -> :type resource_group_name: str :param rule_name: The name of the rule. Required. :type rule_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ScheduledQueryRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_08_01_preview.models.ScheduledQueryRuleResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -261,24 +254,24 @@ async def get(self, resource_group_name: str, rule_name: str, **kwargs: Any) -> _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2022-08-01-preview") + ) cls: ClsType[_models.ScheduledQueryRuleResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, rule_name=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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -288,16 +281,12 @@ async def get(self, resource_group_name: str, rule_name: str, **kwargs: Any) -> error = self._deserialize.failsafe_deserialize(_models.ErrorContract, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ScheduledQueryRuleResource", pipeline_response) + deserialized = self._deserialize("ScheduledQueryRuleResource", 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.Insights/scheduledQueryRules/{ruleName}" - } + return deserialized # type: ignore @overload async def create_or_update( @@ -321,7 +310,6 @@ async def create_or_update( :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: ScheduledQueryRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_08_01_preview.models.ScheduledQueryRuleResource :raises ~azure.core.exceptions.HttpResponseError: @@ -332,7 +320,7 @@ async def create_or_update( self, resource_group_name: str, rule_name: str, - parameters: IO, + parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -345,11 +333,10 @@ async def create_or_update( :param rule_name: The name of the rule. Required. :type rule_name: str :param parameters: The parameters of the rule to create or update. Required. - :type parameters: IO + :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: ScheduledQueryRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_08_01_preview.models.ScheduledQueryRuleResource :raises ~azure.core.exceptions.HttpResponseError: @@ -360,7 +347,7 @@ async def create_or_update( self, resource_group_name: str, rule_name: str, - parameters: Union[_models.ScheduledQueryRuleResource, IO], + parameters: Union[_models.ScheduledQueryRuleResource, IO[bytes]], **kwargs: Any ) -> _models.ScheduledQueryRuleResource: """Creates or updates a scheduled query rule. @@ -371,18 +358,14 @@ async def create_or_update( :param rule_name: The name of the rule. Required. :type rule_name: str :param parameters: The parameters of the rule to create or update. Is either a - ScheduledQueryRuleResource type or a IO type. Required. + ScheduledQueryRuleResource type or a IO[bytes] type. Required. :type parameters: ~azure.mgmt.monitor.v2022_08_01_preview.models.ScheduledQueryRuleResource 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 + IO[bytes] :return: ScheduledQueryRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_08_01_preview.models.ScheduledQueryRuleResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -393,19 +376,21 @@ async def create_or_update( _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", "2022-08-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2022-08-01-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ScheduledQueryRuleResource] = 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, "ScheduledQueryRuleResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, rule_name=rule_name, subscription_id=self._config.subscription_id, @@ -413,16 +398,14 @@ async def create_or_update( 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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -432,21 +415,13 @@ async def create_or_update( error = self._deserialize.failsafe_deserialize(_models.ErrorContract, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if response.status_code == 200: - deserialized = self._deserialize("ScheduledQueryRuleResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("ScheduledQueryRuleResource", pipeline_response) + deserialized = self._deserialize("ScheduledQueryRuleResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/scheduledQueryRules/{ruleName}" - } - @overload async def update( self, @@ -470,7 +445,6 @@ async def update( :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: ScheduledQueryRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_08_01_preview.models.ScheduledQueryRuleResource :raises ~azure.core.exceptions.HttpResponseError: @@ -481,7 +455,7 @@ async def update( self, resource_group_name: str, rule_name: str, - parameters: IO, + parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -494,11 +468,10 @@ async def update( :param rule_name: The name of the rule. Required. :type rule_name: str :param parameters: The parameters of the rule to update. Required. - :type parameters: IO + :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: ScheduledQueryRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_08_01_preview.models.ScheduledQueryRuleResource :raises ~azure.core.exceptions.HttpResponseError: @@ -509,7 +482,7 @@ async def update( self, resource_group_name: str, rule_name: str, - parameters: Union[_models.ScheduledQueryRuleResourcePatch, IO], + parameters: Union[_models.ScheduledQueryRuleResourcePatch, IO[bytes]], **kwargs: Any ) -> _models.ScheduledQueryRuleResource: """Update a scheduled query rule. @@ -520,18 +493,14 @@ async def update( :param rule_name: The name of the rule. Required. :type rule_name: str :param parameters: The parameters of the rule to update. Is either a - ScheduledQueryRuleResourcePatch type or a IO type. Required. + ScheduledQueryRuleResourcePatch type or a IO[bytes] type. Required. :type parameters: - ~azure.mgmt.monitor.v2022_08_01_preview.models.ScheduledQueryRuleResourcePatch 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 + ~azure.mgmt.monitor.v2022_08_01_preview.models.ScheduledQueryRuleResourcePatch or IO[bytes] :return: ScheduledQueryRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_08_01_preview.models.ScheduledQueryRuleResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -542,19 +511,21 @@ async def update( _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", "2022-08-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2022-08-01-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ScheduledQueryRuleResource] = 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, "ScheduledQueryRuleResourcePatch") - request = build_update_request( + _request = build_update_request( resource_group_name=resource_group_name, rule_name=rule_name, subscription_id=self._config.subscription_id, @@ -562,16 +533,14 @@ async def update( 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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -581,21 +550,15 @@ async def update( error = self._deserialize.failsafe_deserialize(_models.ErrorContract, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ScheduledQueryRuleResource", pipeline_response) + deserialized = self._deserialize("ScheduledQueryRuleResource", 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.Insights/scheduledQueryRules/{ruleName}" - } + return deserialized # type: ignore @distributed_trace_async - async def delete( # pylint: disable=inconsistent-return-statements - self, resource_group_name: str, rule_name: str, **kwargs: Any - ) -> None: + async def delete(self, resource_group_name: str, rule_name: str, **kwargs: Any) -> None: """Deletes a scheduled query rule. :param resource_group_name: The name of the resource group. The name is case insensitive. @@ -603,12 +566,11 @@ async def delete( # pylint: disable=inconsistent-return-statements :type resource_group_name: str :param rule_name: The name of the rule. Required. :type 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, @@ -619,24 +581,24 @@ async def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2022-08-01-preview") + ) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, rule_name=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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -647,8 +609,4 @@ async def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/scheduledQueryRules/{ruleName}" - } + return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_08_01_preview/models/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_08_01_preview/models/__init__.py index 2fbbffcd5469..8e0a811f16bb 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_08_01_preview/models/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_08_01_preview/models/__init__.py @@ -5,33 +5,44 @@ # 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 Actions -from ._models_py3 import Condition -from ._models_py3 import ConditionFailingPeriods -from ._models_py3 import Dimension -from ._models_py3 import ErrorContract -from ._models_py3 import ErrorResponseAdditionalInfo -from ._models_py3 import ErrorResponseDetails -from ._models_py3 import Identity -from ._models_py3 import RuleResolveConfiguration -from ._models_py3 import ScheduledQueryRuleCriteria -from ._models_py3 import ScheduledQueryRuleResource -from ._models_py3 import ScheduledQueryRuleResourceCollection -from ._models_py3 import ScheduledQueryRuleResourcePatch -from ._models_py3 import SystemData -from ._models_py3 import UserIdentityProperties +from typing import TYPE_CHECKING -from ._monitor_management_client_enums import AlertSeverity -from ._monitor_management_client_enums import ConditionOperator -from ._monitor_management_client_enums import CreatedByType -from ._monitor_management_client_enums import DimensionOperator -from ._monitor_management_client_enums import IdentityType -from ._monitor_management_client_enums import Kind -from ._monitor_management_client_enums import PublicNetworkAccess -from ._monitor_management_client_enums import TimeAggregation +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models_py3 import ( # type: ignore + Actions, + Condition, + ConditionFailingPeriods, + Dimension, + ErrorContract, + ErrorResponseAdditionalInfo, + ErrorResponseDetails, + Identity, + RuleResolveConfiguration, + ScheduledQueryRuleCriteria, + ScheduledQueryRuleResource, + ScheduledQueryRuleResourceCollection, + ScheduledQueryRuleResourcePatch, + SystemData, + UserIdentityProperties, +) + +from ._monitor_management_client_enums import ( # type: ignore + AlertSeverity, + ConditionOperator, + CreatedByType, + DimensionOperator, + IdentityType, + Kind, + PublicNetworkAccess, + TimeAggregation, +) from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ @@ -59,5 +70,5 @@ "PublicNetworkAccess", "TimeAggregation", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_08_01_preview/models/_models_py3.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_08_01_preview/models/_models_py3.py index 8d9bb334bf54..ce63464b0ca7 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_08_01_preview/models/_models_py3.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_08_01_preview/models/_models_py3.py @@ -1,5 +1,5 @@ -# coding=utf-8 # 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. @@ -13,7 +13,6 @@ from ... import _serialization if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from .. import models as _models @@ -188,7 +187,7 @@ def __init__( class Dimension(_serialization.Model): """Dimension splitting and filtering definition. - 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: Name of the dimension. Required. :vartype name: str @@ -327,7 +326,7 @@ class Identity(_serialization.Model): 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 principal_id: The principal ID of resource identity. :vartype principal_id: str @@ -338,7 +337,7 @@ class Identity(_serialization.Model): :vartype type: str or ~azure.mgmt.monitor.v2022_08_01_preview.models.IdentityType :ivar user_assigned_identities: The list of user identities associated with the resource. The user identity dictionary key references will be ARM resource ids in the form: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'. + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'. # pylint: disable=line-too-long :vartype user_assigned_identities: dict[str, ~azure.mgmt.monitor.v2022_08_01_preview.models.UserIdentityProperties] """ @@ -369,7 +368,7 @@ def __init__( :paramtype type: str or ~azure.mgmt.monitor.v2022_08_01_preview.models.IdentityType :keyword user_assigned_identities: The list of user identities associated with the resource. The user identity dictionary key references will be ARM resource ids in the form: - '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'. + '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'. # pylint: disable=line-too-long :paramtype user_assigned_identities: dict[str, ~azure.mgmt.monitor.v2022_08_01_preview.models.UserIdentityProperties] """ @@ -434,15 +433,15 @@ def __init__(self, *, all_of: Optional[List["_models.Condition"]] = None, **kwar self.all_of = all_of -class ScheduledQueryRuleResource(_serialization.Model): # pylint: disable=too-many-instance-attributes +class ScheduledQueryRuleResource(_serialization.Model): """The scheduled query rule 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: Fully qualified resource ID for the resource. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long :vartype id: str :ivar name: The name of the resource. :vartype name: str @@ -522,9 +521,9 @@ class ScheduledQueryRuleResource(_serialization.Model): # pylint: disable=too-m :ivar auto_mitigate: The flag that indicates whether the alert should be automatically resolved or not. The default is true. Relevant only for rules of the kind LogAlert. :vartype auto_mitigate: bool - :ivar rule_resolve_configuration: Defines the configuration for resolving fired alerts. - Relevant only for rules of the kind LogAlert. - :vartype rule_resolve_configuration: + :ivar resolve_configuration: Defines the configuration for resolving fired alerts. Relevant + only for rules of the kind LogAlert. + :vartype resolve_configuration: ~azure.mgmt.monitor.v2022_08_01_preview.models.RuleResolveConfiguration """ @@ -575,10 +574,7 @@ class ScheduledQueryRuleResource(_serialization.Model): # pylint: disable=too-m }, "skip_query_validation": {"key": "properties.skipQueryValidation", "type": "bool"}, "auto_mitigate": {"key": "properties.autoMitigate", "type": "bool"}, - "rule_resolve_configuration": { - "key": "properties.ruleResolveConfiguration", - "type": "RuleResolveConfiguration", - }, + "resolve_configuration": {"key": "properties.resolveConfiguration", "type": "RuleResolveConfiguration"}, } def __init__( # pylint: disable=too-many-locals @@ -604,7 +600,7 @@ def __init__( # pylint: disable=too-many-locals check_workspace_alerts_storage_configured: Optional[bool] = None, skip_query_validation: Optional[bool] = None, auto_mitigate: Optional[bool] = None, - rule_resolve_configuration: Optional["_models.RuleResolveConfiguration"] = None, + resolve_configuration: Optional["_models.RuleResolveConfiguration"] = None, **kwargs: Any ) -> None: """ @@ -666,9 +662,9 @@ def __init__( # pylint: disable=too-many-locals :keyword auto_mitigate: The flag that indicates whether the alert should be automatically resolved or not. The default is true. Relevant only for rules of the kind LogAlert. :paramtype auto_mitigate: bool - :keyword rule_resolve_configuration: Defines the configuration for resolving fired alerts. - Relevant only for rules of the kind LogAlert. - :paramtype rule_resolve_configuration: + :keyword resolve_configuration: Defines the configuration for resolving fired alerts. Relevant + only for rules of the kind LogAlert. + :paramtype resolve_configuration: ~azure.mgmt.monitor.v2022_08_01_preview.models.RuleResolveConfiguration """ super().__init__(**kwargs) @@ -700,7 +696,7 @@ def __init__( # pylint: disable=too-many-locals self.check_workspace_alerts_storage_configured = check_workspace_alerts_storage_configured self.skip_query_validation = skip_query_validation self.auto_mitigate = auto_mitigate - self.rule_resolve_configuration = rule_resolve_configuration + self.resolve_configuration = resolve_configuration class ScheduledQueryRuleResourceCollection(_serialization.Model): @@ -734,7 +730,7 @@ def __init__(self, *, value: Optional[List["_models.ScheduledQueryRuleResource"] self.next_link = None -class ScheduledQueryRuleResourcePatch(_serialization.Model): # pylint: disable=too-many-instance-attributes +class ScheduledQueryRuleResourcePatch(_serialization.Model): """The scheduled query rule resource for patch operations. Variables are only populated by the server, and will be ignored when sending a request. @@ -799,9 +795,9 @@ class ScheduledQueryRuleResourcePatch(_serialization.Model): # pylint: disable= :ivar auto_mitigate: The flag that indicates whether the alert should be automatically resolved or not. The default is true. Relevant only for rules of the kind LogAlert. :vartype auto_mitigate: bool - :ivar rule_resolve_configuration: Defines the configuration for resolving fired alerts. - Relevant only for rules of the kind LogAlert. - :vartype rule_resolve_configuration: + :ivar resolve_configuration: Defines the configuration for resolving fired alerts. Relevant + only for rules of the kind LogAlert. + :vartype resolve_configuration: ~azure.mgmt.monitor.v2022_08_01_preview.models.RuleResolveConfiguration """ @@ -839,10 +835,7 @@ class ScheduledQueryRuleResourcePatch(_serialization.Model): # pylint: disable= }, "skip_query_validation": {"key": "properties.skipQueryValidation", "type": "bool"}, "auto_mitigate": {"key": "properties.autoMitigate", "type": "bool"}, - "rule_resolve_configuration": { - "key": "properties.ruleResolveConfiguration", - "type": "RuleResolveConfiguration", - }, + "resolve_configuration": {"key": "properties.resolveConfiguration", "type": "RuleResolveConfiguration"}, } def __init__( @@ -866,7 +859,7 @@ def __init__( check_workspace_alerts_storage_configured: Optional[bool] = None, skip_query_validation: Optional[bool] = None, auto_mitigate: Optional[bool] = None, - rule_resolve_configuration: Optional["_models.RuleResolveConfiguration"] = None, + resolve_configuration: Optional["_models.RuleResolveConfiguration"] = None, **kwargs: Any ) -> None: """ @@ -923,9 +916,9 @@ def __init__( :keyword auto_mitigate: The flag that indicates whether the alert should be automatically resolved or not. The default is true. Relevant only for rules of the kind LogAlert. :paramtype auto_mitigate: bool - :keyword rule_resolve_configuration: Defines the configuration for resolving fired alerts. - Relevant only for rules of the kind LogAlert. - :paramtype rule_resolve_configuration: + :keyword resolve_configuration: Defines the configuration for resolving fired alerts. Relevant + only for rules of the kind LogAlert. + :paramtype resolve_configuration: ~azure.mgmt.monitor.v2022_08_01_preview.models.RuleResolveConfiguration """ super().__init__(**kwargs) @@ -950,7 +943,7 @@ def __init__( self.check_workspace_alerts_storage_configured = check_workspace_alerts_storage_configured self.skip_query_validation = skip_query_validation self.auto_mitigate = auto_mitigate - self.rule_resolve_configuration = rule_resolve_configuration + self.resolve_configuration = resolve_configuration class SystemData(_serialization.Model): diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_08_01_preview/operations/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_08_01_preview/operations/__init__.py index e010c281d4fc..795e91ef6843 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_08_01_preview/operations/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_08_01_preview/operations/__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 ._scheduled_query_rules_operations import ScheduledQueryRulesOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._scheduled_query_rules_operations import ScheduledQueryRulesOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ "ScheduledQueryRulesOperations", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_08_01_preview/operations/_scheduled_query_rules_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_08_01_preview/operations/_scheduled_query_rules_operations.py index 0cd8c1d54760..a8aa36db9007 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_08_01_preview/operations/_scheduled_query_rules_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_08_01_preview/operations/_scheduled_query_rules_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload import urllib.parse @@ -19,16 +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, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -51,7 +54,7 @@ def build_list_by_subscription_request(subscription_id: str, **kwargs: Any) -> H "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -81,7 +84,7 @@ def build_list_by_resource_group_request(resource_group_name: str, subscription_ ), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -109,10 +112,10 @@ def build_get_request(resource_group_name: str, rule_name: str, subscription_id: "resourceGroupName": _SERIALIZER.url( "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 ), - "ruleName": _SERIALIZER.url("rule_name", rule_name, "str"), + "ruleName": _SERIALIZER.url("rule_name", rule_name, "str", pattern=r"^[^#<>%&:\?/{}*]{1,260}$"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -143,10 +146,10 @@ def build_create_or_update_request( "resourceGroupName": _SERIALIZER.url( "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 ), - "ruleName": _SERIALIZER.url("rule_name", rule_name, "str"), + "ruleName": _SERIALIZER.url("rule_name", rule_name, "str", pattern=r"^[^#<>%&:\?/{}*]{1,260}$"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -177,10 +180,10 @@ def build_update_request(resource_group_name: str, rule_name: str, subscription_ "resourceGroupName": _SERIALIZER.url( "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 ), - "ruleName": _SERIALIZER.url("rule_name", rule_name, "str"), + "ruleName": _SERIALIZER.url("rule_name", rule_name, "str", pattern=r"^[^#<>%&:\?/{}*]{1,260}$"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -210,10 +213,10 @@ def build_delete_request(resource_group_name: str, rule_name: str, subscription_ "resourceGroupName": _SERIALIZER.url( "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 ), - "ruleName": _SERIALIZER.url("rule_name", rule_name, "str"), + "ruleName": _SERIALIZER.url("rule_name", rule_name, "str", pattern=r"^[^#<>%&:\?/{}*]{1,260}$"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -242,12 +245,12 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list_by_subscription(self, **kwargs: Any) -> Iterable["_models.ScheduledQueryRuleResource"]: """Retrieve a scheduled query rule definitions in a subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ScheduledQueryRuleResource or the result of cls(response) :rtype: @@ -257,10 +260,12 @@ def list_by_subscription(self, **kwargs: Any) -> Iterable["_models.ScheduledQuer _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2022-08-01-preview") + ) cls: ClsType[_models.ScheduledQueryRuleResourceCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -271,15 +276,13 @@ def list_by_subscription(self, **kwargs: Any) -> Iterable["_models.ScheduledQuer def prepare_request(next_link=None): if not next_link: - request = build_list_by_subscription_request( + _request = build_list_by_subscription_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_subscription.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -290,14 +293,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("ScheduledQueryRuleResourceCollection", pipeline_response) @@ -307,11 +309,11 @@ def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -324,10 +326,6 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_by_subscription.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/scheduledQueryRules" - } - @distributed_trace def list_by_resource_group( self, resource_group_name: str, **kwargs: Any @@ -337,7 +335,6 @@ def list_by_resource_group( :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ScheduledQueryRuleResource or the result of cls(response) :rtype: @@ -347,10 +344,12 @@ def list_by_resource_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2022-08-01-preview") + ) cls: ClsType[_models.ScheduledQueryRuleResourceCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -361,16 +360,14 @@ 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_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -381,14 +378,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("ScheduledQueryRuleResourceCollection", pipeline_response) @@ -398,11 +394,11 @@ def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -415,10 +411,6 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/scheduledQueryRules" - } - @distributed_trace def get(self, resource_group_name: str, rule_name: str, **kwargs: Any) -> _models.ScheduledQueryRuleResource: """Retrieve an scheduled query rule definition. @@ -428,12 +420,11 @@ def get(self, resource_group_name: str, rule_name: str, **kwargs: Any) -> _model :type resource_group_name: str :param rule_name: The name of the rule. Required. :type rule_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ScheduledQueryRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_08_01_preview.models.ScheduledQueryRuleResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -444,24 +435,24 @@ def get(self, resource_group_name: str, rule_name: str, **kwargs: Any) -> _model _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2022-08-01-preview") + ) cls: ClsType[_models.ScheduledQueryRuleResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, rule_name=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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -471,16 +462,12 @@ def get(self, resource_group_name: str, rule_name: str, **kwargs: Any) -> _model error = self._deserialize.failsafe_deserialize(_models.ErrorContract, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ScheduledQueryRuleResource", pipeline_response) + deserialized = self._deserialize("ScheduledQueryRuleResource", 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.Insights/scheduledQueryRules/{ruleName}" - } + return deserialized # type: ignore @overload def create_or_update( @@ -504,7 +491,6 @@ def create_or_update( :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: ScheduledQueryRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_08_01_preview.models.ScheduledQueryRuleResource :raises ~azure.core.exceptions.HttpResponseError: @@ -515,7 +501,7 @@ def create_or_update( self, resource_group_name: str, rule_name: str, - parameters: IO, + parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -528,11 +514,10 @@ def create_or_update( :param rule_name: The name of the rule. Required. :type rule_name: str :param parameters: The parameters of the rule to create or update. Required. - :type parameters: IO + :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: ScheduledQueryRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_08_01_preview.models.ScheduledQueryRuleResource :raises ~azure.core.exceptions.HttpResponseError: @@ -543,7 +528,7 @@ def create_or_update( self, resource_group_name: str, rule_name: str, - parameters: Union[_models.ScheduledQueryRuleResource, IO], + parameters: Union[_models.ScheduledQueryRuleResource, IO[bytes]], **kwargs: Any ) -> _models.ScheduledQueryRuleResource: """Creates or updates a scheduled query rule. @@ -554,18 +539,14 @@ def create_or_update( :param rule_name: The name of the rule. Required. :type rule_name: str :param parameters: The parameters of the rule to create or update. Is either a - ScheduledQueryRuleResource type or a IO type. Required. + ScheduledQueryRuleResource type or a IO[bytes] type. Required. :type parameters: ~azure.mgmt.monitor.v2022_08_01_preview.models.ScheduledQueryRuleResource 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 + IO[bytes] :return: ScheduledQueryRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_08_01_preview.models.ScheduledQueryRuleResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -576,19 +557,21 @@ def create_or_update( _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", "2022-08-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2022-08-01-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ScheduledQueryRuleResource] = 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, "ScheduledQueryRuleResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, rule_name=rule_name, subscription_id=self._config.subscription_id, @@ -596,16 +579,14 @@ def create_or_update( 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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -615,21 +596,13 @@ def create_or_update( error = self._deserialize.failsafe_deserialize(_models.ErrorContract, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if response.status_code == 200: - deserialized = self._deserialize("ScheduledQueryRuleResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("ScheduledQueryRuleResource", pipeline_response) + deserialized = self._deserialize("ScheduledQueryRuleResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/scheduledQueryRules/{ruleName}" - } - @overload def update( self, @@ -653,7 +626,6 @@ def update( :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: ScheduledQueryRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_08_01_preview.models.ScheduledQueryRuleResource :raises ~azure.core.exceptions.HttpResponseError: @@ -664,7 +636,7 @@ def update( self, resource_group_name: str, rule_name: str, - parameters: IO, + parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -677,11 +649,10 @@ def update( :param rule_name: The name of the rule. Required. :type rule_name: str :param parameters: The parameters of the rule to update. Required. - :type parameters: IO + :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: ScheduledQueryRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_08_01_preview.models.ScheduledQueryRuleResource :raises ~azure.core.exceptions.HttpResponseError: @@ -692,7 +663,7 @@ def update( self, resource_group_name: str, rule_name: str, - parameters: Union[_models.ScheduledQueryRuleResourcePatch, IO], + parameters: Union[_models.ScheduledQueryRuleResourcePatch, IO[bytes]], **kwargs: Any ) -> _models.ScheduledQueryRuleResource: """Update a scheduled query rule. @@ -703,18 +674,14 @@ def update( :param rule_name: The name of the rule. Required. :type rule_name: str :param parameters: The parameters of the rule to update. Is either a - ScheduledQueryRuleResourcePatch type or a IO type. Required. + ScheduledQueryRuleResourcePatch type or a IO[bytes] type. Required. :type parameters: - ~azure.mgmt.monitor.v2022_08_01_preview.models.ScheduledQueryRuleResourcePatch 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 + ~azure.mgmt.monitor.v2022_08_01_preview.models.ScheduledQueryRuleResourcePatch or IO[bytes] :return: ScheduledQueryRuleResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_08_01_preview.models.ScheduledQueryRuleResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -725,19 +692,21 @@ def update( _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", "2022-08-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2022-08-01-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ScheduledQueryRuleResource] = 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, "ScheduledQueryRuleResourcePatch") - request = build_update_request( + _request = build_update_request( resource_group_name=resource_group_name, rule_name=rule_name, subscription_id=self._config.subscription_id, @@ -745,16 +714,14 @@ def update( 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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -764,16 +731,12 @@ def update( error = self._deserialize.failsafe_deserialize(_models.ErrorContract, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ScheduledQueryRuleResource", pipeline_response) + deserialized = self._deserialize("ScheduledQueryRuleResource", 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.Insights/scheduledQueryRules/{ruleName}" - } + return deserialized # type: ignore @distributed_trace def delete( # pylint: disable=inconsistent-return-statements @@ -786,12 +749,11 @@ def delete( # pylint: disable=inconsistent-return-statements :type resource_group_name: str :param rule_name: The name of the rule. Required. :type 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, @@ -802,24 +764,24 @@ def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-08-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2022-08-01-preview") + ) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, rule_name=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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -830,8 +792,4 @@ def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/scheduledQueryRules/{ruleName}" - } + return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_10_01/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_10_01/__init__.py index 2c7733bfd566..42cc62301757 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_10_01/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_10_01/__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 ._monitor_management_client import MonitorManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._monitor_management_client import MonitorManagementClient # type: ignore from ._version import VERSION __version__ = VERSION try: from ._patch import __all__ as _patch_all - from ._patch import * # 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__ = [ "MonitorManagementClient", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_10_01/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_10_01/_configuration.py index a47c12c4834c..7cca20212c15 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_10_01/_configuration.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_10_01/_configuration.py @@ -8,18 +8,16 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy from ._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MonitorManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class MonitorManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for MonitorManagementClient. Note that all parameters used to create this instance are saved as instance @@ -35,7 +33,6 @@ class MonitorManagementClientConfiguration(Configuration): # pylint: disable=to """ def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: - super(MonitorManagementClientConfiguration, self).__init__(**kwargs) api_version: str = kwargs.pop("api_version", "2022-10-01") if credential is None: @@ -48,6 +45,7 @@ def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-monitor/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -56,9 +54,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.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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_10_01/_metadata.json b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_10_01/_metadata.json index 13f751ef148e..b8cd46b7b044 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_10_01/_metadata.json +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_10_01/_metadata.json @@ -8,10 +8,10 @@ "host_value": "\"https://management.azure.com\"", "parameterized_host_template": null, "azure_arm": true, - "has_lro_operations": false, + "has_public_lro_operations": false, "client_side_validation": false, - "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"sdkcore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMAutoResourceProviderRegistrationPolicy\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}, \"stdlib\": {\"typing_extensions\": [\"Self\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"sdkcore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"AsyncARMAutoResourceProviderRegistrationPolicy\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}, \"stdlib\": {\"typing_extensions\": [\"Self\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "global_parameters": { "sync": { @@ -101,8 +101,8 @@ "credential_scopes": ["https://management.azure.com/.default"], "credential_call_sync": "ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", "credential_call_async": "AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", - "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "sync_imports": "{\"regular\": {\"sdkcore\": {\"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"regular\": {\"sdkcore\": {\"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "operation_groups": { "autoscale_settings": "AutoscaleSettingsOperations", diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_10_01/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_10_01/_monitor_management_client.py index 1bb05affeb7e..807c6ce1f235 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_10_01/_monitor_management_client.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_10_01/_monitor_management_client.py @@ -8,9 +8,12 @@ from copy import deepcopy from typing import Any, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient +from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy from . import models as _models from .._serialization import Deserializer, Serializer @@ -18,11 +21,10 @@ from .operations import AutoscaleSettingsOperations, PredictiveMetricOperations if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MonitorManagementClient: # pylint: disable=client-accepts-api-version-keyword +class MonitorManagementClient: """Monitor Management Client. :ivar autoscale_settings: AutoscaleSettingsOperations operations @@ -52,20 +54,38 @@ def __init__( self._config = MonitorManagementClientConfiguration( credential=credential, subscription_id=subscription_id, **kwargs ) - self._client: ARMPipelineClient = ARMPipelineClient(base_url=base_url, config=self._config, **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), + 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=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.autoscale_settings = AutoscaleSettingsOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2022-10-01" ) self.predictive_metric = PredictiveMetricOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2022-10-01" ) - 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 @@ -85,12 +105,12 @@ 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) -> None: self._client.close() - def __enter__(self) -> "MonitorManagementClient": + def __enter__(self) -> Self: self._client.__enter__() return self diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_10_01/_vendor.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_10_01/_vendor.py deleted file mode 100644 index bd0df84f5319..000000000000 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_10_01/_vendor.py +++ /dev/null @@ -1,30 +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 typing import List, cast - -from azure.core.pipeline.transport import HttpRequest - - -def _convert_request(request, files=None): - data = request.content if not files else None - request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) - if files: - request.set_formdata_body(files) - return request - - -def _format_url_section(template, **kwargs): - components = template.split("/") - while components: - try: - return template.format(**kwargs) - except KeyError as key: - # Need the cast, as for some reasons "split" is typed as list[str | Any] - formatted_components = cast(List[str], template.split("/")) - components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] - template = "/".join(components) diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_10_01/_version.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_10_01/_version.py index 394ee7c0c03c..e5754a47ce68 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_10_01/_version.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_10_01/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "6.0.2" +VERSION = "1.0.0b1" diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_10_01/aio/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_10_01/aio/__init__.py index 2c151bb41c19..3df30ff42149 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_10_01/aio/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_10_01/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 ._monitor_management_client import MonitorManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._monitor_management_client import MonitorManagementClient # type: ignore try: from ._patch import __all__ as _patch_all - from ._patch import * # 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__ = [ "MonitorManagementClient", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_10_01/aio/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_10_01/aio/_configuration.py index a0bd7f0de702..96988a9a9163 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_10_01/aio/_configuration.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_10_01/aio/_configuration.py @@ -8,18 +8,16 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy from .._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MonitorManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class MonitorManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for MonitorManagementClient. Note that all parameters used to create this instance are saved as instance @@ -35,7 +33,6 @@ class MonitorManagementClientConfiguration(Configuration): # pylint: disable=to """ def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: - super(MonitorManagementClientConfiguration, self).__init__(**kwargs) api_version: str = kwargs.pop("api_version", "2022-10-01") if credential is None: @@ -48,6 +45,7 @@ def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **k self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-monitor/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -56,9 +54,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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_10_01/aio/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_10_01/aio/_monitor_management_client.py index 5e131d74b38e..ff96d34dd1c8 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_10_01/aio/_monitor_management_client.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_10_01/aio/_monitor_management_client.py @@ -8,9 +8,12 @@ from copy import deepcopy from typing import Any, Awaitable, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient +from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy from .. import models as _models from ..._serialization import Deserializer, Serializer @@ -18,11 +21,10 @@ from .operations import AutoscaleSettingsOperations, PredictiveMetricOperations if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MonitorManagementClient: # pylint: disable=client-accepts-api-version-keyword +class MonitorManagementClient: """Monitor Management Client. :ivar autoscale_settings: AutoscaleSettingsOperations operations @@ -52,20 +54,40 @@ def __init__( self._config = MonitorManagementClientConfiguration( credential=credential, subscription_id=subscription_id, **kwargs ) - self._client: AsyncARMPipelineClient = AsyncARMPipelineClient(base_url=base_url, config=self._config, **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=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.autoscale_settings = AutoscaleSettingsOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2022-10-01" ) self.predictive_metric = PredictiveMetricOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2022-10-01" ) - 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 @@ -85,12 +107,12 @@ 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) -> "MonitorManagementClient": + async def __aenter__(self) -> Self: await self._client.__aenter__() return self diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_10_01/aio/operations/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_10_01/aio/operations/__init__.py index 3d1ab289551f..e66d31251e99 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_10_01/aio/operations/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_10_01/aio/operations/__init__.py @@ -5,17 +5,23 @@ # 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 ._autoscale_settings_operations import AutoscaleSettingsOperations -from ._predictive_metric_operations import PredictiveMetricOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._autoscale_settings_operations import AutoscaleSettingsOperations # type: ignore +from ._predictive_metric_operations import PredictiveMetricOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ "AutoscaleSettingsOperations", "PredictiveMetricOperations", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_10_01/aio/operations/_autoscale_settings_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_10_01/aio/operations/_autoscale_settings_operations.py index b6db3e4214dc..5f65bd7fd4ae 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_10_01/aio/operations/_autoscale_settings_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_10_01/aio/operations/_autoscale_settings_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload import urllib.parse @@ -19,15 +20,13 @@ 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 ...operations._autoscale_settings_operations import ( build_create_or_update_request, build_delete_request, @@ -37,6 +36,10 @@ build_update_request, ) +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -59,6 +62,7 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list_by_resource_group( @@ -69,7 +73,6 @@ def list_by_resource_group( :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either AutoscaleSettingResource or the result of cls(response) :rtype: @@ -79,10 +82,10 @@ def list_by_resource_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-10-01")) cls: ClsType[_models.AutoscaleSettingResourceCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -93,16 +96,14 @@ 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_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -113,14 +114,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("AutoscaleSettingResourceCollection", pipeline_response) @@ -130,11 +130,11 @@ async def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -147,10 +147,6 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/autoscalesettings" - } - @overload async def create_or_update( self, @@ -173,7 +169,6 @@ async def create_or_update( :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: AutoscaleSettingResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_10_01.models.AutoscaleSettingResource :raises ~azure.core.exceptions.HttpResponseError: @@ -184,7 +179,7 @@ async def create_or_update( self, resource_group_name: str, autoscale_setting_name: str, - parameters: IO, + parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -197,11 +192,10 @@ async def create_or_update( :param autoscale_setting_name: The autoscale setting name. Required. :type autoscale_setting_name: str :param parameters: Parameters supplied to the operation. Required. - :type parameters: IO + :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: AutoscaleSettingResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_10_01.models.AutoscaleSettingResource :raises ~azure.core.exceptions.HttpResponseError: @@ -212,7 +206,7 @@ async def create_or_update( self, resource_group_name: str, autoscale_setting_name: str, - parameters: Union[_models.AutoscaleSettingResource, IO], + parameters: Union[_models.AutoscaleSettingResource, IO[bytes]], **kwargs: Any ) -> _models.AutoscaleSettingResource: """Creates or updates an autoscale setting. @@ -223,17 +217,13 @@ async def create_or_update( :param autoscale_setting_name: The autoscale setting name. Required. :type autoscale_setting_name: str :param parameters: Parameters supplied to the operation. Is either a AutoscaleSettingResource - type or a IO type. Required. - :type parameters: ~azure.mgmt.monitor.v2022_10_01.models.AutoscaleSettingResource 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 + type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.monitor.v2022_10_01.models.AutoscaleSettingResource or IO[bytes] :return: AutoscaleSettingResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_10_01.models.AutoscaleSettingResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -244,19 +234,19 @@ async def create_or_update( _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", "2022-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-10-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.AutoscaleSettingResource] = 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, "AutoscaleSettingResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, autoscale_setting_name=autoscale_setting_name, subscription_id=self._config.subscription_id, @@ -264,16 +254,14 @@ async def create_or_update( 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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -283,25 +271,15 @@ async def create_or_update( error = self._deserialize.failsafe_deserialize(_models.AutoscaleErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if response.status_code == 200: - deserialized = self._deserialize("AutoscaleSettingResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("AutoscaleSettingResource", pipeline_response) + deserialized = self._deserialize("AutoscaleSettingResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/autoscalesettings/{autoscaleSettingName}" - } - @distributed_trace_async - async def delete( # pylint: disable=inconsistent-return-statements - self, resource_group_name: str, autoscale_setting_name: str, **kwargs: Any - ) -> None: + async def delete(self, resource_group_name: str, autoscale_setting_name: str, **kwargs: Any) -> None: """Deletes and autoscale setting. :param resource_group_name: The name of the resource group. The name is case insensitive. @@ -309,12 +287,11 @@ async def delete( # pylint: disable=inconsistent-return-statements :type resource_group_name: str :param autoscale_setting_name: The autoscale setting name. Required. :type autoscale_setting_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, @@ -325,24 +302,22 @@ async def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-10-01")) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, autoscale_setting_name=autoscale_setting_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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -353,11 +328,7 @@ async def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/autoscalesettings/{autoscaleSettingName}" - } + return cls(pipeline_response, None, {}) # type: ignore @distributed_trace_async async def get( @@ -370,12 +341,11 @@ async def get( :type resource_group_name: str :param autoscale_setting_name: The autoscale setting name. Required. :type autoscale_setting_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: AutoscaleSettingResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_10_01.models.AutoscaleSettingResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -386,24 +356,22 @@ async def get( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-10-01")) cls: ClsType[_models.AutoscaleSettingResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, autoscale_setting_name=autoscale_setting_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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -413,16 +381,12 @@ async def get( error = self._deserialize.failsafe_deserialize(_models.AutoscaleErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("AutoscaleSettingResource", pipeline_response) + deserialized = self._deserialize("AutoscaleSettingResource", 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.Insights/autoscalesettings/{autoscaleSettingName}" - } + return deserialized # type: ignore @overload async def update( @@ -448,7 +412,6 @@ async def update( :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: AutoscaleSettingResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_10_01.models.AutoscaleSettingResource :raises ~azure.core.exceptions.HttpResponseError: @@ -459,7 +422,7 @@ async def update( self, resource_group_name: str, autoscale_setting_name: str, - autoscale_setting_resource: IO, + autoscale_setting_resource: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -473,11 +436,10 @@ async def update( :param autoscale_setting_name: The autoscale setting name. Required. :type autoscale_setting_name: str :param autoscale_setting_resource: Parameters supplied to the operation. Required. - :type autoscale_setting_resource: IO + :type autoscale_setting_resource: 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: AutoscaleSettingResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_10_01.models.AutoscaleSettingResource :raises ~azure.core.exceptions.HttpResponseError: @@ -488,7 +450,7 @@ async def update( self, resource_group_name: str, autoscale_setting_name: str, - autoscale_setting_resource: Union[_models.AutoscaleSettingResourcePatch, IO], + autoscale_setting_resource: Union[_models.AutoscaleSettingResourcePatch, IO[bytes]], **kwargs: Any ) -> _models.AutoscaleSettingResource: """Updates an existing AutoscaleSettingsResource. To update other fields use the CreateOrUpdate @@ -500,18 +462,14 @@ async def update( :param autoscale_setting_name: The autoscale setting name. Required. :type autoscale_setting_name: str :param autoscale_setting_resource: Parameters supplied to the operation. Is either a - AutoscaleSettingResourcePatch type or a IO type. Required. + AutoscaleSettingResourcePatch type or a IO[bytes] type. Required. :type autoscale_setting_resource: - ~azure.mgmt.monitor.v2022_10_01.models.AutoscaleSettingResourcePatch 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 + ~azure.mgmt.monitor.v2022_10_01.models.AutoscaleSettingResourcePatch or IO[bytes] :return: AutoscaleSettingResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_10_01.models.AutoscaleSettingResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -522,19 +480,19 @@ async def update( _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", "2022-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-10-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.AutoscaleSettingResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(autoscale_setting_resource, (IO, bytes)): + if isinstance(autoscale_setting_resource, (IOBase, bytes)): _content = autoscale_setting_resource else: _json = self._serialize.body(autoscale_setting_resource, "AutoscaleSettingResourcePatch") - request = build_update_request( + _request = build_update_request( resource_group_name=resource_group_name, autoscale_setting_name=autoscale_setting_name, subscription_id=self._config.subscription_id, @@ -542,16 +500,14 @@ async def update( 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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -561,22 +517,17 @@ async def update( error = self._deserialize.failsafe_deserialize(_models.AutoscaleErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("AutoscaleSettingResource", pipeline_response) + deserialized = self._deserialize("AutoscaleSettingResource", 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.Insights/autoscalesettings/{autoscaleSettingName}" - } + return deserialized # type: ignore @distributed_trace def list_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.AutoscaleSettingResource"]: """Lists the autoscale settings for a subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either AutoscaleSettingResource or the result of cls(response) :rtype: @@ -586,10 +537,10 @@ def list_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.Autoscal _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-10-01")) cls: ClsType[_models.AutoscaleSettingResourceCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -600,15 +551,13 @@ def list_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.Autoscal def prepare_request(next_link=None): if not next_link: - request = build_list_by_subscription_request( + _request = build_list_by_subscription_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_subscription.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -619,14 +568,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("AutoscaleSettingResourceCollection", pipeline_response) @@ -636,11 +584,11 @@ async def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -652,7 +600,3 @@ async def get_next(next_link=None): return pipeline_response return AsyncItemPaged(get_next, extract_data) - - list_by_subscription.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/autoscalesettings" - } diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_10_01/aio/operations/_predictive_metric_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_10_01/aio/operations/_predictive_metric_operations.py index 71a0f12ce4c5..9e41d2d170f5 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_10_01/aio/operations/_predictive_metric_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_10_01/aio/operations/_predictive_metric_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +6,7 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- import datetime +import sys from typing import Any, Callable, Dict, Optional, TypeVar from azure.core.exceptions import ( @@ -18,16 +18,18 @@ 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_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._predictive_metric_operations import build_get_request +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -50,6 +52,7 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace_async async def get( @@ -83,12 +86,11 @@ async def get( :type metric_name: str :param aggregation: The list of aggregation types (comma separated) to retrieve. Required. :type aggregation: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: PredictiveResponse or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_10_01.models.PredictiveResponse :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -99,10 +101,10 @@ async def get( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-10-01")) cls: ClsType[_models.PredictiveResponse] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, autoscale_setting_name=autoscale_setting_name, subscription_id=self._config.subscription_id, @@ -112,16 +114,14 @@ async def get( metric_name=metric_name, aggregation=aggregation, api_version=api_version, - template_url=self.get.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -131,13 +131,9 @@ async def get( error = self._deserialize.failsafe_deserialize(_models.AutoscaleErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("PredictiveResponse", pipeline_response) + deserialized = self._deserialize("PredictiveResponse", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - get.metadata = { - "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/autoscalesettings/{autoscaleSettingName}/predictiveMetrics" - } + return deserialized # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_10_01/models/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_10_01/models/__init__.py index e5589ba8fa19..0e2476f02333 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_10_01/models/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_10_01/models/__init__.py @@ -5,41 +5,52 @@ # 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 AutoscaleErrorResponse -from ._models_py3 import AutoscaleErrorResponseError -from ._models_py3 import AutoscaleNotification -from ._models_py3 import AutoscaleProfile -from ._models_py3 import AutoscaleSettingResource -from ._models_py3 import AutoscaleSettingResourceCollection -from ._models_py3 import AutoscaleSettingResourcePatch -from ._models_py3 import EmailNotification -from ._models_py3 import MetricTrigger -from ._models_py3 import PredictiveAutoscalePolicy -from ._models_py3 import PredictiveResponse -from ._models_py3 import PredictiveValue -from ._models_py3 import Recurrence -from ._models_py3 import RecurrentSchedule -from ._models_py3 import Resource -from ._models_py3 import ScaleAction -from ._models_py3 import ScaleCapacity -from ._models_py3 import ScaleRule -from ._models_py3 import ScaleRuleMetricDimension -from ._models_py3 import SystemData -from ._models_py3 import TimeWindow -from ._models_py3 import WebhookNotification +from typing import TYPE_CHECKING -from ._monitor_management_client_enums import ComparisonOperationType -from ._monitor_management_client_enums import CreatedByType -from ._monitor_management_client_enums import MetricStatisticType -from ._monitor_management_client_enums import PredictiveAutoscalePolicyScaleMode -from ._monitor_management_client_enums import RecurrenceFrequency -from ._monitor_management_client_enums import ScaleDirection -from ._monitor_management_client_enums import ScaleRuleMetricDimensionOperationType -from ._monitor_management_client_enums import ScaleType -from ._monitor_management_client_enums import TimeAggregationType +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models_py3 import ( # type: ignore + AutoscaleErrorResponse, + AutoscaleErrorResponseError, + AutoscaleNotification, + AutoscaleProfile, + AutoscaleSettingResource, + AutoscaleSettingResourceCollection, + AutoscaleSettingResourcePatch, + EmailNotification, + MetricTrigger, + PredictiveAutoscalePolicy, + PredictiveResponse, + PredictiveValue, + Recurrence, + RecurrentSchedule, + Resource, + ScaleAction, + ScaleCapacity, + ScaleRule, + ScaleRuleMetricDimension, + SystemData, + TimeWindow, + WebhookNotification, +) + +from ._monitor_management_client_enums import ( # type: ignore + ComparisonOperationType, + CreatedByType, + MetricStatisticType, + PredictiveAutoscalePolicyScaleMode, + RecurrenceFrequency, + ScaleDirection, + ScaleRuleMetricDimensionOperationType, + ScaleType, + TimeAggregationType, +) from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ @@ -75,5 +86,5 @@ "ScaleType", "TimeAggregationType", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_10_01/models/_models_py3.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_10_01/models/_models_py3.py index c47a2643e8f0..15f55b31e6ae 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_10_01/models/_models_py3.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_10_01/models/_models_py3.py @@ -1,5 +1,5 @@ -# coding=utf-8 # 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. @@ -13,7 +13,6 @@ from ... import _serialization if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from .. import models as _models @@ -98,7 +97,7 @@ class AutoscaleNotification(_serialization.Model): 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 operation: the operation associated with the notification and its value must be "scale". Required. Default value is "Scale". @@ -142,7 +141,7 @@ def __init__( class AutoscaleProfile(_serialization.Model): """Autoscale profile. - 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 name of the profile. Required. :vartype name: str @@ -211,7 +210,7 @@ class Resource(_serialization.Model): 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: Azure resource Id. :vartype id: str @@ -266,12 +265,12 @@ def __init__(self, *, location: str, tags: Optional[Dict[str, str]] = None, **kw self.system_data = None -class AutoscaleSettingResource(Resource): # pylint: disable=too-many-instance-attributes +class AutoscaleSettingResource(Resource): """The autoscale setting 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: Azure resource Id. :vartype id: str @@ -392,7 +391,7 @@ def __init__( class AutoscaleSettingResourceCollection(_serialization.Model): """Represents a collection of autoscale setting resources. - 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 value: the values for the autoscale setting resources. Required. :vartype value: list[~azure.mgmt.monitor.v2022_10_01.models.AutoscaleSettingResource] @@ -559,10 +558,10 @@ def __init__( self.custom_emails = custom_emails -class MetricTrigger(_serialization.Model): # pylint: disable=too-many-instance-attributes +class MetricTrigger(_serialization.Model): """The trigger that results in a scaling action. - 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 metric_name: the name of the metric that defines what the rule monitors. Required. :vartype metric_name: str @@ -594,7 +593,7 @@ class MetricTrigger(_serialization.Model): # pylint: disable=too-many-instance- :ivar threshold: the threshold of the metric that triggers the scale action. Required. :vartype threshold: float :ivar dimensions: List of dimension conditions. For example: - [{"DimensionName":"AppName","Operator":"Equals","Values":["App1"]},{"DimensionName":"Deployment","Operator":"Equals","Values":["default"]}]. + [{"DimensionName":"AppName","Operator":"Equals","Values":["App1"]},{"DimensionName":"Deployment","Operator":"Equals","Values":["default"]}]. # pylint: disable=line-too-long :vartype dimensions: list[~azure.mgmt.monitor.v2022_10_01.models.ScaleRuleMetricDimension] :ivar divide_per_instance: a value indicating whether metric should divide per instance. :vartype divide_per_instance: bool @@ -675,7 +674,7 @@ def __init__( :keyword threshold: the threshold of the metric that triggers the scale action. Required. :paramtype threshold: float :keyword dimensions: List of dimension conditions. For example: - [{"DimensionName":"AppName","Operator":"Equals","Values":["App1"]},{"DimensionName":"Deployment","Operator":"Equals","Values":["default"]}]. + [{"DimensionName":"AppName","Operator":"Equals","Values":["App1"]},{"DimensionName":"Deployment","Operator":"Equals","Values":["default"]}]. # pylint: disable=line-too-long :paramtype dimensions: list[~azure.mgmt.monitor.v2022_10_01.models.ScaleRuleMetricDimension] :keyword divide_per_instance: a value indicating whether metric should divide per instance. :paramtype divide_per_instance: bool @@ -698,7 +697,7 @@ def __init__( class PredictiveAutoscalePolicy(_serialization.Model): """The parameters for enabling predictive autoscale. - 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 scale_mode: the predictive autoscale mode. Required. Known values are: "Disabled", "ForecastOnly", and "Enabled". @@ -803,7 +802,7 @@ def __init__( class PredictiveValue(_serialization.Model): """Represents a predictive metric value in the given bucket. - 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 time_stamp: the timestamp for the metric value in ISO 8601 format. Required. :vartype time_stamp: ~datetime.datetime @@ -837,7 +836,7 @@ class Recurrence(_serialization.Model): """The repeating times at which this profile begins. This element is not used if the FixedDate element is used. - 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 frequency: the recurrence frequency. How often the schedule profile should take effect. This value must be Week, meaning each week will have the same set of profiles. For example, to @@ -884,7 +883,7 @@ def __init__( class RecurrentSchedule(_serialization.Model): """The scheduling constraints for when the profile begins. - 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 time_zone: the timezone for the hours of the profile. Some examples of valid time zones are: Dateline Standard Time, UTC-11, Hawaiian Standard Time, Alaskan Standard Time, Pacific @@ -993,7 +992,7 @@ def __init__(self, *, time_zone: str, days: List[str], hours: List[int], minutes class ScaleAction(_serialization.Model): """The parameters for the scaling action. - 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 direction: the scale direction. Whether the scaling action increases or decreases the number of instances. Required. Known values are: "None", "Increase", and "Decrease". @@ -1055,7 +1054,7 @@ def __init__( class ScaleCapacity(_serialization.Model): """The number of instances that can be used during this profile. - 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 minimum: the minimum number of instances for the resource. Required. :vartype minimum: str @@ -1101,7 +1100,7 @@ def __init__(self, *, minimum: str, maximum: str, default: str, **kwargs: Any) - class ScaleRule(_serialization.Model): """A rule that provide the triggers and parameters for the scaling action. - 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 metric_trigger: the trigger that results in a scaling action. Required. :vartype metric_trigger: ~azure.mgmt.monitor.v2022_10_01.models.MetricTrigger @@ -1136,7 +1135,7 @@ def __init__( class ScaleRuleMetricDimension(_serialization.Model): """Specifies an auto scale rule metric dimension. - 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 dimension_name: Name of the dimension. Required. :vartype dimension_name: str @@ -1253,7 +1252,7 @@ def __init__( class TimeWindow(_serialization.Model): """A specific date-time for the profile. - 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 time_zone: the timezone of the start and end times for the profile. Some examples of valid time zones are: Dateline Standard Time, UTC-11, Hawaiian Standard Time, Alaskan Standard diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_10_01/operations/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_10_01/operations/__init__.py index 3d1ab289551f..e66d31251e99 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_10_01/operations/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_10_01/operations/__init__.py @@ -5,17 +5,23 @@ # 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 ._autoscale_settings_operations import AutoscaleSettingsOperations -from ._predictive_metric_operations import PredictiveMetricOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._autoscale_settings_operations import AutoscaleSettingsOperations # type: ignore +from ._predictive_metric_operations import PredictiveMetricOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ "AutoscaleSettingsOperations", "PredictiveMetricOperations", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_10_01/operations/_autoscale_settings_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_10_01/operations/_autoscale_settings_operations.py index eb8a0947cdab..798edadf8ce3 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_10_01/operations/_autoscale_settings_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_10_01/operations/_autoscale_settings_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload import urllib.parse @@ -19,16 +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, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -55,7 +58,7 @@ def build_list_by_resource_group_request(resource_group_name: str, subscription_ "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -89,7 +92,7 @@ def build_create_or_update_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -124,7 +127,7 @@ def build_delete_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -157,7 +160,7 @@ def build_get_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -191,7 +194,7 @@ def build_update_request( "autoscaleSettingName": _SERIALIZER.url("autoscale_setting_name", autoscale_setting_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -217,7 +220,7 @@ def build_list_by_subscription_request(subscription_id: str, **kwargs: Any) -> H "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -246,6 +249,7 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def list_by_resource_group( @@ -256,7 +260,6 @@ def list_by_resource_group( :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either AutoscaleSettingResource or the result of cls(response) :rtype: @@ -266,10 +269,10 @@ def list_by_resource_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-10-01")) cls: ClsType[_models.AutoscaleSettingResourceCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -280,16 +283,14 @@ 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_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -300,14 +301,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("AutoscaleSettingResourceCollection", pipeline_response) @@ -317,11 +317,11 @@ def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -334,10 +334,6 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/autoscalesettings" - } - @overload def create_or_update( self, @@ -360,7 +356,6 @@ def create_or_update( :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: AutoscaleSettingResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_10_01.models.AutoscaleSettingResource :raises ~azure.core.exceptions.HttpResponseError: @@ -371,7 +366,7 @@ def create_or_update( self, resource_group_name: str, autoscale_setting_name: str, - parameters: IO, + parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -384,11 +379,10 @@ def create_or_update( :param autoscale_setting_name: The autoscale setting name. Required. :type autoscale_setting_name: str :param parameters: Parameters supplied to the operation. Required. - :type parameters: IO + :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: AutoscaleSettingResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_10_01.models.AutoscaleSettingResource :raises ~azure.core.exceptions.HttpResponseError: @@ -399,7 +393,7 @@ def create_or_update( self, resource_group_name: str, autoscale_setting_name: str, - parameters: Union[_models.AutoscaleSettingResource, IO], + parameters: Union[_models.AutoscaleSettingResource, IO[bytes]], **kwargs: Any ) -> _models.AutoscaleSettingResource: """Creates or updates an autoscale setting. @@ -410,17 +404,13 @@ def create_or_update( :param autoscale_setting_name: The autoscale setting name. Required. :type autoscale_setting_name: str :param parameters: Parameters supplied to the operation. Is either a AutoscaleSettingResource - type or a IO type. Required. - :type parameters: ~azure.mgmt.monitor.v2022_10_01.models.AutoscaleSettingResource 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 + type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.monitor.v2022_10_01.models.AutoscaleSettingResource or IO[bytes] :return: AutoscaleSettingResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_10_01.models.AutoscaleSettingResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -431,19 +421,19 @@ def create_or_update( _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", "2022-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-10-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.AutoscaleSettingResource] = 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, "AutoscaleSettingResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, autoscale_setting_name=autoscale_setting_name, subscription_id=self._config.subscription_id, @@ -451,16 +441,14 @@ def create_or_update( 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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -470,21 +458,13 @@ def create_or_update( error = self._deserialize.failsafe_deserialize(_models.AutoscaleErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if response.status_code == 200: - deserialized = self._deserialize("AutoscaleSettingResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("AutoscaleSettingResource", pipeline_response) + deserialized = self._deserialize("AutoscaleSettingResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/autoscalesettings/{autoscaleSettingName}" - } - @distributed_trace def delete( # pylint: disable=inconsistent-return-statements self, resource_group_name: str, autoscale_setting_name: str, **kwargs: Any @@ -496,12 +476,11 @@ def delete( # pylint: disable=inconsistent-return-statements :type resource_group_name: str :param autoscale_setting_name: The autoscale setting name. Required. :type autoscale_setting_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, @@ -512,24 +491,22 @@ def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-10-01")) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, autoscale_setting_name=autoscale_setting_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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -540,11 +517,7 @@ def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/autoscalesettings/{autoscaleSettingName}" - } + return cls(pipeline_response, None, {}) # type: ignore @distributed_trace def get( @@ -557,12 +530,11 @@ def get( :type resource_group_name: str :param autoscale_setting_name: The autoscale setting name. Required. :type autoscale_setting_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: AutoscaleSettingResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_10_01.models.AutoscaleSettingResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -573,24 +545,22 @@ def get( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-10-01")) cls: ClsType[_models.AutoscaleSettingResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, autoscale_setting_name=autoscale_setting_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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -600,16 +570,12 @@ def get( error = self._deserialize.failsafe_deserialize(_models.AutoscaleErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("AutoscaleSettingResource", pipeline_response) + deserialized = self._deserialize("AutoscaleSettingResource", 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.Insights/autoscalesettings/{autoscaleSettingName}" - } + return deserialized # type: ignore @overload def update( @@ -635,7 +601,6 @@ def update( :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: AutoscaleSettingResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_10_01.models.AutoscaleSettingResource :raises ~azure.core.exceptions.HttpResponseError: @@ -646,7 +611,7 @@ def update( self, resource_group_name: str, autoscale_setting_name: str, - autoscale_setting_resource: IO, + autoscale_setting_resource: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -660,11 +625,10 @@ def update( :param autoscale_setting_name: The autoscale setting name. Required. :type autoscale_setting_name: str :param autoscale_setting_resource: Parameters supplied to the operation. Required. - :type autoscale_setting_resource: IO + :type autoscale_setting_resource: 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: AutoscaleSettingResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_10_01.models.AutoscaleSettingResource :raises ~azure.core.exceptions.HttpResponseError: @@ -675,7 +639,7 @@ def update( self, resource_group_name: str, autoscale_setting_name: str, - autoscale_setting_resource: Union[_models.AutoscaleSettingResourcePatch, IO], + autoscale_setting_resource: Union[_models.AutoscaleSettingResourcePatch, IO[bytes]], **kwargs: Any ) -> _models.AutoscaleSettingResource: """Updates an existing AutoscaleSettingsResource. To update other fields use the CreateOrUpdate @@ -687,18 +651,14 @@ def update( :param autoscale_setting_name: The autoscale setting name. Required. :type autoscale_setting_name: str :param autoscale_setting_resource: Parameters supplied to the operation. Is either a - AutoscaleSettingResourcePatch type or a IO type. Required. + AutoscaleSettingResourcePatch type or a IO[bytes] type. Required. :type autoscale_setting_resource: - ~azure.mgmt.monitor.v2022_10_01.models.AutoscaleSettingResourcePatch 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 + ~azure.mgmt.monitor.v2022_10_01.models.AutoscaleSettingResourcePatch or IO[bytes] :return: AutoscaleSettingResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_10_01.models.AutoscaleSettingResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -709,19 +669,19 @@ def update( _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", "2022-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-10-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.AutoscaleSettingResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(autoscale_setting_resource, (IO, bytes)): + if isinstance(autoscale_setting_resource, (IOBase, bytes)): _content = autoscale_setting_resource else: _json = self._serialize.body(autoscale_setting_resource, "AutoscaleSettingResourcePatch") - request = build_update_request( + _request = build_update_request( resource_group_name=resource_group_name, autoscale_setting_name=autoscale_setting_name, subscription_id=self._config.subscription_id, @@ -729,16 +689,14 @@ def update( 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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -748,22 +706,17 @@ def update( error = self._deserialize.failsafe_deserialize(_models.AutoscaleErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("AutoscaleSettingResource", pipeline_response) + deserialized = self._deserialize("AutoscaleSettingResource", 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.Insights/autoscalesettings/{autoscaleSettingName}" - } + return deserialized # type: ignore @distributed_trace def list_by_subscription(self, **kwargs: Any) -> Iterable["_models.AutoscaleSettingResource"]: """Lists the autoscale settings for a subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either AutoscaleSettingResource or the result of cls(response) :rtype: @@ -773,10 +726,10 @@ def list_by_subscription(self, **kwargs: Any) -> Iterable["_models.AutoscaleSett _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-10-01")) cls: ClsType[_models.AutoscaleSettingResourceCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -787,15 +740,13 @@ def list_by_subscription(self, **kwargs: Any) -> Iterable["_models.AutoscaleSett def prepare_request(next_link=None): if not next_link: - request = build_list_by_subscription_request( + _request = build_list_by_subscription_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_subscription.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -806,14 +757,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("AutoscaleSettingResourceCollection", pipeline_response) @@ -823,11 +773,11 @@ def extract_data(pipeline_response): 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) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -839,7 +789,3 @@ def get_next(next_link=None): return pipeline_response return ItemPaged(get_next, extract_data) - - list_by_subscription.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/autoscalesettings" - } diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_10_01/operations/_predictive_metric_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_10_01/operations/_predictive_metric_operations.py index d1f57c131d60..ffe724ad26a3 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_10_01/operations/_predictive_metric_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2022_10_01/operations/_predictive_metric_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +6,7 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- import datetime +import sys from typing import Any, Callable, Dict, Optional, TypeVar from azure.core.exceptions import ( @@ -18,16 +18,18 @@ map_error, ) 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 +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -66,7 +68,7 @@ def build_get_request( "autoscaleSettingName": _SERIALIZER.url("autoscale_setting_name", autoscale_setting_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["timespan"] = _SERIALIZER.query("timespan", timespan, "str") @@ -100,6 +102,7 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @distributed_trace def get( @@ -133,12 +136,11 @@ def get( :type metric_name: str :param aggregation: The list of aggregation types (comma separated) to retrieve. Required. :type aggregation: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: PredictiveResponse or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2022_10_01.models.PredictiveResponse :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -149,10 +151,10 @@ def get( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-10-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2022-10-01")) cls: ClsType[_models.PredictiveResponse] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, autoscale_setting_name=autoscale_setting_name, subscription_id=self._config.subscription_id, @@ -162,16 +164,14 @@ def get( metric_name=metric_name, aggregation=aggregation, api_version=api_version, - template_url=self.get.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -181,13 +181,9 @@ def get( error = self._deserialize.failsafe_deserialize(_models.AutoscaleErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("PredictiveResponse", pipeline_response) + deserialized = self._deserialize("PredictiveResponse", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - get.metadata = { - "url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/autoscalesettings/{autoscaleSettingName}/predictiveMetrics" - } + return deserialized # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_01_01/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_01_01/__init__.py index 2c7733bfd566..42cc62301757 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_01_01/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_01_01/__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 ._monitor_management_client import MonitorManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._monitor_management_client import MonitorManagementClient # type: ignore from ._version import VERSION __version__ = VERSION try: from ._patch import __all__ as _patch_all - from ._patch import * # 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__ = [ "MonitorManagementClient", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_01_01/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_01_01/_configuration.py index 44706f982b49..7e5dd54e0629 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_01_01/_configuration.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_01_01/_configuration.py @@ -8,18 +8,16 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy from ._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MonitorManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class MonitorManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for MonitorManagementClient. Note that all parameters used to create this instance are saved as instance @@ -35,7 +33,6 @@ class MonitorManagementClientConfiguration(Configuration): # pylint: disable=to """ def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: - super(MonitorManagementClientConfiguration, self).__init__(**kwargs) api_version: str = kwargs.pop("api_version", "2023-01-01") if credential is None: @@ -48,6 +45,7 @@ def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-monitor/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -56,9 +54,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.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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_01_01/_metadata.json b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_01_01/_metadata.json index dd4f1ef7423e..44e6788a8b96 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_01_01/_metadata.json +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_01_01/_metadata.json @@ -8,10 +8,10 @@ "host_value": "\"https://management.azure.com\"", "parameterized_host_template": null, "azure_arm": true, - "has_lro_operations": true, + "has_public_lro_operations": true, "client_side_validation": false, - "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"sdkcore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMAutoResourceProviderRegistrationPolicy\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}, \"stdlib\": {\"typing_extensions\": [\"Self\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"sdkcore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"AsyncARMAutoResourceProviderRegistrationPolicy\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}, \"stdlib\": {\"typing_extensions\": [\"Self\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "global_parameters": { "sync": { @@ -101,8 +101,8 @@ "credential_scopes": ["https://management.azure.com/.default"], "credential_call_sync": "ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", "credential_call_async": "AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", - "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "sync_imports": "{\"regular\": {\"sdkcore\": {\"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"regular\": {\"sdkcore\": {\"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "operation_groups": { "action_groups": "ActionGroupsOperations" diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_01_01/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_01_01/_monitor_management_client.py index 2df565f22f59..77219a384be1 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_01_01/_monitor_management_client.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_01_01/_monitor_management_client.py @@ -8,9 +8,12 @@ from copy import deepcopy from typing import Any, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient +from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy from . import models as _models from .._serialization import Deserializer, Serializer @@ -18,11 +21,10 @@ from .operations import ActionGroupsOperations if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MonitorManagementClient: # pylint: disable=client-accepts-api-version-keyword +class MonitorManagementClient: """Monitor Management Client. :ivar action_groups: ActionGroupsOperations operations @@ -50,15 +52,35 @@ def __init__( self._config = MonitorManagementClientConfiguration( credential=credential, subscription_id=subscription_id, **kwargs ) - self._client: ARMPipelineClient = ARMPipelineClient(base_url=base_url, config=self._config, **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), + 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=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.action_groups = ActionGroupsOperations(self._client, self._config, self._serialize, self._deserialize) + self.action_groups = ActionGroupsOperations( + self._client, self._config, self._serialize, self._deserialize, "2023-01-01" + ) - 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 @@ -78,12 +100,12 @@ 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) -> None: self._client.close() - def __enter__(self) -> "MonitorManagementClient": + def __enter__(self) -> Self: self._client.__enter__() return self diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_01_01/_vendor.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_01_01/_vendor.py deleted file mode 100644 index bd0df84f5319..000000000000 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_01_01/_vendor.py +++ /dev/null @@ -1,30 +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 typing import List, cast - -from azure.core.pipeline.transport import HttpRequest - - -def _convert_request(request, files=None): - data = request.content if not files else None - request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) - if files: - request.set_formdata_body(files) - return request - - -def _format_url_section(template, **kwargs): - components = template.split("/") - while components: - try: - return template.format(**kwargs) - except KeyError as key: - # Need the cast, as for some reasons "split" is typed as list[str | Any] - formatted_components = cast(List[str], template.split("/")) - components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] - template = "/".join(components) diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_01_01/_version.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_01_01/_version.py index 394ee7c0c03c..e5754a47ce68 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_01_01/_version.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_01_01/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "6.0.2" +VERSION = "1.0.0b1" diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_01_01/aio/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_01_01/aio/__init__.py index 2c151bb41c19..3df30ff42149 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_01_01/aio/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_01_01/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 ._monitor_management_client import MonitorManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._monitor_management_client import MonitorManagementClient # type: ignore try: from ._patch import __all__ as _patch_all - from ._patch import * # 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__ = [ "MonitorManagementClient", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_01_01/aio/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_01_01/aio/_configuration.py index dde84c532624..3d9f0d6e12a4 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_01_01/aio/_configuration.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_01_01/aio/_configuration.py @@ -8,18 +8,16 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy from .._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MonitorManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class MonitorManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for MonitorManagementClient. Note that all parameters used to create this instance are saved as instance @@ -35,7 +33,6 @@ class MonitorManagementClientConfiguration(Configuration): # pylint: disable=to """ def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: - super(MonitorManagementClientConfiguration, self).__init__(**kwargs) api_version: str = kwargs.pop("api_version", "2023-01-01") if credential is None: @@ -48,6 +45,7 @@ def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **k self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-monitor/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -56,9 +54,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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_01_01/aio/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_01_01/aio/_monitor_management_client.py index e729b5d59b3f..468a5d49d880 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_01_01/aio/_monitor_management_client.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_01_01/aio/_monitor_management_client.py @@ -8,9 +8,12 @@ from copy import deepcopy from typing import Any, Awaitable, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient +from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy from .. import models as _models from ..._serialization import Deserializer, Serializer @@ -18,11 +21,10 @@ from .operations import ActionGroupsOperations if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MonitorManagementClient: # pylint: disable=client-accepts-api-version-keyword +class MonitorManagementClient: """Monitor Management Client. :ivar action_groups: ActionGroupsOperations operations @@ -50,15 +52,37 @@ def __init__( self._config = MonitorManagementClientConfiguration( credential=credential, subscription_id=subscription_id, **kwargs ) - self._client: AsyncARMPipelineClient = AsyncARMPipelineClient(base_url=base_url, config=self._config, **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=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.action_groups = ActionGroupsOperations(self._client, self._config, self._serialize, self._deserialize) + self.action_groups = ActionGroupsOperations( + self._client, self._config, self._serialize, self._deserialize, "2023-01-01" + ) - 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 @@ -78,12 +102,12 @@ 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) -> "MonitorManagementClient": + async def __aenter__(self) -> Self: await self._client.__aenter__() return self diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_01_01/aio/operations/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_01_01/aio/operations/__init__.py index 05f0527dc979..410e631e0472 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_01_01/aio/operations/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_01_01/aio/operations/__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 ._action_groups_operations import ActionGroupsOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._action_groups_operations import ActionGroupsOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ "ActionGroupsOperations", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_01_01/aio/operations/_action_groups_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_01_01/aio/operations/_action_groups_operations.py index 0b64afbb9f89..978bdb683614 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_01_01/aio/operations/_action_groups_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_01_01/aio/operations/_action_groups_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,7 +5,9 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload +from io import IOBase +import sys +from typing import Any, AsyncIterable, AsyncIterator, Callable, Dict, IO, Optional, Type, TypeVar, Union, cast, overload import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList @@ -16,12 +17,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 @@ -29,7 +31,6 @@ from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models -from ..._vendor import _convert_request from ...operations._action_groups_operations import ( build_create_notifications_at_action_group_resource_level_request, build_create_or_update_request, @@ -42,6 +43,10 @@ build_update_request, ) +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -64,6 +69,7 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @overload async def create_or_update( @@ -87,7 +93,6 @@ async def create_or_update( :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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2023_01_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -98,7 +103,7 @@ async def create_or_update( self, resource_group_name: str, action_group_name: str, - action_group: IO, + action_group: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -111,11 +116,10 @@ async def create_or_update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group: The action group to create or use for the update. Required. - :type action_group: IO + :type action_group: 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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2023_01_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -126,7 +130,7 @@ async def create_or_update( self, resource_group_name: str, action_group_name: str, - action_group: Union[_models.ActionGroupResource, IO], + action_group: Union[_models.ActionGroupResource, IO[bytes]], **kwargs: Any ) -> _models.ActionGroupResource: """Create a new action group or update an existing one. @@ -137,17 +141,13 @@ async def create_or_update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group: The action group to create or use for the update. Is either a - ActionGroupResource type or a IO type. Required. - :type action_group: ~azure.mgmt.monitor.v2023_01_01.models.ActionGroupResource 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 + ActionGroupResource type or a IO[bytes] type. Required. + :type action_group: ~azure.mgmt.monitor.v2023_01_01.models.ActionGroupResource or IO[bytes] :return: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2023_01_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -158,19 +158,19 @@ async def create_or_update( _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", "2023-01-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2023-01-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ActionGroupResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(action_group, (IO, bytes)): + if isinstance(action_group, (IOBase, bytes)): _content = action_group else: _json = self._serialize.body(action_group, "ActionGroupResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, action_group_name=action_group_name, subscription_id=self._config.subscription_id, @@ -178,16 +178,14 @@ async def create_or_update( 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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -197,21 +195,13 @@ async def create_or_update( 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("ActionGroupResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("ActionGroupResource", pipeline_response) + deserialized = self._deserialize("ActionGroupResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/actionGroups/{actionGroupName}" - } - @distributed_trace_async async def get(self, resource_group_name: str, action_group_name: str, **kwargs: Any) -> _models.ActionGroupResource: """Get an action group. @@ -221,12 +211,11 @@ async def get(self, resource_group_name: str, action_group_name: str, **kwargs: :type resource_group_name: str :param action_group_name: The name of the action group. Required. :type action_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2023_01_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -237,24 +226,22 @@ async def get(self, resource_group_name: str, action_group_name: str, **kwargs: _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-01-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2023-01-01")) cls: ClsType[_models.ActionGroupResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, action_group_name=action_group_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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -264,21 +251,15 @@ async def get(self, resource_group_name: str, action_group_name: str, **kwargs: error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ActionGroupResource", pipeline_response) + deserialized = self._deserialize("ActionGroupResource", 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.Insights/actionGroups/{actionGroupName}" - } + return deserialized # type: ignore @distributed_trace_async - async def delete( # pylint: disable=inconsistent-return-statements - self, resource_group_name: str, action_group_name: str, **kwargs: Any - ) -> None: + async def delete(self, resource_group_name: str, action_group_name: str, **kwargs: Any) -> None: """Delete an action group. :param resource_group_name: The name of the resource group. The name is case insensitive. @@ -286,12 +267,11 @@ async def delete( # pylint: disable=inconsistent-return-statements :type resource_group_name: str :param action_group_name: The name of the action group. Required. :type action_group_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, @@ -302,24 +282,22 @@ async def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-01-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2023-01-01")) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, action_group_name=action_group_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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -330,11 +308,7 @@ async def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/actionGroups/{actionGroupName}" - } + return cls(pipeline_response, None, {}) # type: ignore @overload async def update( @@ -358,7 +332,6 @@ async def update( :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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2023_01_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -369,7 +342,7 @@ async def update( self, resource_group_name: str, action_group_name: str, - action_group_patch: IO, + action_group_patch: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -382,11 +355,10 @@ async def update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group_patch: Parameters supplied to the operation. Required. - :type action_group_patch: IO + :type action_group_patch: 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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2023_01_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -397,7 +369,7 @@ async def update( self, resource_group_name: str, action_group_name: str, - action_group_patch: Union[_models.ActionGroupPatchBody, IO], + action_group_patch: Union[_models.ActionGroupPatchBody, IO[bytes]], **kwargs: Any ) -> _models.ActionGroupResource: """Updates an existing action group's tags. To update other fields use the CreateOrUpdate method. @@ -408,17 +380,14 @@ async def update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group_patch: Parameters supplied to the operation. Is either a - ActionGroupPatchBody type or a IO type. Required. - :type action_group_patch: ~azure.mgmt.monitor.v2023_01_01.models.ActionGroupPatchBody 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 + ActionGroupPatchBody type or a IO[bytes] type. Required. + :type action_group_patch: ~azure.mgmt.monitor.v2023_01_01.models.ActionGroupPatchBody or + IO[bytes] :return: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2023_01_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -429,19 +398,19 @@ async def update( _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", "2023-01-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2023-01-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ActionGroupResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(action_group_patch, (IO, bytes)): + if isinstance(action_group_patch, (IOBase, bytes)): _content = action_group_patch else: _json = self._serialize.body(action_group_patch, "ActionGroupPatchBody") - request = build_update_request( + _request = build_update_request( resource_group_name=resource_group_name, action_group_name=action_group_name, subscription_id=self._config.subscription_id, @@ -449,16 +418,14 @@ async def update( 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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -468,25 +435,21 @@ async def update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ActionGroupResource", pipeline_response) + deserialized = self._deserialize("ActionGroupResource", 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.Insights/actionGroups/{actionGroupName}" - } + return deserialized # type: ignore async def _create_notifications_at_action_group_resource_level_initial( # pylint: disable=name-too-long self, resource_group_name: str, action_group_name: str, - notification_request: Union[_models.NotificationRequestBody, IO], + notification_request: Union[_models.NotificationRequestBody, IO[bytes]], **kwargs: Any - ) -> Optional[_models.TestNotificationDetailsResponse]: - error_map = { + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -497,19 +460,19 @@ async def _create_notifications_at_action_group_resource_level_initial( # pylin _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", "2023-01-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2023-01-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Optional[_models.TestNotificationDetailsResponse]] = kwargs.pop("cls", None) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(notification_request, (IO, bytes)): + if isinstance(notification_request, (IOBase, bytes)): _content = notification_request else: _json = self._serialize.body(notification_request, "NotificationRequestBody") - request = build_create_notifications_at_action_group_resource_level_request( + _request = build_create_notifications_at_action_group_resource_level_request( resource_group_name=resource_group_name, action_group_name=action_group_name, subscription_id=self._config.subscription_id, @@ -517,41 +480,38 @@ async def _create_notifications_at_action_group_resource_level_initial( # pylin content_type=content_type, json=_json, content=_content, - template_url=self._create_notifications_at_action_group_resource_level_initial.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: + 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 = None response_headers = {} - if response.status_code == 200: - deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response) - if response.status_code == 202: response_headers["location"] = self._deserialize("str", response.headers.get("location")) - if cls: - return cls(pipeline_response, deserialized, response_headers) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - return deserialized + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore - _create_notifications_at_action_group_resource_level_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/actionGroups/{actionGroupName}/createNotifications" - } + return deserialized # type: ignore @overload async def begin_create_notifications_at_action_group_resource_level( # pylint: disable=name-too-long @@ -576,14 +536,6 @@ async def begin_create_notifications_at_action_group_resource_level( # pylint: :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 TestNotificationDetailsResponse or the result of cls(response) :rtype: @@ -596,7 +548,7 @@ async def begin_create_notifications_at_action_group_resource_level( # pylint: self, resource_group_name: str, action_group_name: str, - notification_request: IO, + notification_request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -610,18 +562,10 @@ async def begin_create_notifications_at_action_group_resource_level( # pylint: :type action_group_name: str :param notification_request: The notification request body which includes the contact details. Required. - :type notification_request: IO + :type notification_request: 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 TestNotificationDetailsResponse or the result of cls(response) :rtype: @@ -634,7 +578,7 @@ async def begin_create_notifications_at_action_group_resource_level( # pylint: self, resource_group_name: str, action_group_name: str, - notification_request: Union[_models.NotificationRequestBody, IO], + notification_request: Union[_models.NotificationRequestBody, IO[bytes]], **kwargs: Any ) -> AsyncLROPoller[_models.TestNotificationDetailsResponse]: """Send test notifications to a set of provided receivers. @@ -645,20 +589,9 @@ async def begin_create_notifications_at_action_group_resource_level( # pylint: :param action_group_name: The name of the action group. Required. :type action_group_name: str :param notification_request: The notification request body which includes the contact details. - Is either a NotificationRequestBody type or a IO type. Required. + Is either a NotificationRequestBody type or a IO[bytes] type. Required. :type notification_request: ~azure.mgmt.monitor.v2023_01_01.models.NotificationRequestBody 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. + IO[bytes] :return: An instance of AsyncLROPoller that returns either TestNotificationDetailsResponse or the result of cls(response) :rtype: @@ -668,7 +601,7 @@ async def begin_create_notifications_at_action_group_resource_level( # pylint: _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", "2023-01-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2023-01-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.TestNotificationDetailsResponse] = kwargs.pop("cls", None) polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) @@ -686,12 +619,13 @@ async def begin_create_notifications_at_action_group_resource_level( # pylint: 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("TestNotificationDetailsResponse", pipeline_response) + deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: @@ -703,17 +637,15 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return AsyncLROPoller.from_continuation_token( + return AsyncLROPoller[_models.TestNotificationDetailsResponse].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_create_notifications_at_action_group_resource_level.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/actionGroups/{actionGroupName}/createNotifications" - } + return AsyncLROPoller[_models.TestNotificationDetailsResponse]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) @distributed_trace_async async def get_test_notifications_at_action_group_resource_level( # pylint: disable=name-too-long @@ -728,12 +660,11 @@ async def get_test_notifications_at_action_group_resource_level( # pylint: disa :type action_group_name: str :param notification_id: The notification id. Required. :type notification_id: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: TestNotificationDetailsResponse or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2023_01_01.models.TestNotificationDetailsResponse :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -744,25 +675,23 @@ async def get_test_notifications_at_action_group_resource_level( # pylint: disa _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-01-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2023-01-01")) cls: ClsType[_models.TestNotificationDetailsResponse] = kwargs.pop("cls", None) - request = build_get_test_notifications_at_action_group_resource_level_request( + _request = build_get_test_notifications_at_action_group_resource_level_request( resource_group_name=resource_group_name, action_group_name=action_group_name, notification_id=notification_id, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get_test_notifications_at_action_group_resource_level.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -772,22 +701,17 @@ async def get_test_notifications_at_action_group_resource_level( # pylint: disa error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response) + deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get_test_notifications_at_action_group_resource_level.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/actionGroups/{actionGroupName}/notificationStatus/{notificationId}" - } + return deserialized # type: ignore @distributed_trace def list_by_subscription_id(self, **kwargs: Any) -> AsyncIterable["_models.ActionGroupResource"]: """Get a list of all action groups in a subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ActionGroupResource or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.monitor.v2023_01_01.models.ActionGroupResource] @@ -796,10 +720,10 @@ def list_by_subscription_id(self, **kwargs: Any) -> AsyncIterable["_models.Actio _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-01-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2023-01-01")) cls: ClsType[_models.ActionGroupList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -810,15 +734,13 @@ def list_by_subscription_id(self, **kwargs: Any) -> AsyncIterable["_models.Actio def prepare_request(next_link=None): if not next_link: - request = build_list_by_subscription_id_request( + _request = build_list_by_subscription_id_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_subscription_id.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -829,14 +751,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("ActionGroupList", pipeline_response) @@ -846,11 +767,11 @@ async def extract_data(pipeline_response): return None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -863,10 +784,6 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_by_subscription_id.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/actionGroups" - } - @distributed_trace def list_by_resource_group( self, resource_group_name: str, **kwargs: Any @@ -876,7 +793,6 @@ def list_by_resource_group( :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ActionGroupResource or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.monitor.v2023_01_01.models.ActionGroupResource] @@ -885,10 +801,10 @@ def list_by_resource_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-01-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2023-01-01")) cls: ClsType[_models.ActionGroupList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -899,16 +815,14 @@ 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_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -919,14 +833,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("ActionGroupList", pipeline_response) @@ -936,11 +849,11 @@ async def extract_data(pipeline_response): return None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -953,12 +866,8 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/actionGroups" - } - @overload - async def enable_receiver( # pylint: disable=inconsistent-return-statements + async def enable_receiver( self, resource_group_name: str, action_group_name: str, @@ -980,18 +889,17 @@ async def enable_receiver( # pylint: disable=inconsistent-return-statements :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: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def enable_receiver( # pylint: disable=inconsistent-return-statements + async def enable_receiver( self, resource_group_name: str, action_group_name: str, - enable_request: IO, + enable_request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -1005,22 +913,21 @@ async def enable_receiver( # pylint: disable=inconsistent-return-statements :param action_group_name: The name of the action group. Required. :type action_group_name: str :param enable_request: The receiver to re-enable. Required. - :type enable_request: IO + :type enable_request: 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: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async - async def enable_receiver( # pylint: disable=inconsistent-return-statements + async def enable_receiver( self, resource_group_name: str, action_group_name: str, - enable_request: Union[_models.EnableRequest, IO], + enable_request: Union[_models.EnableRequest, IO[bytes]], **kwargs: Any ) -> None: """Enable a receiver in an action group. This changes the receiver's status from Disabled to @@ -1031,41 +938,40 @@ async def enable_receiver( # pylint: disable=inconsistent-return-statements :type resource_group_name: str :param action_group_name: The name of the action group. Required. :type action_group_name: str - :param enable_request: The receiver to re-enable. Is either a EnableRequest type or a IO type. - Required. - :type enable_request: ~azure.mgmt.monitor.v2023_01_01.models.EnableRequest 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 + :param enable_request: The receiver to re-enable. Is either a EnableRequest type or a IO[bytes] + type. Required. + :type enable_request: ~azure.mgmt.monitor.v2023_01_01.models.EnableRequest or IO[bytes] :return: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 304: ResourceNotModifiedError, - 409: lambda response: ResourceExistsError(response=response, error_format=ARMErrorFormat), + 409: cast( + Type[HttpResponseError], + lambda response: ResourceExistsError(response=response, error_format=ARMErrorFormat), + ), } 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: str = kwargs.pop("api_version", _params.pop("api-version", "2023-01-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2023-01-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[None] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(enable_request, (IO, bytes)): + if isinstance(enable_request, (IOBase, bytes)): _content = enable_request else: _json = self._serialize.body(enable_request, "EnableRequest") - request = build_enable_receiver_request( + _request = build_enable_receiver_request( resource_group_name=resource_group_name, action_group_name=action_group_name, subscription_id=self._config.subscription_id, @@ -1073,28 +979,22 @@ async def enable_receiver( # pylint: disable=inconsistent-return-statements content_type=content_type, json=_json, content=_content, - template_url=self.enable_receiver.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _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) + map_error(status_code=response.status_code, response=response, error_map=error_map) # type: ignore 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, {}) - - enable_receiver.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/actionGroups/{actionGroupName}/subscribe" - } + return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_01_01/models/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_01_01/models/__init__.py index b1dac637c403..2e909d448f9e 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_01_01/models/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_01_01/models/__init__.py @@ -5,32 +5,43 @@ # 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 ActionDetail -from ._models_py3 import ActionGroupList -from ._models_py3 import ActionGroupPatchBody -from ._models_py3 import ActionGroupResource -from ._models_py3 import ArmRoleReceiver -from ._models_py3 import AutomationRunbookReceiver -from ._models_py3 import AzureAppPushReceiver -from ._models_py3 import AzureFunctionReceiver -from ._models_py3 import AzureResource -from ._models_py3 import Context -from ._models_py3 import EmailReceiver -from ._models_py3 import EnableRequest -from ._models_py3 import ErrorResponse -from ._models_py3 import EventHubReceiver -from ._models_py3 import ItsmReceiver -from ._models_py3 import LogicAppReceiver -from ._models_py3 import NotificationRequestBody -from ._models_py3 import SmsReceiver -from ._models_py3 import TestNotificationDetailsResponse -from ._models_py3 import VoiceReceiver -from ._models_py3 import WebhookReceiver +from typing import TYPE_CHECKING -from ._monitor_management_client_enums import ReceiverStatus +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models_py3 import ( # type: ignore + ActionDetail, + ActionGroupList, + ActionGroupPatchBody, + ActionGroupResource, + ArmRoleReceiver, + AutomationRunbookReceiver, + AzureAppPushReceiver, + AzureFunctionReceiver, + AzureResource, + Context, + EmailReceiver, + EnableRequest, + ErrorResponse, + EventHubReceiver, + ItsmReceiver, + LogicAppReceiver, + NotificationRequestBody, + SmsReceiver, + TestNotificationDetailsResponse, + VoiceReceiver, + WebhookReceiver, +) + +from ._monitor_management_client_enums import ( # type: ignore + ReceiverStatus, +) from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ @@ -57,5 +68,5 @@ "WebhookReceiver", "ReceiverStatus", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_01_01/models/_models_py3.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_01_01/models/_models_py3.py index f75c74e4eec6..e23a66e759d6 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_01_01/models/_models_py3.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_01_01/models/_models_py3.py @@ -1,5 +1,5 @@ -# coding=utf-8 # 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. @@ -12,7 +12,6 @@ from ... import _serialization if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from .. import models as _models @@ -141,7 +140,7 @@ class AzureResource(_serialization.Model): 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: Azure resource Id. :vartype id: str @@ -185,12 +184,12 @@ def __init__(self, *, location: str, tags: Optional[Dict[str, str]] = None, **kw self.tags = tags -class ActionGroupResource(AzureResource): # pylint: disable=too-many-instance-attributes +class ActionGroupResource(AzureResource): """An action group 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: Azure resource Id. :vartype id: str @@ -352,7 +351,7 @@ def __init__( class ArmRoleReceiver(_serialization.Model): """An arm role receiver. - 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 name of the arm role receiver. Names must be unique across all receivers within an action group. Required. @@ -393,7 +392,7 @@ def __init__(self, *, name: str, role_id: str, use_common_alert_schema: bool = F class AutomationRunbookReceiver(_serialization.Model): """The Azure Automation Runbook notification receiver. - 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 automation_account_id: The Azure automation account Id which holds this runbook and authenticate to Azure resource. Required. @@ -471,7 +470,7 @@ def __init__( class AzureAppPushReceiver(_serialization.Model): """The Azure mobile App push notification receiver. - 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 name of the Azure mobile app push receiver. Names must be unique across all receivers within an action group. Required. @@ -506,7 +505,7 @@ def __init__(self, *, name: str, email_address: str, **kwargs: Any) -> None: class AzureFunctionReceiver(_serialization.Model): """An azure function receiver. - 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 name of the azure function receiver. Names must be unique across all receivers within an action group. Required. @@ -600,7 +599,7 @@ class EmailReceiver(_serialization.Model): 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 name: The name of the email receiver. Names must be unique across all receivers within an action group. Required. @@ -647,7 +646,7 @@ def __init__(self, *, name: str, email_address: str, use_common_alert_schema: bo class EnableRequest(_serialization.Model): """Describes a receiver that should be resubscribed. - 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 receiver_name: The name of the receiver to resubscribe. Required. :vartype receiver_name: str @@ -699,7 +698,7 @@ def __init__(self, *, code: Optional[str] = None, message: Optional[str] = None, class EventHubReceiver(_serialization.Model): """An Event hub receiver. - 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 name of the Event hub receiver. Names must be unique across all receivers within an action group. Required. @@ -770,7 +769,7 @@ def __init__( class ItsmReceiver(_serialization.Model): """An Itsm receiver. - 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 name of the Itsm receiver. Names must be unique across all receivers within an action group. Required. @@ -784,7 +783,7 @@ class ItsmReceiver(_serialization.Model): CreateMultipleWorkItems option will be part of this blob as well. Required. :vartype ticket_configuration: str :ivar region: Region in which workspace resides. Supported - values:'centralindia','japaneast','southeastasia','australiasoutheast','uksouth','westcentralus','canadacentral','eastus','westeurope'. + values:'centralindia','japaneast','southeastasia','australiasoutheast','uksouth','westcentralus','canadacentral','eastus','westeurope'. # pylint: disable=line-too-long Required. :vartype region: str """ @@ -821,7 +820,7 @@ def __init__( CreateMultipleWorkItems option will be part of this blob as well. Required. :paramtype ticket_configuration: str :keyword region: Region in which workspace resides. Supported - values:'centralindia','japaneast','southeastasia','australiasoutheast','uksouth','westcentralus','canadacentral','eastus','westeurope'. + values:'centralindia','japaneast','southeastasia','australiasoutheast','uksouth','westcentralus','canadacentral','eastus','westeurope'. # pylint: disable=line-too-long Required. :paramtype region: str """ @@ -836,7 +835,7 @@ def __init__( class LogicAppReceiver(_serialization.Model): """A logic app receiver. - 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 name of the logic app receiver. Names must be unique across all receivers within an action group. Required. @@ -883,10 +882,10 @@ def __init__( self.use_common_alert_schema = use_common_alert_schema -class NotificationRequestBody(_serialization.Model): # pylint: disable=too-many-instance-attributes +class NotificationRequestBody(_serialization.Model): """The request body which contain contact detail metadata. - 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 alert_type: The value of the supported alert type. Supported alert type values are: servicehealth, metricstaticthreshold, metricsdynamicthreshold, logalertv2, smartalert, @@ -1018,7 +1017,7 @@ class SmsReceiver(_serialization.Model): 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 name: The name of the SMS receiver. Names must be unique across all receivers within an action group. Required. @@ -1066,7 +1065,7 @@ def __init__(self, *, name: str, country_code: str, phone_number: str, **kwargs: class TestNotificationDetailsResponse(_serialization.Model): """The details of the test notification results. - 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 context: The context info. :vartype context: ~azure.mgmt.monitor.v2023_01_01.models.Context @@ -1125,7 +1124,7 @@ def __init__( class VoiceReceiver(_serialization.Model): """A voice receiver. - 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 name of the voice receiver. Names must be unique across all receivers within an action group. Required. @@ -1167,7 +1166,7 @@ def __init__(self, *, name: str, country_code: str, phone_number: str, **kwargs: class WebhookReceiver(_serialization.Model): """A webhook receiver. - 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 name of the webhook receiver. Names must be unique across all receivers within an action group. Required. diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_01_01/operations/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_01_01/operations/__init__.py index 05f0527dc979..410e631e0472 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_01_01/operations/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_01_01/operations/__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 ._action_groups_operations import ActionGroupsOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._action_groups_operations import ActionGroupsOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ "ActionGroupsOperations", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_01_01/operations/_action_groups_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_01_01/operations/_action_groups_operations.py index 8dc6e1859808..7dfcf58be4e5 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_01_01/operations/_action_groups_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_01_01/operations/_action_groups_operations.py @@ -6,7 +6,9 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload +from io import IOBase +import sys +from typing import Any, Callable, Dict, IO, Iterable, Iterator, Optional, Type, TypeVar, Union, cast, overload import urllib.parse from azure.core.exceptions import ( @@ -15,13 +17,14 @@ 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 @@ -29,8 +32,11 @@ from .. import models as _models from ..._serialization import Serializer -from .._vendor import _convert_request, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -61,7 +67,7 @@ def build_create_or_update_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -96,7 +102,7 @@ def build_get_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -129,7 +135,7 @@ def build_delete_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -163,7 +169,7 @@ def build_update_request( "actionGroupName": _SERIALIZER.url("action_group_name", action_group_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -199,7 +205,7 @@ def build_create_notifications_at_action_group_resource_level_request( # pylint "actionGroupName": _SERIALIZER.url("action_group_name", action_group_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -235,7 +241,7 @@ def build_get_test_notifications_at_action_group_resource_level_request( # pyli "notificationId": _SERIALIZER.url("notification_id", notification_id, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -259,7 +265,7 @@ def build_list_by_subscription_id_request(subscription_id: str, **kwargs: Any) - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -289,7 +295,7 @@ def build_list_by_resource_group_request(resource_group_name: str, subscription_ "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -323,7 +329,7 @@ def build_enable_receiver_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -354,6 +360,7 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @overload def create_or_update( @@ -377,7 +384,6 @@ def create_or_update( :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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2023_01_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -388,7 +394,7 @@ def create_or_update( self, resource_group_name: str, action_group_name: str, - action_group: IO, + action_group: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -401,11 +407,10 @@ def create_or_update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group: The action group to create or use for the update. Required. - :type action_group: IO + :type action_group: 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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2023_01_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -416,7 +421,7 @@ def create_or_update( self, resource_group_name: str, action_group_name: str, - action_group: Union[_models.ActionGroupResource, IO], + action_group: Union[_models.ActionGroupResource, IO[bytes]], **kwargs: Any ) -> _models.ActionGroupResource: """Create a new action group or update an existing one. @@ -427,17 +432,13 @@ def create_or_update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group: The action group to create or use for the update. Is either a - ActionGroupResource type or a IO type. Required. - :type action_group: ~azure.mgmt.monitor.v2023_01_01.models.ActionGroupResource 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 + ActionGroupResource type or a IO[bytes] type. Required. + :type action_group: ~azure.mgmt.monitor.v2023_01_01.models.ActionGroupResource or IO[bytes] :return: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2023_01_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -448,19 +449,19 @@ def create_or_update( _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", "2023-01-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2023-01-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ActionGroupResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(action_group, (IO, bytes)): + if isinstance(action_group, (IOBase, bytes)): _content = action_group else: _json = self._serialize.body(action_group, "ActionGroupResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, action_group_name=action_group_name, subscription_id=self._config.subscription_id, @@ -468,16 +469,14 @@ def create_or_update( 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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -487,21 +486,13 @@ def create_or_update( 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("ActionGroupResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("ActionGroupResource", pipeline_response) + deserialized = self._deserialize("ActionGroupResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/actionGroups/{actionGroupName}" - } - @distributed_trace def get(self, resource_group_name: str, action_group_name: str, **kwargs: Any) -> _models.ActionGroupResource: """Get an action group. @@ -511,12 +502,11 @@ def get(self, resource_group_name: str, action_group_name: str, **kwargs: Any) - :type resource_group_name: str :param action_group_name: The name of the action group. Required. :type action_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2023_01_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -527,24 +517,22 @@ def get(self, resource_group_name: str, action_group_name: str, **kwargs: Any) - _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-01-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2023-01-01")) cls: ClsType[_models.ActionGroupResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, action_group_name=action_group_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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -554,16 +542,12 @@ def get(self, resource_group_name: str, action_group_name: str, **kwargs: Any) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ActionGroupResource", pipeline_response) + deserialized = self._deserialize("ActionGroupResource", 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.Insights/actionGroups/{actionGroupName}" - } + return deserialized # type: ignore @distributed_trace def delete( # pylint: disable=inconsistent-return-statements @@ -576,12 +560,11 @@ def delete( # pylint: disable=inconsistent-return-statements :type resource_group_name: str :param action_group_name: The name of the action group. Required. :type action_group_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, @@ -592,24 +575,22 @@ def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-01-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2023-01-01")) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, action_group_name=action_group_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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -620,11 +601,7 @@ def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/actionGroups/{actionGroupName}" - } + return cls(pipeline_response, None, {}) # type: ignore @overload def update( @@ -648,7 +625,6 @@ def update( :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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2023_01_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -659,7 +635,7 @@ def update( self, resource_group_name: str, action_group_name: str, - action_group_patch: IO, + action_group_patch: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -672,11 +648,10 @@ def update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group_patch: Parameters supplied to the operation. Required. - :type action_group_patch: IO + :type action_group_patch: 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: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2023_01_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -687,7 +662,7 @@ def update( self, resource_group_name: str, action_group_name: str, - action_group_patch: Union[_models.ActionGroupPatchBody, IO], + action_group_patch: Union[_models.ActionGroupPatchBody, IO[bytes]], **kwargs: Any ) -> _models.ActionGroupResource: """Updates an existing action group's tags. To update other fields use the CreateOrUpdate method. @@ -698,17 +673,14 @@ def update( :param action_group_name: The name of the action group. Required. :type action_group_name: str :param action_group_patch: Parameters supplied to the operation. Is either a - ActionGroupPatchBody type or a IO type. Required. - :type action_group_patch: ~azure.mgmt.monitor.v2023_01_01.models.ActionGroupPatchBody 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 + ActionGroupPatchBody type or a IO[bytes] type. Required. + :type action_group_patch: ~azure.mgmt.monitor.v2023_01_01.models.ActionGroupPatchBody or + IO[bytes] :return: ActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2023_01_01.models.ActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -719,19 +691,19 @@ def update( _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", "2023-01-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2023-01-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.ActionGroupResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(action_group_patch, (IO, bytes)): + if isinstance(action_group_patch, (IOBase, bytes)): _content = action_group_patch else: _json = self._serialize.body(action_group_patch, "ActionGroupPatchBody") - request = build_update_request( + _request = build_update_request( resource_group_name=resource_group_name, action_group_name=action_group_name, subscription_id=self._config.subscription_id, @@ -739,16 +711,14 @@ def update( 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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -758,25 +728,21 @@ def update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("ActionGroupResource", pipeline_response) + deserialized = self._deserialize("ActionGroupResource", 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.Insights/actionGroups/{actionGroupName}" - } + return deserialized # type: ignore def _create_notifications_at_action_group_resource_level_initial( # pylint: disable=name-too-long self, resource_group_name: str, action_group_name: str, - notification_request: Union[_models.NotificationRequestBody, IO], + notification_request: Union[_models.NotificationRequestBody, IO[bytes]], **kwargs: Any - ) -> Optional[_models.TestNotificationDetailsResponse]: - error_map = { + ) -> Iterator[bytes]: + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -787,19 +753,19 @@ def _create_notifications_at_action_group_resource_level_initial( # pylint: dis _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", "2023-01-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2023-01-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Optional[_models.TestNotificationDetailsResponse]] = kwargs.pop("cls", None) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(notification_request, (IO, bytes)): + if isinstance(notification_request, (IOBase, bytes)): _content = notification_request else: _json = self._serialize.body(notification_request, "NotificationRequestBody") - request = build_create_notifications_at_action_group_resource_level_request( + _request = build_create_notifications_at_action_group_resource_level_request( resource_group_name=resource_group_name, action_group_name=action_group_name, subscription_id=self._config.subscription_id, @@ -807,41 +773,38 @@ def _create_notifications_at_action_group_resource_level_initial( # pylint: dis content_type=content_type, json=_json, content=_content, - template_url=self._create_notifications_at_action_group_resource_level_initial.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 202]: + 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) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = None response_headers = {} - if response.status_code == 200: - deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response) - if response.status_code == 202: response_headers["location"] = self._deserialize("str", response.headers.get("location")) - if cls: - return cls(pipeline_response, deserialized, response_headers) + deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - return deserialized + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore - _create_notifications_at_action_group_resource_level_initial.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/actionGroups/{actionGroupName}/createNotifications" - } + return deserialized # type: ignore @overload def begin_create_notifications_at_action_group_resource_level( # pylint: disable=name-too-long @@ -866,14 +829,6 @@ def begin_create_notifications_at_action_group_resource_level( # pylint: disabl :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 TestNotificationDetailsResponse or the result of cls(response) :rtype: @@ -886,7 +841,7 @@ def begin_create_notifications_at_action_group_resource_level( # pylint: disabl self, resource_group_name: str, action_group_name: str, - notification_request: IO, + notification_request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -900,18 +855,10 @@ def begin_create_notifications_at_action_group_resource_level( # pylint: disabl :type action_group_name: str :param notification_request: The notification request body which includes the contact details. Required. - :type notification_request: IO + :type notification_request: 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 TestNotificationDetailsResponse or the result of cls(response) :rtype: @@ -924,7 +871,7 @@ def begin_create_notifications_at_action_group_resource_level( # pylint: disabl self, resource_group_name: str, action_group_name: str, - notification_request: Union[_models.NotificationRequestBody, IO], + notification_request: Union[_models.NotificationRequestBody, IO[bytes]], **kwargs: Any ) -> LROPoller[_models.TestNotificationDetailsResponse]: """Send test notifications to a set of provided receivers. @@ -935,20 +882,9 @@ def begin_create_notifications_at_action_group_resource_level( # pylint: disabl :param action_group_name: The name of the action group. Required. :type action_group_name: str :param notification_request: The notification request body which includes the contact details. - Is either a NotificationRequestBody type or a IO type. Required. + Is either a NotificationRequestBody type or a IO[bytes] type. Required. :type notification_request: ~azure.mgmt.monitor.v2023_01_01.models.NotificationRequestBody 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. + IO[bytes] :return: An instance of LROPoller that returns either TestNotificationDetailsResponse or the result of cls(response) :rtype: @@ -958,7 +894,7 @@ def begin_create_notifications_at_action_group_resource_level( # pylint: disabl _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", "2023-01-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2023-01-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.TestNotificationDetailsResponse] = kwargs.pop("cls", None) polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) @@ -976,12 +912,13 @@ def begin_create_notifications_at_action_group_resource_level( # pylint: disabl 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("TestNotificationDetailsResponse", pipeline_response) + deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized if polling is True: @@ -993,17 +930,15 @@ def get_long_running_output(pipeline_response): else: polling_method = polling if cont_token: - return LROPoller.from_continuation_token( + return LROPoller[_models.TestNotificationDetailsResponse].from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output, ) - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore - - begin_create_notifications_at_action_group_resource_level.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/actionGroups/{actionGroupName}/createNotifications" - } + return LROPoller[_models.TestNotificationDetailsResponse]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) @distributed_trace def get_test_notifications_at_action_group_resource_level( # pylint: disable=name-too-long @@ -1018,12 +953,11 @@ def get_test_notifications_at_action_group_resource_level( # pylint: disable=na :type action_group_name: str :param notification_id: The notification id. Required. :type notification_id: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: TestNotificationDetailsResponse or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2023_01_01.models.TestNotificationDetailsResponse :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1034,25 +968,23 @@ def get_test_notifications_at_action_group_resource_level( # pylint: disable=na _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-01-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2023-01-01")) cls: ClsType[_models.TestNotificationDetailsResponse] = kwargs.pop("cls", None) - request = build_get_test_notifications_at_action_group_resource_level_request( + _request = build_get_test_notifications_at_action_group_resource_level_request( resource_group_name=resource_group_name, action_group_name=action_group_name, notification_id=notification_id, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get_test_notifications_at_action_group_resource_level.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1062,22 +994,17 @@ def get_test_notifications_at_action_group_resource_level( # pylint: disable=na error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response) + deserialized = self._deserialize("TestNotificationDetailsResponse", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get_test_notifications_at_action_group_resource_level.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/actionGroups/{actionGroupName}/notificationStatus/{notificationId}" - } + return deserialized # type: ignore @distributed_trace def list_by_subscription_id(self, **kwargs: Any) -> Iterable["_models.ActionGroupResource"]: """Get a list of all action groups in a subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ActionGroupResource or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.monitor.v2023_01_01.models.ActionGroupResource] @@ -1086,10 +1013,10 @@ def list_by_subscription_id(self, **kwargs: Any) -> Iterable["_models.ActionGrou _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-01-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2023-01-01")) cls: ClsType[_models.ActionGroupList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1100,15 +1027,13 @@ def list_by_subscription_id(self, **kwargs: Any) -> Iterable["_models.ActionGrou def prepare_request(next_link=None): if not next_link: - request = build_list_by_subscription_id_request( + _request = build_list_by_subscription_id_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_subscription_id.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -1119,14 +1044,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("ActionGroupList", pipeline_response) @@ -1136,11 +1060,11 @@ def extract_data(pipeline_response): return None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1153,10 +1077,6 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_by_subscription_id.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/actionGroups" - } - @distributed_trace def list_by_resource_group( self, resource_group_name: str, **kwargs: Any @@ -1166,7 +1086,6 @@ def list_by_resource_group( :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ActionGroupResource or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.monitor.v2023_01_01.models.ActionGroupResource] @@ -1175,10 +1094,10 @@ def list_by_resource_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-01-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2023-01-01")) cls: ClsType[_models.ActionGroupList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1189,16 +1108,14 @@ 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_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -1209,14 +1126,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("ActionGroupList", pipeline_response) @@ -1226,11 +1142,11 @@ def extract_data(pipeline_response): return None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1243,12 +1159,8 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/actionGroups" - } - @overload - def enable_receiver( # pylint: disable=inconsistent-return-statements + def enable_receiver( self, resource_group_name: str, action_group_name: str, @@ -1270,18 +1182,17 @@ def enable_receiver( # pylint: disable=inconsistent-return-statements :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: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def enable_receiver( # pylint: disable=inconsistent-return-statements + def enable_receiver( self, resource_group_name: str, action_group_name: str, - enable_request: IO, + enable_request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -1295,11 +1206,10 @@ def enable_receiver( # pylint: disable=inconsistent-return-statements :param action_group_name: The name of the action group. Required. :type action_group_name: str :param enable_request: The receiver to re-enable. Required. - :type enable_request: IO + :type enable_request: 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: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1310,7 +1220,7 @@ def enable_receiver( # pylint: disable=inconsistent-return-statements self, resource_group_name: str, action_group_name: str, - enable_request: Union[_models.EnableRequest, IO], + enable_request: Union[_models.EnableRequest, IO[bytes]], **kwargs: Any ) -> None: """Enable a receiver in an action group. This changes the receiver's status from Disabled to @@ -1321,41 +1231,40 @@ def enable_receiver( # pylint: disable=inconsistent-return-statements :type resource_group_name: str :param action_group_name: The name of the action group. Required. :type action_group_name: str - :param enable_request: The receiver to re-enable. Is either a EnableRequest type or a IO type. - Required. - :type enable_request: ~azure.mgmt.monitor.v2023_01_01.models.EnableRequest 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 + :param enable_request: The receiver to re-enable. Is either a EnableRequest type or a IO[bytes] + type. Required. + :type enable_request: ~azure.mgmt.monitor.v2023_01_01.models.EnableRequest or IO[bytes] :return: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 304: ResourceNotModifiedError, - 409: lambda response: ResourceExistsError(response=response, error_format=ARMErrorFormat), + 409: cast( + Type[HttpResponseError], + lambda response: ResourceExistsError(response=response, error_format=ARMErrorFormat), + ), } 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: str = kwargs.pop("api_version", _params.pop("api-version", "2023-01-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._api_version or "2023-01-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[None] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(enable_request, (IO, bytes)): + if isinstance(enable_request, (IOBase, bytes)): _content = enable_request else: _json = self._serialize.body(enable_request, "EnableRequest") - request = build_enable_receiver_request( + _request = build_enable_receiver_request( resource_group_name=resource_group_name, action_group_name=action_group_name, subscription_id=self._config.subscription_id, @@ -1363,28 +1272,22 @@ def enable_receiver( # pylint: disable=inconsistent-return-statements content_type=content_type, json=_json, content=_content, - template_url=self.enable_receiver.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _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) + map_error(status_code=response.status_code, response=response, error_map=error_map) # type: ignore 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, {}) - - enable_receiver.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/actionGroups/{actionGroupName}/subscribe" - } + return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_03_01_preview/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_03_01_preview/__init__.py index 2c7733bfd566..42cc62301757 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_03_01_preview/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_03_01_preview/__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 ._monitor_management_client import MonitorManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._monitor_management_client import MonitorManagementClient # type: ignore from ._version import VERSION __version__ = VERSION try: from ._patch import __all__ as _patch_all - from ._patch import * # 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__ = [ "MonitorManagementClient", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_03_01_preview/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_03_01_preview/_configuration.py index 3c8cf235fbba..32820c9a24e3 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_03_01_preview/_configuration.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_03_01_preview/_configuration.py @@ -8,18 +8,16 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy from ._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MonitorManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class MonitorManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for MonitorManagementClient. Note that all parameters used to create this instance are saved as instance @@ -33,7 +31,6 @@ class MonitorManagementClientConfiguration(Configuration): # pylint: disable=to """ def __init__(self, credential: "TokenCredential", **kwargs: Any) -> None: - super(MonitorManagementClientConfiguration, self).__init__(**kwargs) api_version: str = kwargs.pop("api_version", "2023-03-01-preview") if credential is None: @@ -43,6 +40,7 @@ def __init__(self, credential: "TokenCredential", **kwargs: Any) -> None: self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-monitor/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -51,9 +49,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.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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_03_01_preview/_metadata.json b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_03_01_preview/_metadata.json index 7ff4dcddf356..9461de688d06 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_03_01_preview/_metadata.json +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_03_01_preview/_metadata.json @@ -8,10 +8,10 @@ "host_value": "\"https://management.azure.com\"", "parameterized_host_template": null, "azure_arm": true, - "has_lro_operations": false, + "has_public_lro_operations": false, "client_side_validation": false, - "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"azurecore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "sync_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"sdkcore\": {\"azure.mgmt.core\": [\"ARMPipelineClient\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMAutoResourceProviderRegistrationPolicy\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \".._serialization\": [\"Deserializer\", \"Serializer\"]}, \"stdlib\": {\"typing_extensions\": [\"Self\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}}, \"regular\": {\"sdkcore\": {\"azure.mgmt.core\": [\"AsyncARMPipelineClient\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"AsyncARMAutoResourceProviderRegistrationPolicy\"], \"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"]}, \"local\": {\"._configuration\": [\"MonitorManagementClientConfiguration\"], \"..._serialization\": [\"Deserializer\", \"Serializer\"]}, \"stdlib\": {\"typing_extensions\": [\"Self\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "global_parameters": { "sync": { @@ -88,8 +88,8 @@ "credential_scopes": ["https://management.azure.com/.default"], "credential_call_sync": "ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", "credential_call_async": "AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)", - "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" + "sync_imports": "{\"regular\": {\"sdkcore\": {\"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMChallengeAuthenticationPolicy\", \"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", + "async_imports": "{\"regular\": {\"sdkcore\": {\"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\", \"AsyncARMChallengeAuthenticationPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"sdkcore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, "operation_groups": { "tenant_action_groups": "TenantActionGroupsOperations" diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_03_01_preview/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_03_01_preview/_monitor_management_client.py index d3b97cc5c89b..e254fc9cd251 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_03_01_preview/_monitor_management_client.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_03_01_preview/_monitor_management_client.py @@ -8,9 +8,12 @@ from copy import deepcopy from typing import Any, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient +from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy from . import models as _models from .._serialization import Deserializer, Serializer @@ -18,11 +21,10 @@ from .operations import TenantActionGroupsOperations if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MonitorManagementClient: # pylint: disable=client-accepts-api-version-keyword +class MonitorManagementClient: """Monitor Management Client. :ivar tenant_action_groups: TenantActionGroupsOperations operations @@ -41,17 +43,35 @@ def __init__( self, credential: "TokenCredential", base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: self._config = MonitorManagementClientConfiguration(credential=credential, **kwargs) - self._client: ARMPipelineClient = ARMPipelineClient(base_url=base_url, config=self._config, **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), + 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=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.tenant_action_groups = TenantActionGroupsOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2023-03-01-preview" ) - 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 @@ -71,12 +91,12 @@ 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) -> None: self._client.close() - def __enter__(self) -> "MonitorManagementClient": + def __enter__(self) -> Self: self._client.__enter__() return self diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_03_01_preview/_vendor.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_03_01_preview/_vendor.py deleted file mode 100644 index bd0df84f5319..000000000000 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_03_01_preview/_vendor.py +++ /dev/null @@ -1,30 +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 typing import List, cast - -from azure.core.pipeline.transport import HttpRequest - - -def _convert_request(request, files=None): - data = request.content if not files else None - request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) - if files: - request.set_formdata_body(files) - return request - - -def _format_url_section(template, **kwargs): - components = template.split("/") - while components: - try: - return template.format(**kwargs) - except KeyError as key: - # Need the cast, as for some reasons "split" is typed as list[str | Any] - formatted_components = cast(List[str], template.split("/")) - components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] - template = "/".join(components) diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_03_01_preview/_version.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_03_01_preview/_version.py index 394ee7c0c03c..e5754a47ce68 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_03_01_preview/_version.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_03_01_preview/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "6.0.2" +VERSION = "1.0.0b1" diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_03_01_preview/aio/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_03_01_preview/aio/__init__.py index 2c151bb41c19..3df30ff42149 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_03_01_preview/aio/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_03_01_preview/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 ._monitor_management_client import MonitorManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._monitor_management_client import MonitorManagementClient # type: ignore try: from ._patch import __all__ as _patch_all - from ._patch import * # 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__ = [ "MonitorManagementClient", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_03_01_preview/aio/_configuration.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_03_01_preview/aio/_configuration.py index e95fb3f74ae1..d9fa6a3b0bde 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_03_01_preview/aio/_configuration.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_03_01_preview/aio/_configuration.py @@ -8,18 +8,16 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy from .._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MonitorManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class MonitorManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for MonitorManagementClient. Note that all parameters used to create this instance are saved as instance @@ -33,7 +31,6 @@ class MonitorManagementClientConfiguration(Configuration): # pylint: disable=to """ def __init__(self, credential: "AsyncTokenCredential", **kwargs: Any) -> None: - super(MonitorManagementClientConfiguration, self).__init__(**kwargs) api_version: str = kwargs.pop("api_version", "2023-03-01-preview") if credential is None: @@ -43,6 +40,7 @@ def __init__(self, credential: "AsyncTokenCredential", **kwargs: Any) -> None: self.api_version = api_version self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-monitor/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -51,9 +49,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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_03_01_preview/aio/_monitor_management_client.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_03_01_preview/aio/_monitor_management_client.py index 5bafc0c09b2b..98f8d2bca364 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_03_01_preview/aio/_monitor_management_client.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_03_01_preview/aio/_monitor_management_client.py @@ -8,9 +8,12 @@ from copy import deepcopy from typing import Any, Awaitable, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient +from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy from .. import models as _models from ..._serialization import Deserializer, Serializer @@ -18,11 +21,10 @@ from .operations import TenantActionGroupsOperations if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MonitorManagementClient: # pylint: disable=client-accepts-api-version-keyword +class MonitorManagementClient: """Monitor Management Client. :ivar tenant_action_groups: TenantActionGroupsOperations operations @@ -41,17 +43,37 @@ def __init__( self, credential: "AsyncTokenCredential", base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: self._config = MonitorManagementClientConfiguration(credential=credential, **kwargs) - self._client: AsyncARMPipelineClient = AsyncARMPipelineClient(base_url=base_url, config=self._config, **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=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.tenant_action_groups = TenantActionGroupsOperations( - self._client, self._config, self._serialize, self._deserialize + self._client, self._config, self._serialize, self._deserialize, "2023-03-01-preview" ) - 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 @@ -71,12 +93,12 @@ 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) -> "MonitorManagementClient": + async def __aenter__(self) -> Self: await self._client.__aenter__() return self diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_03_01_preview/aio/operations/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_03_01_preview/aio/operations/__init__.py index 19fc23938681..c6363b8f0b2f 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_03_01_preview/aio/operations/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_03_01_preview/aio/operations/__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 ._tenant_action_groups_operations import TenantActionGroupsOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._tenant_action_groups_operations import TenantActionGroupsOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ "TenantActionGroupsOperations", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_03_01_preview/aio/operations/_tenant_action_groups_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_03_01_preview/aio/operations/_tenant_action_groups_operations.py index dd43cf92c8c6..dd669048688f 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_03_01_preview/aio/operations/_tenant_action_groups_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_03_01_preview/aio/operations/_tenant_action_groups_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload import urllib.parse @@ -19,15 +20,13 @@ 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 ...operations._tenant_action_groups_operations import ( build_create_or_update_request, build_delete_request, @@ -36,6 +35,10 @@ build_update_request, ) +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -58,6 +61,7 @@ def __init__(self, *args, **kwargs) -> None: 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @overload async def create_or_update( @@ -83,7 +87,6 @@ async def create_or_update( :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: TenantActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2023_03_01_preview.models.TenantActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -95,7 +98,7 @@ async def create_or_update( management_group_id: str, tenant_action_group_name: str, x_ms_client_tenant_id: str, - action_group: IO, + action_group: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -109,11 +112,10 @@ async def create_or_update( :param x_ms_client_tenant_id: The tenant ID of the client making the request. Required. :type x_ms_client_tenant_id: str :param action_group: The tenant action group to create or use for the update. Required. - :type action_group: IO + :type action_group: 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: TenantActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2023_03_01_preview.models.TenantActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -125,7 +127,7 @@ async def create_or_update( management_group_id: str, tenant_action_group_name: str, x_ms_client_tenant_id: str, - action_group: Union[_models.TenantActionGroupResource, IO], + action_group: Union[_models.TenantActionGroupResource, IO[bytes]], **kwargs: Any ) -> _models.TenantActionGroupResource: """Create a new tenant action group or update an existing one. @@ -137,18 +139,14 @@ async def create_or_update( :param x_ms_client_tenant_id: The tenant ID of the client making the request. Required. :type x_ms_client_tenant_id: str :param action_group: The tenant action group to create or use for the update. Is either a - TenantActionGroupResource type or a IO type. Required. + TenantActionGroupResource type or a IO[bytes] type. Required. :type action_group: ~azure.mgmt.monitor.v2023_03_01_preview.models.TenantActionGroupResource 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 + IO[bytes] :return: TenantActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2023_03_01_preview.models.TenantActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -159,19 +157,21 @@ async def create_or_update( _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", "2023-03-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2023-03-01-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.TenantActionGroupResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(action_group, (IO, bytes)): + if isinstance(action_group, (IOBase, bytes)): _content = action_group else: _json = self._serialize.body(action_group, "TenantActionGroupResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( management_group_id=management_group_id, tenant_action_group_name=tenant_action_group_name, x_ms_client_tenant_id=x_ms_client_tenant_id, @@ -179,16 +179,14 @@ async def create_or_update( 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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -198,21 +196,13 @@ async def create_or_update( 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("TenantActionGroupResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("TenantActionGroupResource", pipeline_response) + deserialized = self._deserialize("TenantActionGroupResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create_or_update.metadata = { - "url": "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Insights/tenantActionGroups/{tenantActionGroupName}" - } - @distributed_trace_async async def get( self, management_group_id: str, tenant_action_group_name: str, x_ms_client_tenant_id: str, **kwargs: Any @@ -225,12 +215,11 @@ async def get( :type tenant_action_group_name: str :param x_ms_client_tenant_id: The tenant ID of the client making the request. Required. :type x_ms_client_tenant_id: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: TenantActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2023_03_01_preview.models.TenantActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -241,24 +230,24 @@ async def get( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-03-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2023-03-01-preview") + ) cls: ClsType[_models.TenantActionGroupResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( management_group_id=management_group_id, tenant_action_group_name=tenant_action_group_name, x_ms_client_tenant_id=x_ms_client_tenant_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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -268,19 +257,15 @@ async def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("TenantActionGroupResource", pipeline_response) + deserialized = self._deserialize("TenantActionGroupResource", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get.metadata = { - "url": "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Insights/tenantActionGroups/{tenantActionGroupName}" - } + return deserialized # type: ignore @distributed_trace_async - async def delete( # pylint: disable=inconsistent-return-statements + async def delete( self, management_group_id: str, tenant_action_group_name: str, x_ms_client_tenant_id: str, **kwargs: Any ) -> None: """Delete a tenant action group. @@ -291,12 +276,11 @@ async def delete( # pylint: disable=inconsistent-return-statements :type tenant_action_group_name: str :param x_ms_client_tenant_id: The tenant ID of the client making the request. Required. :type x_ms_client_tenant_id: 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, @@ -307,24 +291,24 @@ async def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-03-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2023-03-01-preview") + ) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( management_group_id=management_group_id, tenant_action_group_name=tenant_action_group_name, x_ms_client_tenant_id=x_ms_client_tenant_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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -335,11 +319,7 @@ async def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Insights/tenantActionGroups/{tenantActionGroupName}" - } + return cls(pipeline_response, None, {}) # type: ignore @overload async def update( @@ -367,7 +347,6 @@ async def update( :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: TenantActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2023_03_01_preview.models.TenantActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -379,7 +358,7 @@ async def update( management_group_id: str, tenant_action_group_name: str, x_ms_client_tenant_id: str, - tenant_action_group_patch: IO, + tenant_action_group_patch: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -394,11 +373,10 @@ async def update( :param x_ms_client_tenant_id: The tenant ID of the client making the request. Required. :type x_ms_client_tenant_id: str :param tenant_action_group_patch: Parameters supplied to the operation. Required. - :type tenant_action_group_patch: IO + :type tenant_action_group_patch: 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: TenantActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2023_03_01_preview.models.TenantActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -410,7 +388,7 @@ async def update( management_group_id: str, tenant_action_group_name: str, x_ms_client_tenant_id: str, - tenant_action_group_patch: Union[_models.ActionGroupPatchBody, IO], + tenant_action_group_patch: Union[_models.ActionGroupPatchBody, IO[bytes]], **kwargs: Any ) -> _models.TenantActionGroupResource: """Updates an existing tenant action group's tags. To update other fields use the CreateOrUpdate @@ -423,18 +401,14 @@ async def update( :param x_ms_client_tenant_id: The tenant ID of the client making the request. Required. :type x_ms_client_tenant_id: str :param tenant_action_group_patch: Parameters supplied to the operation. Is either a - ActionGroupPatchBody type or a IO type. Required. + ActionGroupPatchBody type or a IO[bytes] type. Required. :type tenant_action_group_patch: - ~azure.mgmt.monitor.v2023_03_01_preview.models.ActionGroupPatchBody 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 + ~azure.mgmt.monitor.v2023_03_01_preview.models.ActionGroupPatchBody or IO[bytes] :return: TenantActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2023_03_01_preview.models.TenantActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -445,19 +419,21 @@ async def update( _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", "2023-03-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2023-03-01-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.TenantActionGroupResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(tenant_action_group_patch, (IO, bytes)): + if isinstance(tenant_action_group_patch, (IOBase, bytes)): _content = tenant_action_group_patch else: _json = self._serialize.body(tenant_action_group_patch, "ActionGroupPatchBody") - request = build_update_request( + _request = build_update_request( management_group_id=management_group_id, tenant_action_group_name=tenant_action_group_name, x_ms_client_tenant_id=x_ms_client_tenant_id, @@ -465,16 +441,14 @@ async def update( 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) + _request.url = self._client.format_url(_request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -484,28 +458,24 @@ async def update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("TenantActionGroupResource", pipeline_response) + deserialized = self._deserialize("TenantActionGroupResource", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - update.metadata = { - "url": "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Insights/tenantActionGroups/{tenantActionGroupName}" - } + return deserialized # type: ignore @distributed_trace def list_by_management_group_id( self, management_group_id: str, x_ms_client_tenant_id: str, **kwargs: Any ) -> AsyncIterable["_models.TenantActionGroupResource"]: + # pylint: disable=line-too-long """Get a list of all tenant action groups in a management group. :param management_group_id: The management group id. Required. :type management_group_id: str :param x_ms_client_tenant_id: The tenant ID of the client making the request. Required. :type x_ms_client_tenant_id: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either TenantActionGroupResource or the result of cls(response) :rtype: @@ -515,10 +485,12 @@ def list_by_management_group_id( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-03-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2023-03-01-preview") + ) cls: ClsType[_models.TenantActionGroupList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -529,16 +501,14 @@ def list_by_management_group_id( def prepare_request(next_link=None): if not next_link: - request = build_list_by_management_group_id_request( + _request = build_list_by_management_group_id_request( management_group_id=management_group_id, x_ms_client_tenant_id=x_ms_client_tenant_id, api_version=api_version, - template_url=self.list_by_management_group_id.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -549,14 +519,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("TenantActionGroupList", pipeline_response) @@ -566,11 +535,11 @@ async def extract_data(pipeline_response): return None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -582,7 +551,3 @@ async def get_next(next_link=None): return pipeline_response return AsyncItemPaged(get_next, extract_data) - - list_by_management_group_id.metadata = { - "url": "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Insights/tenantActionGroups" - } diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_03_01_preview/models/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_03_01_preview/models/__init__.py index ff5d331e257f..9bb27ab14cef 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_03_01_preview/models/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_03_01_preview/models/__init__.py @@ -5,21 +5,32 @@ # 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 ActionGroupPatchBody -from ._models_py3 import AzureAppPushReceiver -from ._models_py3 import AzureResource -from ._models_py3 import EmailReceiver -from ._models_py3 import ErrorResponse -from ._models_py3 import SmsReceiver -from ._models_py3 import TenantActionGroupList -from ._models_py3 import TenantActionGroupResource -from ._models_py3 import VoiceReceiver -from ._models_py3 import WebhookReceiver +from typing import TYPE_CHECKING -from ._monitor_management_client_enums import ReceiverStatus +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models_py3 import ( # type: ignore + ActionGroupPatchBody, + AzureAppPushReceiver, + AzureResource, + EmailReceiver, + ErrorResponse, + SmsReceiver, + TenantActionGroupList, + TenantActionGroupResource, + VoiceReceiver, + WebhookReceiver, +) + +from ._monitor_management_client_enums import ( # type: ignore + ReceiverStatus, +) from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ @@ -35,5 +46,5 @@ "WebhookReceiver", "ReceiverStatus", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_03_01_preview/models/_models_py3.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_03_01_preview/models/_models_py3.py index 0228f1dc008e..049f20400ace 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_03_01_preview/models/_models_py3.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_03_01_preview/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. @@ -12,7 +11,6 @@ from ... import _serialization if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from .. import models as _models @@ -47,7 +45,7 @@ def __init__(self, *, tags: Optional[Dict[str, str]] = None, enabled: bool = Tru class AzureAppPushReceiver(_serialization.Model): """The Azure mobile App push notification receiver. - 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 name of the Azure mobile app push receiver. Names must be unique across all receivers within a tenant action group. Required. @@ -84,7 +82,7 @@ class AzureResource(_serialization.Model): 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: Azure resource Id. :vartype id: str @@ -133,7 +131,7 @@ class EmailReceiver(_serialization.Model): 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 name: The name of the email receiver. Names must be unique across all receivers within a tenant action group. Required. @@ -208,7 +206,7 @@ class SmsReceiver(_serialization.Model): 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 name: The name of the SMS receiver. Names must be unique across all receivers within a tenant action group. Required. @@ -286,12 +284,12 @@ def __init__( self.next_link = next_link -class TenantActionGroupResource(AzureResource): # pylint: disable=too-many-instance-attributes +class TenantActionGroupResource(AzureResource): """A tenant action group 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: Azure resource Id. :vartype id: str @@ -402,7 +400,7 @@ def __init__( class VoiceReceiver(_serialization.Model): """A voice receiver. - 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 name of the voice receiver. Names must be unique across all receivers within a tenant action group. Required. @@ -444,7 +442,7 @@ def __init__(self, *, name: str, country_code: str, phone_number: str, **kwargs: class WebhookReceiver(_serialization.Model): """A webhook receiver. - 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 name of the webhook receiver. Names must be unique across all receivers within a tenant action group. Required. diff --git a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_03_01_preview/operations/__init__.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_03_01_preview/operations/__init__.py index 19fc23938681..c6363b8f0b2f 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_03_01_preview/operations/__init__.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_03_01_preview/operations/__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 ._tenant_action_groups_operations import TenantActionGroupsOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._tenant_action_groups_operations import TenantActionGroupsOperations # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ "TenantActionGroupsOperations", ] -__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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_03_01_preview/operations/_tenant_action_groups_operations.py b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_03_01_preview/operations/_tenant_action_groups_operations.py index f9e38c81b647..27e50b9fa6e5 100644 --- a/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_03_01_preview/operations/_tenant_action_groups_operations.py +++ b/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2023_03_01_preview/operations/_tenant_action_groups_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,6 +5,8 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase +import sys from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload import urllib.parse @@ -19,16 +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, _format_url_section +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -56,7 +59,7 @@ def build_create_or_update_request( "tenantActionGroupName": _SERIALIZER.url("tenant_action_group_name", tenant_action_group_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -89,7 +92,7 @@ def build_get_request( "tenantActionGroupName": _SERIALIZER.url("tenant_action_group_name", tenant_action_group_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -120,7 +123,7 @@ def build_delete_request( "tenantActionGroupName": _SERIALIZER.url("tenant_action_group_name", tenant_action_group_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -152,7 +155,7 @@ def build_update_request( "tenantActionGroupName": _SERIALIZER.url("tenant_action_group_name", tenant_action_group_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -184,7 +187,7 @@ def build_list_by_management_group_id_request( # pylint: disable=name-too-long "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -214,6 +217,7 @@ def __init__(self, *args, **kwargs): 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._api_version = input_args.pop(0) if input_args else kwargs.pop("api_version") @overload def create_or_update( @@ -239,7 +243,6 @@ def create_or_update( :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: TenantActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2023_03_01_preview.models.TenantActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -251,7 +254,7 @@ def create_or_update( management_group_id: str, tenant_action_group_name: str, x_ms_client_tenant_id: str, - action_group: IO, + action_group: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -265,11 +268,10 @@ def create_or_update( :param x_ms_client_tenant_id: The tenant ID of the client making the request. Required. :type x_ms_client_tenant_id: str :param action_group: The tenant action group to create or use for the update. Required. - :type action_group: IO + :type action_group: 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: TenantActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2023_03_01_preview.models.TenantActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -281,7 +283,7 @@ def create_or_update( management_group_id: str, tenant_action_group_name: str, x_ms_client_tenant_id: str, - action_group: Union[_models.TenantActionGroupResource, IO], + action_group: Union[_models.TenantActionGroupResource, IO[bytes]], **kwargs: Any ) -> _models.TenantActionGroupResource: """Create a new tenant action group or update an existing one. @@ -293,18 +295,14 @@ def create_or_update( :param x_ms_client_tenant_id: The tenant ID of the client making the request. Required. :type x_ms_client_tenant_id: str :param action_group: The tenant action group to create or use for the update. Is either a - TenantActionGroupResource type or a IO type. Required. + TenantActionGroupResource type or a IO[bytes] type. Required. :type action_group: ~azure.mgmt.monitor.v2023_03_01_preview.models.TenantActionGroupResource 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 + IO[bytes] :return: TenantActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2023_03_01_preview.models.TenantActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -315,19 +313,21 @@ def create_or_update( _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", "2023-03-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2023-03-01-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.TenantActionGroupResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(action_group, (IO, bytes)): + if isinstance(action_group, (IOBase, bytes)): _content = action_group else: _json = self._serialize.body(action_group, "TenantActionGroupResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( management_group_id=management_group_id, tenant_action_group_name=tenant_action_group_name, x_ms_client_tenant_id=x_ms_client_tenant_id, @@ -335,16 +335,14 @@ def create_or_update( 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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -354,21 +352,13 @@ def create_or_update( 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("TenantActionGroupResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("TenantActionGroupResource", pipeline_response) + deserialized = self._deserialize("TenantActionGroupResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create_or_update.metadata = { - "url": "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Insights/tenantActionGroups/{tenantActionGroupName}" - } - @distributed_trace def get( self, management_group_id: str, tenant_action_group_name: str, x_ms_client_tenant_id: str, **kwargs: Any @@ -381,12 +371,11 @@ def get( :type tenant_action_group_name: str :param x_ms_client_tenant_id: The tenant ID of the client making the request. Required. :type x_ms_client_tenant_id: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: TenantActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2023_03_01_preview.models.TenantActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -397,24 +386,24 @@ def get( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-03-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2023-03-01-preview") + ) cls: ClsType[_models.TenantActionGroupResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( management_group_id=management_group_id, tenant_action_group_name=tenant_action_group_name, x_ms_client_tenant_id=x_ms_client_tenant_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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -424,16 +413,12 @@ def get( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("TenantActionGroupResource", pipeline_response) + deserialized = self._deserialize("TenantActionGroupResource", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get.metadata = { - "url": "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Insights/tenantActionGroups/{tenantActionGroupName}" - } + return deserialized # type: ignore @distributed_trace def delete( # pylint: disable=inconsistent-return-statements @@ -447,12 +432,11 @@ def delete( # pylint: disable=inconsistent-return-statements :type tenant_action_group_name: str :param x_ms_client_tenant_id: The tenant ID of the client making the request. Required. :type x_ms_client_tenant_id: 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, @@ -463,24 +447,24 @@ def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-03-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2023-03-01-preview") + ) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( management_group_id=management_group_id, tenant_action_group_name=tenant_action_group_name, x_ms_client_tenant_id=x_ms_client_tenant_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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -491,11 +475,7 @@ def delete( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Insights/tenantActionGroups/{tenantActionGroupName}" - } + return cls(pipeline_response, None, {}) # type: ignore @overload def update( @@ -523,7 +503,6 @@ def update( :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: TenantActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2023_03_01_preview.models.TenantActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -535,7 +514,7 @@ def update( management_group_id: str, tenant_action_group_name: str, x_ms_client_tenant_id: str, - tenant_action_group_patch: IO, + tenant_action_group_patch: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -550,11 +529,10 @@ def update( :param x_ms_client_tenant_id: The tenant ID of the client making the request. Required. :type x_ms_client_tenant_id: str :param tenant_action_group_patch: Parameters supplied to the operation. Required. - :type tenant_action_group_patch: IO + :type tenant_action_group_patch: 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: TenantActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2023_03_01_preview.models.TenantActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -566,7 +544,7 @@ def update( management_group_id: str, tenant_action_group_name: str, x_ms_client_tenant_id: str, - tenant_action_group_patch: Union[_models.ActionGroupPatchBody, IO], + tenant_action_group_patch: Union[_models.ActionGroupPatchBody, IO[bytes]], **kwargs: Any ) -> _models.TenantActionGroupResource: """Updates an existing tenant action group's tags. To update other fields use the CreateOrUpdate @@ -579,18 +557,14 @@ def update( :param x_ms_client_tenant_id: The tenant ID of the client making the request. Required. :type x_ms_client_tenant_id: str :param tenant_action_group_patch: Parameters supplied to the operation. Is either a - ActionGroupPatchBody type or a IO type. Required. + ActionGroupPatchBody type or a IO[bytes] type. Required. :type tenant_action_group_patch: - ~azure.mgmt.monitor.v2023_03_01_preview.models.ActionGroupPatchBody 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 + ~azure.mgmt.monitor.v2023_03_01_preview.models.ActionGroupPatchBody or IO[bytes] :return: TenantActionGroupResource or the result of cls(response) :rtype: ~azure.mgmt.monitor.v2023_03_01_preview.models.TenantActionGroupResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -601,19 +575,21 @@ def update( _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", "2023-03-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2023-03-01-preview") + ) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.TenantActionGroupResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(tenant_action_group_patch, (IO, bytes)): + if isinstance(tenant_action_group_patch, (IOBase, bytes)): _content = tenant_action_group_patch else: _json = self._serialize.body(tenant_action_group_patch, "ActionGroupPatchBody") - request = build_update_request( + _request = build_update_request( management_group_id=management_group_id, tenant_action_group_name=tenant_action_group_name, x_ms_client_tenant_id=x_ms_client_tenant_id, @@ -621,16 +597,14 @@ def update( 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) + _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 + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -640,16 +614,12 @@ def update( error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("TenantActionGroupResource", pipeline_response) + deserialized = self._deserialize("TenantActionGroupResource", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - update.metadata = { - "url": "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Insights/tenantActionGroups/{tenantActionGroupName}" - } + return deserialized # type: ignore @distributed_trace def list_by_management_group_id( @@ -661,7 +631,6 @@ def list_by_management_group_id( :type management_group_id: str :param x_ms_client_tenant_id: The tenant ID of the client making the request. Required. :type x_ms_client_tenant_id: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either TenantActionGroupResource or the result of cls(response) :rtype: @@ -671,10 +640,12 @@ def list_by_management_group_id( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-03-01-preview")) + api_version: str = kwargs.pop( + "api_version", _params.pop("api-version", self._api_version or "2023-03-01-preview") + ) cls: ClsType[_models.TenantActionGroupList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -685,16 +656,14 @@ def list_by_management_group_id( def prepare_request(next_link=None): if not next_link: - request = build_list_by_management_group_id_request( + _request = build_list_by_management_group_id_request( management_group_id=management_group_id, x_ms_client_tenant_id=x_ms_client_tenant_id, api_version=api_version, - template_url=self.list_by_management_group_id.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: # make call to next link with the client's api-version @@ -705,14 +674,13 @@ def prepare_request(next_link=None): for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest( + _next_request_params["api-version"] = self._api_version + _request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("TenantActionGroupList", pipeline_response) @@ -722,11 +690,11 @@ def extract_data(pipeline_response): return None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=_stream, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -738,7 +706,3 @@ def get_next(next_link=None): return pipeline_response return ItemPaged(get_next, extract_data) - - list_by_management_group_id.metadata = { - "url": "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Insights/tenantActionGroups" - } diff --git a/sdk/monitor/azure-mgmt-monitor/generated_samples/create_or_update_action_group.py b/sdk/monitor/azure-mgmt-monitor/generated_samples/create_or_update_action_group.py index 4dd3d512ffb1..64b41ddabf75 100644 --- a/sdk/monitor/azure-mgmt-monitor/generated_samples/create_or_update_action_group.py +++ b/sdk/monitor/azure-mgmt-monitor/generated_samples/create_or_update_action_group.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.monitor import MonitorManagementClient """ diff --git a/sdk/monitor/azure-mgmt-monitor/generated_samples/delete_action_group.py b/sdk/monitor/azure-mgmt-monitor/generated_samples/delete_action_group.py index 6716be2d669f..493feb1600e8 100644 --- a/sdk/monitor/azure-mgmt-monitor/generated_samples/delete_action_group.py +++ b/sdk/monitor/azure-mgmt-monitor/generated_samples/delete_action_group.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.monitor import MonitorManagementClient """ @@ -29,11 +30,10 @@ def main(): subscription_id="187f412d-1758-44d9-b052-169e2564721d", ) - response = client.action_groups.delete( + client.action_groups.delete( resource_group_name="Default-NotificationRules", action_group_name="SampleActionGroup", ) - print(response) # x-ms-original-file: specification/monitor/resource-manager/Microsoft.Insights/stable/2023-01-01/examples/deleteActionGroup.json diff --git a/sdk/monitor/azure-mgmt-monitor/generated_samples/enable_receiver.py b/sdk/monitor/azure-mgmt-monitor/generated_samples/enable_receiver.py index 279b1f524c9f..676be389c581 100644 --- a/sdk/monitor/azure-mgmt-monitor/generated_samples/enable_receiver.py +++ b/sdk/monitor/azure-mgmt-monitor/generated_samples/enable_receiver.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.monitor import MonitorManagementClient """ @@ -29,12 +30,11 @@ def main(): subscription_id="187f412d-1758-44d9-b052-169e2564721d", ) - response = client.action_groups.enable_receiver( + client.action_groups.enable_receiver( resource_group_name="Default-NotificationRules", action_group_name="SampleActionGroup", enable_request={"receiverName": "John Doe's mobile"}, ) - print(response) # x-ms-original-file: specification/monitor/resource-manager/Microsoft.Insights/stable/2023-01-01/examples/enableReceiver.json diff --git a/sdk/monitor/azure-mgmt-monitor/generated_samples/get_action_group.py b/sdk/monitor/azure-mgmt-monitor/generated_samples/get_action_group.py index 39ea28de7e66..9f74d913e236 100644 --- a/sdk/monitor/azure-mgmt-monitor/generated_samples/get_action_group.py +++ b/sdk/monitor/azure-mgmt-monitor/generated_samples/get_action_group.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.monitor import MonitorManagementClient """ diff --git a/sdk/monitor/azure-mgmt-monitor/generated_samples/get_test_notifications_at_action_group_resource_level.py b/sdk/monitor/azure-mgmt-monitor/generated_samples/get_test_notifications_at_action_group_resource_level.py index 639516f78e98..d3f68579b6d9 100644 --- a/sdk/monitor/azure-mgmt-monitor/generated_samples/get_test_notifications_at_action_group_resource_level.py +++ b/sdk/monitor/azure-mgmt-monitor/generated_samples/get_test_notifications_at_action_group_resource_level.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.monitor import MonitorManagementClient """ diff --git a/sdk/monitor/azure-mgmt-monitor/generated_samples/list_action_groups.py b/sdk/monitor/azure-mgmt-monitor/generated_samples/list_action_groups.py index b9a9276dd2eb..27652100dfb4 100644 --- a/sdk/monitor/azure-mgmt-monitor/generated_samples/list_action_groups.py +++ b/sdk/monitor/azure-mgmt-monitor/generated_samples/list_action_groups.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.monitor import MonitorManagementClient """ @@ -29,7 +30,9 @@ def main(): subscription_id="187f412d-1758-44d9-b052-169e2564721d", ) - response = client.action_groups.list_by_subscription_id() + response = client.action_groups.list_by_resource_group( + resource_group_name="Default-NotificationRules", + ) for item in response: print(item) diff --git a/sdk/monitor/azure-mgmt-monitor/generated_samples/patch_action_group.py b/sdk/monitor/azure-mgmt-monitor/generated_samples/patch_action_group.py index ab33a88347fe..1f1831b591c6 100644 --- a/sdk/monitor/azure-mgmt-monitor/generated_samples/patch_action_group.py +++ b/sdk/monitor/azure-mgmt-monitor/generated_samples/patch_action_group.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.monitor import MonitorManagementClient """ diff --git a/sdk/monitor/azure-mgmt-monitor/generated_samples/post_test_notifications_at_action_group_resource_level.py b/sdk/monitor/azure-mgmt-monitor/generated_samples/post_test_notifications_at_action_group_resource_level.py index 1653ae8ce3cc..5e9b4f9b6a6d 100644 --- a/sdk/monitor/azure-mgmt-monitor/generated_samples/post_test_notifications_at_action_group_resource_level.py +++ b/sdk/monitor/azure-mgmt-monitor/generated_samples/post_test_notifications_at_action_group_resource_level.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.monitor import MonitorManagementClient """ diff --git a/sdk/monitor/azure-mgmt-monitor/generated_tests/conftest.py b/sdk/monitor/azure-mgmt-monitor/generated_tests/conftest.py new file mode 100644 index 000000000000..f4702001bc6c --- /dev/null +++ b/sdk/monitor/azure-mgmt-monitor/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): + monitormanagement_subscription_id = os.environ.get("AZURE_SUBSCRIPTION_ID", "00000000-0000-0000-0000-000000000000") + monitormanagement_tenant_id = os.environ.get("AZURE_TENANT_ID", "00000000-0000-0000-0000-000000000000") + monitormanagement_client_id = os.environ.get("AZURE_CLIENT_ID", "00000000-0000-0000-0000-000000000000") + monitormanagement_client_secret = os.environ.get("AZURE_CLIENT_SECRET", "00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=monitormanagement_subscription_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=monitormanagement_tenant_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=monitormanagement_client_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=monitormanagement_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/monitor/azure-mgmt-monitor/generated_tests/test_monitor_management_action_groups_operations.py b/sdk/monitor/azure-mgmt-monitor/generated_tests/test_monitor_management_action_groups_operations.py new file mode 100644 index 000000000000..4d4eb9c23e37 --- /dev/null +++ b/sdk/monitor/azure-mgmt-monitor/generated_tests/test_monitor_management_action_groups_operations.py @@ -0,0 +1,259 @@ +# 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.monitor import MonitorManagementClient + +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 TestMonitorManagementActionGroupsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(MonitorManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_action_groups_create_or_update(self, resource_group): + response = self.client.action_groups.create_or_update( + resource_group_name=resource_group.name, + action_group_name="str", + action_group={ + "location": "str", + "armRoleReceivers": [{"name": "str", "roleId": "str", "useCommonAlertSchema": False}], + "automationRunbookReceivers": [ + { + "automationAccountId": "str", + "isGlobalRunbook": bool, + "runbookName": "str", + "webhookResourceId": "str", + "name": "str", + "serviceUri": "str", + "useCommonAlertSchema": False, + } + ], + "azureAppPushReceivers": [{"emailAddress": "str", "name": "str"}], + "azureFunctionReceivers": [ + { + "functionAppResourceId": "str", + "functionName": "str", + "httpTriggerUrl": "str", + "name": "str", + "useCommonAlertSchema": False, + } + ], + "emailReceivers": [ + {"emailAddress": "str", "name": "str", "status": "str", "useCommonAlertSchema": False} + ], + "enabled": True, + "eventHubReceivers": [ + { + "eventHubName": "str", + "eventHubNameSpace": "str", + "name": "str", + "subscriptionId": "str", + "tenantId": "str", + "useCommonAlertSchema": False, + } + ], + "groupShortName": "str", + "id": "str", + "itsmReceivers": [ + { + "connectionId": "str", + "name": "str", + "region": "str", + "ticketConfiguration": "str", + "workspaceId": "str", + } + ], + "logicAppReceivers": [ + {"callbackUrl": "str", "name": "str", "resourceId": "str", "useCommonAlertSchema": False} + ], + "name": "str", + "smsReceivers": [{"countryCode": "str", "name": "str", "phoneNumber": "str", "status": "str"}], + "tags": {"str": "str"}, + "type": "str", + "voiceReceivers": [{"countryCode": "str", "name": "str", "phoneNumber": "str"}], + "webhookReceivers": [ + { + "name": "str", + "serviceUri": "str", + "identifierUri": "str", + "objectId": "str", + "tenantId": "str", + "useAadAuth": False, + "useCommonAlertSchema": False, + } + ], + }, + api_version="2023-01-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_action_groups_get(self, resource_group): + response = self.client.action_groups.get( + resource_group_name=resource_group.name, + action_group_name="str", + api_version="2023-01-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_action_groups_delete(self, resource_group): + response = self.client.action_groups.delete( + resource_group_name=resource_group.name, + action_group_name="str", + api_version="2023-01-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_action_groups_update(self, resource_group): + response = self.client.action_groups.update( + resource_group_name=resource_group.name, + action_group_name="str", + action_group_patch={"enabled": True, "tags": {"str": "str"}}, + api_version="2023-01-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_action_groups_begin_create_notifications_at_action_group_resource_level(self, resource_group): + response = self.client.action_groups.begin_create_notifications_at_action_group_resource_level( + resource_group_name=resource_group.name, + action_group_name="str", + notification_request={ + "alertType": "str", + "armRoleReceivers": [{"name": "str", "roleId": "str", "useCommonAlertSchema": False}], + "automationRunbookReceivers": [ + { + "automationAccountId": "str", + "isGlobalRunbook": bool, + "runbookName": "str", + "webhookResourceId": "str", + "name": "str", + "serviceUri": "str", + "useCommonAlertSchema": False, + } + ], + "azureAppPushReceivers": [{"emailAddress": "str", "name": "str"}], + "azureFunctionReceivers": [ + { + "functionAppResourceId": "str", + "functionName": "str", + "httpTriggerUrl": "str", + "name": "str", + "useCommonAlertSchema": False, + } + ], + "emailReceivers": [ + {"emailAddress": "str", "name": "str", "status": "str", "useCommonAlertSchema": False} + ], + "eventHubReceivers": [ + { + "eventHubName": "str", + "eventHubNameSpace": "str", + "name": "str", + "subscriptionId": "str", + "tenantId": "str", + "useCommonAlertSchema": False, + } + ], + "itsmReceivers": [ + { + "connectionId": "str", + "name": "str", + "region": "str", + "ticketConfiguration": "str", + "workspaceId": "str", + } + ], + "logicAppReceivers": [ + {"callbackUrl": "str", "name": "str", "resourceId": "str", "useCommonAlertSchema": False} + ], + "smsReceivers": [{"countryCode": "str", "name": "str", "phoneNumber": "str", "status": "str"}], + "voiceReceivers": [{"countryCode": "str", "name": "str", "phoneNumber": "str"}], + "webhookReceivers": [ + { + "name": "str", + "serviceUri": "str", + "identifierUri": "str", + "objectId": "str", + "tenantId": "str", + "useAadAuth": False, + "useCommonAlertSchema": False, + } + ], + }, + api_version="2023-01-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_action_groups_get_test_notifications_at_action_group_resource_level(self, resource_group): + response = self.client.action_groups.get_test_notifications_at_action_group_resource_level( + resource_group_name=resource_group.name, + action_group_name="str", + notification_id="str", + api_version="2023-01-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_action_groups_list_by_subscription_id(self, resource_group): + response = self.client.action_groups.list_by_subscription_id( + api_version="2023-01-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_action_groups_list_by_resource_group(self, resource_group): + response = self.client.action_groups.list_by_resource_group( + resource_group_name=resource_group.name, + api_version="2023-01-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_action_groups_enable_receiver(self, resource_group): + response = self.client.action_groups.enable_receiver( + resource_group_name=resource_group.name, + action_group_name="str", + enable_request={"receiverName": "str"}, + api_version="2023-01-01", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/monitor/azure-mgmt-monitor/generated_tests/test_monitor_management_action_groups_operations_async.py b/sdk/monitor/azure-mgmt-monitor/generated_tests/test_monitor_management_action_groups_operations_async.py new file mode 100644 index 000000000000..895a2dbd5f06 --- /dev/null +++ b/sdk/monitor/azure-mgmt-monitor/generated_tests/test_monitor_management_action_groups_operations_async.py @@ -0,0 +1,262 @@ +# 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.monitor.aio import MonitorManagementClient + +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 TestMonitorManagementActionGroupsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(MonitorManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_action_groups_create_or_update(self, resource_group): + response = await self.client.action_groups.create_or_update( + resource_group_name=resource_group.name, + action_group_name="str", + action_group={ + "location": "str", + "armRoleReceivers": [{"name": "str", "roleId": "str", "useCommonAlertSchema": False}], + "automationRunbookReceivers": [ + { + "automationAccountId": "str", + "isGlobalRunbook": bool, + "runbookName": "str", + "webhookResourceId": "str", + "name": "str", + "serviceUri": "str", + "useCommonAlertSchema": False, + } + ], + "azureAppPushReceivers": [{"emailAddress": "str", "name": "str"}], + "azureFunctionReceivers": [ + { + "functionAppResourceId": "str", + "functionName": "str", + "httpTriggerUrl": "str", + "name": "str", + "useCommonAlertSchema": False, + } + ], + "emailReceivers": [ + {"emailAddress": "str", "name": "str", "status": "str", "useCommonAlertSchema": False} + ], + "enabled": True, + "eventHubReceivers": [ + { + "eventHubName": "str", + "eventHubNameSpace": "str", + "name": "str", + "subscriptionId": "str", + "tenantId": "str", + "useCommonAlertSchema": False, + } + ], + "groupShortName": "str", + "id": "str", + "itsmReceivers": [ + { + "connectionId": "str", + "name": "str", + "region": "str", + "ticketConfiguration": "str", + "workspaceId": "str", + } + ], + "logicAppReceivers": [ + {"callbackUrl": "str", "name": "str", "resourceId": "str", "useCommonAlertSchema": False} + ], + "name": "str", + "smsReceivers": [{"countryCode": "str", "name": "str", "phoneNumber": "str", "status": "str"}], + "tags": {"str": "str"}, + "type": "str", + "voiceReceivers": [{"countryCode": "str", "name": "str", "phoneNumber": "str"}], + "webhookReceivers": [ + { + "name": "str", + "serviceUri": "str", + "identifierUri": "str", + "objectId": "str", + "tenantId": "str", + "useAadAuth": False, + "useCommonAlertSchema": False, + } + ], + }, + api_version="2023-01-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_action_groups_get(self, resource_group): + response = await self.client.action_groups.get( + resource_group_name=resource_group.name, + action_group_name="str", + api_version="2023-01-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_action_groups_delete(self, resource_group): + response = await self.client.action_groups.delete( + resource_group_name=resource_group.name, + action_group_name="str", + api_version="2023-01-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_action_groups_update(self, resource_group): + response = await self.client.action_groups.update( + resource_group_name=resource_group.name, + action_group_name="str", + action_group_patch={"enabled": True, "tags": {"str": "str"}}, + api_version="2023-01-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_action_groups_begin_create_notifications_at_action_group_resource_level(self, resource_group): + response = await ( + await self.client.action_groups.begin_create_notifications_at_action_group_resource_level( + resource_group_name=resource_group.name, + action_group_name="str", + notification_request={ + "alertType": "str", + "armRoleReceivers": [{"name": "str", "roleId": "str", "useCommonAlertSchema": False}], + "automationRunbookReceivers": [ + { + "automationAccountId": "str", + "isGlobalRunbook": bool, + "runbookName": "str", + "webhookResourceId": "str", + "name": "str", + "serviceUri": "str", + "useCommonAlertSchema": False, + } + ], + "azureAppPushReceivers": [{"emailAddress": "str", "name": "str"}], + "azureFunctionReceivers": [ + { + "functionAppResourceId": "str", + "functionName": "str", + "httpTriggerUrl": "str", + "name": "str", + "useCommonAlertSchema": False, + } + ], + "emailReceivers": [ + {"emailAddress": "str", "name": "str", "status": "str", "useCommonAlertSchema": False} + ], + "eventHubReceivers": [ + { + "eventHubName": "str", + "eventHubNameSpace": "str", + "name": "str", + "subscriptionId": "str", + "tenantId": "str", + "useCommonAlertSchema": False, + } + ], + "itsmReceivers": [ + { + "connectionId": "str", + "name": "str", + "region": "str", + "ticketConfiguration": "str", + "workspaceId": "str", + } + ], + "logicAppReceivers": [ + {"callbackUrl": "str", "name": "str", "resourceId": "str", "useCommonAlertSchema": False} + ], + "smsReceivers": [{"countryCode": "str", "name": "str", "phoneNumber": "str", "status": "str"}], + "voiceReceivers": [{"countryCode": "str", "name": "str", "phoneNumber": "str"}], + "webhookReceivers": [ + { + "name": "str", + "serviceUri": "str", + "identifierUri": "str", + "objectId": "str", + "tenantId": "str", + "useAadAuth": False, + "useCommonAlertSchema": False, + } + ], + }, + api_version="2023-01-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_action_groups_get_test_notifications_at_action_group_resource_level(self, resource_group): + response = await self.client.action_groups.get_test_notifications_at_action_group_resource_level( + resource_group_name=resource_group.name, + action_group_name="str", + notification_id="str", + api_version="2023-01-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_action_groups_list_by_subscription_id(self, resource_group): + response = self.client.action_groups.list_by_subscription_id( + api_version="2023-01-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_action_groups_list_by_resource_group(self, resource_group): + response = self.client.action_groups.list_by_resource_group( + resource_group_name=resource_group.name, + api_version="2023-01-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_action_groups_enable_receiver(self, resource_group): + response = await self.client.action_groups.enable_receiver( + resource_group_name=resource_group.name, + action_group_name="str", + enable_request={"receiverName": "str"}, + api_version="2023-01-01", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/monitor/azure-mgmt-monitor/setup.py b/sdk/monitor/azure-mgmt-monitor/setup.py index ae79d6845502..8528a161d7a7 100644 --- a/sdk/monitor/azure-mgmt-monitor/setup.py +++ b/sdk/monitor/azure-mgmt-monitor/setup.py @@ -53,11 +53,11 @@ "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", + "Programming Language :: Python :: 3.12", "License :: OSI Approved :: MIT License", ], zip_safe=False, @@ -74,10 +74,10 @@ "pytyped": ["py.typed"], }, install_requires=[ - "isodate<1.0.0,>=0.6.1", - "azure-common~=1.1", - "azure-mgmt-core>=1.3.2,<2.0.0", - "typing-extensions>=4.3.0; python_version<'3.8.0'", + "isodate>=0.6.1", + "typing-extensions>=4.6.0", + "azure-common>=1.1", + "azure-mgmt-core>=1.3.2", ], - python_requires=">=3.7", + python_requires=">=3.8", )