diff --git a/sdk/rdbms/azure-mgmt-rdbms/_meta.json b/sdk/rdbms/azure-mgmt-rdbms/_meta.json index 7f79724060fb..9619cd60211c 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/_meta.json +++ b/sdk/rdbms/azure-mgmt-rdbms/_meta.json @@ -1,11 +1,11 @@ { - "autorest": "3.7.2", + "commit": "3677b04c2a76196e9c2b9f4e33ee41bdae7e3e30", + "repository_url": "https://github.com/Azure/azure-rest-api-specs", + "autorest": "3.9.2", "use": [ - "@autorest/python@5.16.0", - "@autorest/modelerfour@4.19.3" + "@autorest/python@6.1.11", + "@autorest/modelerfour@4.24.3" ], - "commit": "352507b7909fabb6b6bb3e48b49d188c612c819f", - "repository_url": "https://github.com/Azure/azure-rest-api-specs", - "autorest_command": "autorest specification/mysql/resource-manager/readme.md --python --python-sdks-folder=/home/vsts/work/1/azure-sdk-for-python/sdk --python3-only --use=@autorest/python@5.16.0 --use=@autorest/modelerfour@4.19.3 --version=3.7.2", + "autorest_command": "autorest specification/mysql/resource-manager/readme.md --python --python-sdks-folder=/mnt/vss/_work/1/s/azure-sdk-for-python/sdk --use=@autorest/python@6.1.11 --use=@autorest/modelerfour@4.24.3 --version=3.9.2 --version-tolerant=False", "readme": "specification/mysql/resource-manager/readme.md" } \ No newline at end of file diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/__init__.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/__init__.py index 3ca776ae04a9..3ba002b536c9 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/__init__.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/__init__.py @@ -17,7 +17,8 @@ except ImportError: _patch_all = [] from ._patch import patch_sdk as _patch_sdk -__all__ = ['MySQLManagementClient'] + +__all__ = ["MySQLManagementClient"] __all__.extend([p for p in _patch_all if p not in __all__]) _patch_sdk() diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/_configuration.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/_configuration.py index b437ac926399..d84e91646389 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/_configuration.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/_configuration.py @@ -25,18 +25,13 @@ class MySQLManagementClientConfiguration(Configuration): # pylint: disable=too- Note that all parameters used to create this instance are saved as instance attributes. - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: The ID of the target subscription. + :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str """ - def __init__( - self, - credential: "TokenCredential", - subscription_id: str, - **kwargs: Any - ) -> None: + def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: super(MySQLManagementClientConfiguration, self).__init__(**kwargs) if credential is None: raise ValueError("Parameter 'credential' must not be None.") @@ -45,23 +40,24 @@ def __init__( self.credential = credential self.subscription_id = subscription_id - self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'mgmt-rdbms/{}'.format(VERSION)) + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-rdbms/{}".format(VERSION)) self._configure(**kwargs) def _configure( - self, - **kwargs # type: Any + self, **kwargs # type: Any ): # type: (...) -> None - self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get('retry_policy') or policies.RetryPolicy(**kwargs) - self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get('redirect_policy') or policies.RedirectPolicy(**kwargs) - self.authentication_policy = kwargs.get('authentication_policy') + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: - self.authentication_policy = ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs) + self.authentication_policy = ARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/_my_sql_management_client.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/_my_sql_management_client.py index 1bebfc1ebe23..fcad83b6a8bb 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/_my_sql_management_client.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/_my_sql_management_client.py @@ -9,20 +9,49 @@ from copy import deepcopy from typing import Any, TYPE_CHECKING -from msrest import Deserializer, Serializer - from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient from . import models from ._configuration import MySQLManagementClientConfiguration -from .operations import AdvisorsOperations, CheckNameAvailabilityOperations, ConfigurationsOperations, DatabasesOperations, FirewallRulesOperations, LocationBasedPerformanceTierOperations, LocationBasedRecommendedActionSessionsOperationStatusOperations, LocationBasedRecommendedActionSessionsResultOperations, LogFilesOperations, MySQLManagementClientOperationsMixin, Operations, PrivateEndpointConnectionsOperations, PrivateLinkResourcesOperations, QueryTextsOperations, RecommendedActionsOperations, RecoverableServersOperations, ReplicasOperations, ServerAdministratorsOperations, ServerBasedPerformanceTierOperations, ServerKeysOperations, ServerParametersOperations, ServerSecurityAlertPoliciesOperations, ServersOperations, TopQueryStatisticsOperations, VirtualNetworkRulesOperations, WaitStatisticsOperations +from ._serialization import Deserializer, Serializer +from .operations import ( + AdvisorsOperations, + CheckNameAvailabilityOperations, + ConfigurationsOperations, + DatabasesOperations, + FirewallRulesOperations, + LocationBasedPerformanceTierOperations, + LocationBasedRecommendedActionSessionsOperationStatusOperations, + LocationBasedRecommendedActionSessionsResultOperations, + LogFilesOperations, + MySQLManagementClientOperationsMixin, + Operations, + PrivateEndpointConnectionsOperations, + PrivateLinkResourcesOperations, + QueryTextsOperations, + RecommendedActionsOperations, + RecoverableServersOperations, + ReplicasOperations, + ServerAdministratorsOperations, + ServerBasedPerformanceTierOperations, + ServerKeysOperations, + ServerParametersOperations, + ServerSecurityAlertPoliciesOperations, + ServersOperations, + TopQueryStatisticsOperations, + VirtualNetworkRulesOperations, + WaitStatisticsOperations, +) if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MySQLManagementClient(MySQLManagementClientOperationsMixin): # pylint: disable=too-many-instance-attributes + +class MySQLManagementClient( + MySQLManagementClientOperationsMixin +): # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes """The Microsoft Azure management API provides create, read, update, and delete functionality for Azure MySQL resources including servers, databases, firewall rules, VNET rules, log files and configurations with new business model. @@ -88,9 +117,9 @@ class MySQLManagementClient(MySQLManagementClientOperationsMixin): # pylint: azure.mgmt.rdbms.mysql.operations.PrivateLinkResourcesOperations :ivar server_keys: ServerKeysOperations operations :vartype server_keys: azure.mgmt.rdbms.mysql.operations.ServerKeysOperations - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: The ID of the target subscription. + :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str :param base_url: Service URL. Default value is "https://management.azure.com". :type base_url: str @@ -105,37 +134,27 @@ def __init__( base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: - self._config = MySQLManagementClientConfiguration(credential=credential, subscription_id=subscription_id, **kwargs) + self._config = MySQLManagementClientConfiguration( + credential=credential, subscription_id=subscription_id, **kwargs + ) self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) self._deserialize = Deserializer(client_models) self._serialize.client_side_validation = False - self.servers = ServersOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.replicas = ReplicasOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.firewall_rules = FirewallRulesOperations( - self._client, self._config, self._serialize, self._deserialize - ) + self.servers = ServersOperations(self._client, self._config, self._serialize, self._deserialize) + self.replicas = ReplicasOperations(self._client, self._config, self._serialize, self._deserialize) + self.firewall_rules = FirewallRulesOperations(self._client, self._config, self._serialize, self._deserialize) self.virtual_network_rules = VirtualNetworkRulesOperations( self._client, self._config, self._serialize, self._deserialize ) - self.databases = DatabasesOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.configurations = ConfigurationsOperations( - self._client, self._config, self._serialize, self._deserialize - ) + self.databases = DatabasesOperations(self._client, self._config, self._serialize, self._deserialize) + self.configurations = ConfigurationsOperations(self._client, self._config, self._serialize, self._deserialize) self.server_parameters = ServerParametersOperations( self._client, self._config, self._serialize, self._deserialize ) - self.log_files = LogFilesOperations( - self._client, self._config, self._serialize, self._deserialize - ) + self.log_files = LogFilesOperations(self._client, self._config, self._serialize, self._deserialize) self.server_administrators = ServerAdministratorsOperations( self._client, self._config, self._serialize, self._deserialize ) @@ -151,29 +170,23 @@ def __init__( self.check_name_availability = CheckNameAvailabilityOperations( 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) self.server_security_alert_policies = ServerSecurityAlertPoliciesOperations( self._client, self._config, self._serialize, self._deserialize ) - self.query_texts = QueryTextsOperations( - self._client, self._config, self._serialize, self._deserialize - ) + self.query_texts = QueryTextsOperations(self._client, self._config, self._serialize, self._deserialize) self.top_query_statistics = TopQueryStatisticsOperations( self._client, self._config, self._serialize, self._deserialize ) - self.wait_statistics = WaitStatisticsOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.advisors = AdvisorsOperations( - self._client, self._config, self._serialize, self._deserialize - ) + self.wait_statistics = WaitStatisticsOperations(self._client, self._config, self._serialize, self._deserialize) + self.advisors = AdvisorsOperations(self._client, self._config, self._serialize, self._deserialize) self.recommended_actions = RecommendedActionsOperations( self._client, self._config, self._serialize, self._deserialize ) - self.location_based_recommended_action_sessions_operation_status = LocationBasedRecommendedActionSessionsOperationStatusOperations( - self._client, self._config, self._serialize, self._deserialize + self.location_based_recommended_action_sessions_operation_status = ( + LocationBasedRecommendedActionSessionsOperationStatusOperations( + self._client, self._config, self._serialize, self._deserialize + ) ) self.location_based_recommended_action_sessions_result = LocationBasedRecommendedActionSessionsResultOperations( self._client, self._config, self._serialize, self._deserialize @@ -184,16 +197,9 @@ def __init__( self.private_link_resources = PrivateLinkResourcesOperations( self._client, self._config, self._serialize, self._deserialize ) - self.server_keys = ServerKeysOperations( - self._client, self._config, self._serialize, self._deserialize - ) + self.server_keys = ServerKeysOperations(self._client, self._config, self._serialize, self._deserialize) - - def _send_request( - self, - request: HttpRequest, - **kwargs: Any - ) -> HttpResponse: + def _send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: """Runs the network request through the client's chained policies. >>> from azure.core.rest import HttpRequest @@ -202,7 +208,7 @@ def _send_request( >>> response = client._send_request(request) - For more information on this code flow, see https://aka.ms/azsdk/python/protocol/quickstart + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request :param request: The network request you want to make. Required. :type request: ~azure.core.rest.HttpRequest diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/_patch.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/_patch.py index 74e48ecd07cf..f99e77fef986 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/_patch.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/_patch.py @@ -28,4 +28,4 @@ # This file is used for handwritten extensions to the generated code. Example: # https://github.com/Azure/azure-sdk-for-python/blob/main/doc/dev/customize_code/how-to-patch-sdk-code.md def patch_sdk(): - pass \ No newline at end of file + pass diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/_serialization.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/_serialization.py new file mode 100644 index 000000000000..7c1dedb5133d --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/_serialization.py @@ -0,0 +1,1970 @@ +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- + +# pylint: skip-file + +from base64 import b64decode, b64encode +import calendar +import datetime +import decimal +import email +from enum import Enum +import json +import logging +import re +import sys +import codecs + +try: + from urllib import quote # type: ignore +except ImportError: + from urllib.parse import quote # type: ignore +import xml.etree.ElementTree as ET + +import isodate + +from typing import Dict, Any, cast, TYPE_CHECKING + +from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback + +_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") + +if TYPE_CHECKING: + from typing import Optional, Union, AnyStr, IO, Mapping + + +class RawDeserializer: + + # Accept "text" because we're open minded people... + JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") + + # Name used in context + CONTEXT_NAME = "deserialized_data" + + @classmethod + def deserialize_from_text(cls, data, content_type=None): + # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any + """Decode data according to content-type. + + Accept a stream of data as well, but will be load at once in memory for now. + + If no content-type, will return the string version (not bytes, not stream) + + :param data: Input, could be bytes or stream (will be decoded with UTF8) or text + :type data: str or bytes or IO + :param str content_type: The content type. + """ + if hasattr(data, "read"): + # Assume a stream + data = cast(IO, data).read() + + if isinstance(data, bytes): + data_as_str = data.decode(encoding="utf-8-sig") + else: + # Explain to mypy the correct type. + data_as_str = cast(str, data) + + # Remove Byte Order Mark if present in string + data_as_str = data_as_str.lstrip(_BOM) + + if content_type is None: + return data + + if cls.JSON_REGEXP.match(content_type): + try: + return json.loads(data_as_str) + except ValueError as err: + raise DeserializationError("JSON is invalid: {}".format(err), err) + elif "xml" in (content_type or []): + try: + + try: + if isinstance(data, unicode): # type: ignore + # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string + data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore + except NameError: + pass + + return ET.fromstring(data_as_str) # nosec + except ET.ParseError: + # It might be because the server has an issue, and returned JSON with + # content-type XML.... + # So let's try a JSON load, and if it's still broken + # let's flow the initial exception + def _json_attemp(data): + try: + return True, json.loads(data) + except ValueError: + return False, None # Don't care about this one + + success, json_result = _json_attemp(data) + if success: + return json_result + # If i'm here, it's not JSON, it's not XML, let's scream + # and raise the last context in this block (the XML exception) + # The function hack is because Py2.7 messes up with exception + # context otherwise. + _LOGGER.critical("Wasn't XML not JSON, failing") + raise_with_traceback(DeserializationError, "XML is invalid") + raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) + + @classmethod + def deserialize_from_http_generics(cls, body_bytes, headers): + # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any + """Deserialize from HTTP response. + + Use bytes and headers to NOT use any requests/aiohttp or whatever + specific implementation. + Headers will tested for "content-type" + """ + # Try to use content-type from headers if available + content_type = None + if "content-type" in headers: + content_type = headers["content-type"].split(";")[0].strip().lower() + # Ouch, this server did not declare what it sent... + # Let's guess it's JSON... + # Also, since Autorest was considering that an empty body was a valid JSON, + # need that test as well.... + else: + content_type = "application/json" + + if body_bytes: + return cls.deserialize_from_text(body_bytes, content_type) + return None + + +try: + basestring # type: ignore + unicode_str = unicode # type: ignore +except NameError: + basestring = str # type: ignore + unicode_str = str # type: ignore + +_LOGGER = logging.getLogger(__name__) + +try: + _long_type = long # type: ignore +except NameError: + _long_type = int + + +class UTC(datetime.tzinfo): + """Time Zone info for handling UTC""" + + def utcoffset(self, dt): + """UTF offset for UTC is 0.""" + return datetime.timedelta(0) + + def tzname(self, dt): + """Timestamp representation.""" + return "Z" + + def dst(self, dt): + """No daylight saving for UTC.""" + return datetime.timedelta(hours=1) + + +try: + from datetime import timezone as _FixedOffset +except ImportError: # Python 2.7 + + class _FixedOffset(datetime.tzinfo): # type: ignore + """Fixed offset in minutes east from UTC. + Copy/pasted from Python doc + :param datetime.timedelta offset: offset in timedelta format + """ + + def __init__(self, offset): + self.__offset = offset + + def utcoffset(self, dt): + return self.__offset + + def tzname(self, dt): + return str(self.__offset.total_seconds() / 3600) + + def __repr__(self): + return "".format(self.tzname(None)) + + def dst(self, dt): + return datetime.timedelta(0) + + def __getinitargs__(self): + return (self.__offset,) + + +try: + from datetime import timezone + + TZ_UTC = timezone.utc # type: ignore +except ImportError: + TZ_UTC = UTC() # type: ignore + +_FLATTEN = re.compile(r"(? y, + "minimum": lambda x, y: x < y, + "maximum": lambda x, y: x > y, + "minimum_ex": lambda x, y: x <= y, + "maximum_ex": lambda x, y: x >= y, + "min_items": lambda x, y: len(x) < y, + "max_items": lambda x, y: len(x) > y, + "pattern": lambda x, y: not re.match(y, x, re.UNICODE), + "unique": lambda x, y: len(x) != len(set(x)), + "multiple": lambda x, y: x % y != 0, + } + + def __init__(self, classes=None): + self.serialize_type = { + "iso-8601": Serializer.serialize_iso, + "rfc-1123": Serializer.serialize_rfc, + "unix-time": Serializer.serialize_unix, + "duration": Serializer.serialize_duration, + "date": Serializer.serialize_date, + "time": Serializer.serialize_time, + "decimal": Serializer.serialize_decimal, + "long": Serializer.serialize_long, + "bytearray": Serializer.serialize_bytearray, + "base64": Serializer.serialize_base64, + "object": self.serialize_object, + "[]": self.serialize_iter, + "{}": self.serialize_dict, + } + self.dependencies = dict(classes) if classes else {} + self.key_transformer = full_restapi_key_transformer + self.client_side_validation = True + + def _serialize(self, target_obj, data_type=None, **kwargs): + """Serialize data into a string according to type. + + :param target_obj: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str, dict + :raises: SerializationError if serialization fails. + """ + key_transformer = kwargs.get("key_transformer", self.key_transformer) + keep_readonly = kwargs.get("keep_readonly", False) + if target_obj is None: + return None + + attr_name = None + class_name = target_obj.__class__.__name__ + + if data_type: + return self.serialize_data(target_obj, data_type, **kwargs) + + if not hasattr(target_obj, "_attribute_map"): + data_type = type(target_obj).__name__ + if data_type in self.basic_types.values(): + return self.serialize_data(target_obj, data_type, **kwargs) + + # Force "is_xml" kwargs if we detect a XML model + try: + is_xml_model_serialization = kwargs["is_xml"] + except KeyError: + is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) + + serialized = {} + if is_xml_model_serialization: + serialized = target_obj._create_xml_node() + try: + attributes = target_obj._attribute_map + for attr, attr_desc in attributes.items(): + attr_name = attr + if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): + continue + + if attr_name == "additional_properties" and attr_desc["key"] == "": + if target_obj.additional_properties is not None: + serialized.update(target_obj.additional_properties) + continue + try: + + orig_attr = getattr(target_obj, attr) + if is_xml_model_serialization: + pass # Don't provide "transformer" for XML for now. Keep "orig_attr" + else: # JSON + keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) + keys = keys if isinstance(keys, list) else [keys] + + kwargs["serialization_ctxt"] = attr_desc + new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) + + if is_xml_model_serialization: + xml_desc = attr_desc.get("xml", {}) + xml_name = xml_desc.get("name", attr_desc["key"]) + xml_prefix = xml_desc.get("prefix", None) + xml_ns = xml_desc.get("ns", None) + if xml_desc.get("attr", False): + if xml_ns: + ET.register_namespace(xml_prefix, xml_ns) + xml_name = "{}{}".format(xml_ns, xml_name) + serialized.set(xml_name, new_attr) + continue + if xml_desc.get("text", False): + serialized.text = new_attr + continue + if isinstance(new_attr, list): + serialized.extend(new_attr) + elif isinstance(new_attr, ET.Element): + # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. + if "name" not in getattr(orig_attr, "_xml_map", {}): + splitted_tag = new_attr.tag.split("}") + if len(splitted_tag) == 2: # Namespace + new_attr.tag = "}".join([splitted_tag[0], xml_name]) + else: + new_attr.tag = xml_name + serialized.append(new_attr) + else: # That's a basic type + # Integrate namespace if necessary + local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) + local_node.text = unicode_str(new_attr) + serialized.append(local_node) + else: # JSON + for k in reversed(keys): + unflattened = {k: new_attr} + new_attr = unflattened + + _new_attr = new_attr + _serialized = serialized + for k in keys: + if k not in _serialized: + _serialized.update(_new_attr) + _new_attr = _new_attr[k] + _serialized = _serialized[k] + except ValueError: + continue + + except (AttributeError, KeyError, TypeError) as err: + msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) + raise_with_traceback(SerializationError, msg, err) + else: + return serialized + + def body(self, data, data_type, **kwargs): + """Serialize data intended for a request body. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: dict + :raises: SerializationError if serialization fails. + :raises: ValueError if data is None + """ + + # Just in case this is a dict + internal_data_type = data_type.strip("[]{}") + internal_data_type = self.dependencies.get(internal_data_type, None) + try: + is_xml_model_serialization = kwargs["is_xml"] + except KeyError: + if internal_data_type and issubclass(internal_data_type, Model): + is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) + else: + is_xml_model_serialization = False + if internal_data_type and not isinstance(internal_data_type, Enum): + try: + deserializer = Deserializer(self.dependencies) + # Since it's on serialization, it's almost sure that format is not JSON REST + # We're not able to deal with additional properties for now. + deserializer.additional_properties_detection = False + if is_xml_model_serialization: + deserializer.key_extractors = [ + attribute_key_case_insensitive_extractor, + ] + else: + deserializer.key_extractors = [ + rest_key_case_insensitive_extractor, + attribute_key_case_insensitive_extractor, + last_rest_key_case_insensitive_extractor, + ] + data = deserializer._deserialize(data_type, data) + except DeserializationError as err: + raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) + + return self._serialize(data, data_type, **kwargs) + + def url(self, name, data, data_type, **kwargs): + """Serialize data intended for a URL path. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :raises: TypeError if serialization fails. + :raises: ValueError if data is None + """ + try: + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + + if kwargs.get("skip_quote") is True: + output = str(output) + else: + output = quote(str(output), safe="") + except SerializationError: + raise TypeError("{} must be type {}.".format(name, data_type)) + else: + return output + + def query(self, name, data, data_type, **kwargs): + """Serialize data intended for a URL query. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :raises: TypeError if serialization fails. + :raises: ValueError if data is None + """ + try: + # Treat the list aside, since we don't want to encode the div separator + if data_type.startswith("["): + internal_data_type = data_type[1:-1] + data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] + if not kwargs.get("skip_quote", False): + data = [quote(str(d), safe="") for d in data] + return str(self.serialize_iter(data, internal_data_type, **kwargs)) + + # Not a list, regular serialization + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + if kwargs.get("skip_quote") is True: + output = str(output) + else: + output = quote(str(output), safe="") + except SerializationError: + raise TypeError("{} must be type {}.".format(name, data_type)) + else: + return str(output) + + def header(self, name, data, data_type, **kwargs): + """Serialize data intended for a request header. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :raises: TypeError if serialization fails. + :raises: ValueError if data is None + """ + try: + if data_type in ["[str]"]: + data = ["" if d is None else d for d in data] + + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + except SerializationError: + raise TypeError("{} must be type {}.".format(name, data_type)) + else: + return str(output) + + def serialize_data(self, data, data_type, **kwargs): + """Serialize generic data according to supplied data type. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :param bool required: Whether it's essential that the data not be + empty or None + :raises: AttributeError if required data is None. + :raises: ValueError if data is None + :raises: SerializationError if serialization fails. + """ + if data is None: + raise ValueError("No value for given attribute") + + try: + if data_type in self.basic_types.values(): + return self.serialize_basic(data, data_type, **kwargs) + + elif data_type in self.serialize_type: + return self.serialize_type[data_type](data, **kwargs) + + # If dependencies is empty, try with current data class + # It has to be a subclass of Enum anyway + enum_type = self.dependencies.get(data_type, data.__class__) + if issubclass(enum_type, Enum): + return Serializer.serialize_enum(data, enum_obj=enum_type) + + iter_type = data_type[0] + data_type[-1] + if iter_type in self.serialize_type: + return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) + + except (ValueError, TypeError) as err: + msg = "Unable to serialize value: {!r} as type: {!r}." + raise_with_traceback(SerializationError, msg.format(data, data_type), err) + else: + return self._serialize(data, **kwargs) + + @classmethod + def _get_custom_serializers(cls, data_type, **kwargs): + custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) + if custom_serializer: + return custom_serializer + if kwargs.get("is_xml", False): + return cls._xml_basic_types_serializers.get(data_type) + + @classmethod + def serialize_basic(cls, data, data_type, **kwargs): + """Serialize basic builting data type. + Serializes objects to str, int, float or bool. + + Possible kwargs: + - basic_types_serializers dict[str, callable] : If set, use the callable as serializer + - is_xml bool : If set, use xml_basic_types_serializers + + :param data: Object to be serialized. + :param str data_type: Type of object in the iterable. + """ + custom_serializer = cls._get_custom_serializers(data_type, **kwargs) + if custom_serializer: + return custom_serializer(data) + if data_type == "str": + return cls.serialize_unicode(data) + return eval(data_type)(data) # nosec + + @classmethod + def serialize_unicode(cls, data): + """Special handling for serializing unicode strings in Py2. + Encode to UTF-8 if unicode, otherwise handle as a str. + + :param data: Object to be serialized. + :rtype: str + """ + try: # If I received an enum, return its value + return data.value + except AttributeError: + pass + + try: + if isinstance(data, unicode): + # Don't change it, JSON and XML ElementTree are totally able + # to serialize correctly u'' strings + return data + except NameError: + return str(data) + else: + return str(data) + + def serialize_iter(self, data, iter_type, div=None, **kwargs): + """Serialize iterable. + + Supported kwargs: + - serialization_ctxt dict : The current entry of _attribute_map, or same format. + serialization_ctxt['type'] should be same as data_type. + - is_xml bool : If set, serialize as XML + + :param list attr: Object to be serialized. + :param str iter_type: Type of object in the iterable. + :param bool required: Whether the objects in the iterable must + not be None or empty. + :param str div: If set, this str will be used to combine the elements + in the iterable into a combined string. Default is 'None'. + :rtype: list, str + """ + if isinstance(data, str): + raise SerializationError("Refuse str type as a valid iter type.") + + serialization_ctxt = kwargs.get("serialization_ctxt", {}) + is_xml = kwargs.get("is_xml", False) + + serialized = [] + for d in data: + try: + serialized.append(self.serialize_data(d, iter_type, **kwargs)) + except ValueError: + serialized.append(None) + + if div: + serialized = ["" if s is None else str(s) for s in serialized] + serialized = div.join(serialized) + + if "xml" in serialization_ctxt or is_xml: + # XML serialization is more complicated + xml_desc = serialization_ctxt.get("xml", {}) + xml_name = xml_desc.get("name") + if not xml_name: + xml_name = serialization_ctxt["key"] + + # Create a wrap node if necessary (use the fact that Element and list have "append") + is_wrapped = xml_desc.get("wrapped", False) + node_name = xml_desc.get("itemsName", xml_name) + if is_wrapped: + final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + else: + final_result = [] + # All list elements to "local_node" + for el in serialized: + if isinstance(el, ET.Element): + el_node = el + else: + el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + if el is not None: # Otherwise it writes "None" :-p + el_node.text = str(el) + final_result.append(el_node) + return final_result + return serialized + + def serialize_dict(self, attr, dict_type, **kwargs): + """Serialize a dictionary of objects. + + :param dict attr: Object to be serialized. + :param str dict_type: Type of object in the dictionary. + :param bool required: Whether the objects in the dictionary must + not be None or empty. + :rtype: dict + """ + serialization_ctxt = kwargs.get("serialization_ctxt", {}) + serialized = {} + for key, value in attr.items(): + try: + serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) + except ValueError: + serialized[self.serialize_unicode(key)] = None + + if "xml" in serialization_ctxt: + # XML serialization is more complicated + xml_desc = serialization_ctxt["xml"] + xml_name = xml_desc["name"] + + final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + for key, value in serialized.items(): + ET.SubElement(final_result, key).text = value + return final_result + + return serialized + + def serialize_object(self, attr, **kwargs): + """Serialize a generic object. + This will be handled as a dictionary. If object passed in is not + a basic type (str, int, float, dict, list) it will simply be + cast to str. + + :param dict attr: Object to be serialized. + :rtype: dict or str + """ + if attr is None: + return None + if isinstance(attr, ET.Element): + return attr + obj_type = type(attr) + if obj_type in self.basic_types: + return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) + if obj_type is _long_type: + return self.serialize_long(attr) + if obj_type is unicode_str: + return self.serialize_unicode(attr) + if obj_type is datetime.datetime: + return self.serialize_iso(attr) + if obj_type is datetime.date: + return self.serialize_date(attr) + if obj_type is datetime.time: + return self.serialize_time(attr) + if obj_type is datetime.timedelta: + return self.serialize_duration(attr) + if obj_type is decimal.Decimal: + return self.serialize_decimal(attr) + + # If it's a model or I know this dependency, serialize as a Model + elif obj_type in self.dependencies.values() or isinstance(attr, Model): + return self._serialize(attr) + + if obj_type == dict: + serialized = {} + for key, value in attr.items(): + try: + serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) + except ValueError: + serialized[self.serialize_unicode(key)] = None + return serialized + + if obj_type == list: + serialized = [] + for obj in attr: + try: + serialized.append(self.serialize_object(obj, **kwargs)) + except ValueError: + pass + return serialized + return str(attr) + + @staticmethod + def serialize_enum(attr, enum_obj=None): + try: + result = attr.value + except AttributeError: + result = attr + try: + enum_obj(result) + return result + except ValueError: + for enum_value in enum_obj: + if enum_value.value.lower() == str(attr).lower(): + return enum_value.value + error = "{!r} is not valid value for enum {!r}" + raise SerializationError(error.format(attr, enum_obj)) + + @staticmethod + def serialize_bytearray(attr, **kwargs): + """Serialize bytearray into base-64 string. + + :param attr: Object to be serialized. + :rtype: str + """ + return b64encode(attr).decode() + + @staticmethod + def serialize_base64(attr, **kwargs): + """Serialize str into base-64 string. + + :param attr: Object to be serialized. + :rtype: str + """ + encoded = b64encode(attr).decode("ascii") + return encoded.strip("=").replace("+", "-").replace("/", "_") + + @staticmethod + def serialize_decimal(attr, **kwargs): + """Serialize Decimal object to float. + + :param attr: Object to be serialized. + :rtype: float + """ + return float(attr) + + @staticmethod + def serialize_long(attr, **kwargs): + """Serialize long (Py2) or int (Py3). + + :param attr: Object to be serialized. + :rtype: int/long + """ + return _long_type(attr) + + @staticmethod + def serialize_date(attr, **kwargs): + """Serialize Date object into ISO-8601 formatted string. + + :param Date attr: Object to be serialized. + :rtype: str + """ + if isinstance(attr, str): + attr = isodate.parse_date(attr) + t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) + return t + + @staticmethod + def serialize_time(attr, **kwargs): + """Serialize Time object into ISO-8601 formatted string. + + :param datetime.time attr: Object to be serialized. + :rtype: str + """ + if isinstance(attr, str): + attr = isodate.parse_time(attr) + t = "{:02}:{:02}:{:02}".format(attr.hour, attr.minute, attr.second) + if attr.microsecond: + t += ".{:02}".format(attr.microsecond) + return t + + @staticmethod + def serialize_duration(attr, **kwargs): + """Serialize TimeDelta object into ISO-8601 formatted string. + + :param TimeDelta attr: Object to be serialized. + :rtype: str + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + return isodate.duration_isoformat(attr) + + @staticmethod + def serialize_rfc(attr, **kwargs): + """Serialize Datetime object into RFC-1123 formatted string. + + :param Datetime attr: Object to be serialized. + :rtype: str + :raises: TypeError if format invalid. + """ + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + utc = attr.utctimetuple() + except AttributeError: + raise TypeError("RFC1123 object must be valid Datetime object.") + + return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( + Serializer.days[utc.tm_wday], + utc.tm_mday, + Serializer.months[utc.tm_mon], + utc.tm_year, + utc.tm_hour, + utc.tm_min, + utc.tm_sec, + ) + + @staticmethod + def serialize_iso(attr, **kwargs): + """Serialize Datetime object into ISO-8601 formatted string. + + :param Datetime attr: Object to be serialized. + :rtype: str + :raises: SerializationError if format invalid. + """ + if isinstance(attr, str): + attr = isodate.parse_datetime(attr) + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + utc = attr.utctimetuple() + if utc.tm_year > 9999 or utc.tm_year < 1: + raise OverflowError("Hit max or min date") + + microseconds = str(attr.microsecond).rjust(6, "0").rstrip("0").ljust(3, "0") + if microseconds: + microseconds = "." + microseconds + date = "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}".format( + utc.tm_year, utc.tm_mon, utc.tm_mday, utc.tm_hour, utc.tm_min, utc.tm_sec + ) + return date + microseconds + "Z" + except (ValueError, OverflowError) as err: + msg = "Unable to serialize datetime object." + raise_with_traceback(SerializationError, msg, err) + except AttributeError as err: + msg = "ISO-8601 object must be valid Datetime object." + raise_with_traceback(TypeError, msg, err) + + @staticmethod + def serialize_unix(attr, **kwargs): + """Serialize Datetime object into IntTime format. + This is represented as seconds. + + :param Datetime attr: Object to be serialized. + :rtype: int + :raises: SerializationError if format invalid + """ + if isinstance(attr, int): + return attr + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + return int(calendar.timegm(attr.utctimetuple())) + except AttributeError: + raise TypeError("Unix time object must be valid Datetime object.") + + +def rest_key_extractor(attr, attr_desc, data): + key = attr_desc["key"] + working_data = data + + while "." in key: + dict_keys = _FLATTEN.split(key) + if len(dict_keys) == 1: + key = _decode_attribute_map_key(dict_keys[0]) + break + working_key = _decode_attribute_map_key(dict_keys[0]) + working_data = working_data.get(working_key, data) + if working_data is None: + # If at any point while following flatten JSON path see None, it means + # that all properties under are None as well + # https://github.com/Azure/msrest-for-python/issues/197 + return None + key = ".".join(dict_keys[1:]) + + return working_data.get(key) + + +def rest_key_case_insensitive_extractor(attr, attr_desc, data): + key = attr_desc["key"] + working_data = data + + while "." in key: + dict_keys = _FLATTEN.split(key) + if len(dict_keys) == 1: + key = _decode_attribute_map_key(dict_keys[0]) + break + working_key = _decode_attribute_map_key(dict_keys[0]) + working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) + if working_data is None: + # If at any point while following flatten JSON path see None, it means + # that all properties under are None as well + # https://github.com/Azure/msrest-for-python/issues/197 + return None + key = ".".join(dict_keys[1:]) + + if working_data: + return attribute_key_case_insensitive_extractor(key, None, working_data) + + +def last_rest_key_extractor(attr, attr_desc, data): + """Extract the attribute in "data" based on the last part of the JSON path key.""" + key = attr_desc["key"] + dict_keys = _FLATTEN.split(key) + return attribute_key_extractor(dict_keys[-1], None, data) + + +def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): + """Extract the attribute in "data" based on the last part of the JSON path key. + + This is the case insensitive version of "last_rest_key_extractor" + """ + key = attr_desc["key"] + dict_keys = _FLATTEN.split(key) + return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) + + +def attribute_key_extractor(attr, _, data): + return data.get(attr) + + +def attribute_key_case_insensitive_extractor(attr, _, data): + found_key = None + lower_attr = attr.lower() + for key in data: + if lower_attr == key.lower(): + found_key = key + break + + return data.get(found_key) + + +def _extract_name_from_internal_type(internal_type): + """Given an internal type XML description, extract correct XML name with namespace. + + :param dict internal_type: An model type + :rtype: tuple + :returns: A tuple XML name + namespace dict + """ + internal_type_xml_map = getattr(internal_type, "_xml_map", {}) + xml_name = internal_type_xml_map.get("name", internal_type.__name__) + xml_ns = internal_type_xml_map.get("ns", None) + if xml_ns: + xml_name = "{}{}".format(xml_ns, xml_name) + return xml_name + + +def xml_key_extractor(attr, attr_desc, data): + if isinstance(data, dict): + return None + + # Test if this model is XML ready first + if not isinstance(data, ET.Element): + return None + + xml_desc = attr_desc.get("xml", {}) + xml_name = xml_desc.get("name", attr_desc["key"]) + + # Look for a children + is_iter_type = attr_desc["type"].startswith("[") + is_wrapped = xml_desc.get("wrapped", False) + internal_type = attr_desc.get("internalType", None) + internal_type_xml_map = getattr(internal_type, "_xml_map", {}) + + # Integrate namespace if necessary + xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) + if xml_ns: + xml_name = "{}{}".format(xml_ns, xml_name) + + # If it's an attribute, that's simple + if xml_desc.get("attr", False): + return data.get(xml_name) + + # If it's x-ms-text, that's simple too + if xml_desc.get("text", False): + return data.text + + # Scenario where I take the local name: + # - Wrapped node + # - Internal type is an enum (considered basic types) + # - Internal type has no XML/Name node + if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): + children = data.findall(xml_name) + # If internal type has a local name and it's not a list, I use that name + elif not is_iter_type and internal_type and "name" in internal_type_xml_map: + xml_name = _extract_name_from_internal_type(internal_type) + children = data.findall(xml_name) + # That's an array + else: + if internal_type: # Complex type, ignore itemsName and use the complex type name + items_name = _extract_name_from_internal_type(internal_type) + else: + items_name = xml_desc.get("itemsName", xml_name) + children = data.findall(items_name) + + if len(children) == 0: + if is_iter_type: + if is_wrapped: + return None # is_wrapped no node, we want None + else: + return [] # not wrapped, assume empty list + return None # Assume it's not there, maybe an optional node. + + # If is_iter_type and not wrapped, return all found children + if is_iter_type: + if not is_wrapped: + return children + else: # Iter and wrapped, should have found one node only (the wrap one) + if len(children) != 1: + raise DeserializationError( + "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( + xml_name + ) + ) + return list(children[0]) # Might be empty list and that's ok. + + # Here it's not a itertype, we should have found one element only or empty + if len(children) > 1: + raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) + return children[0] + + +class Deserializer(object): + """Response object model deserializer. + + :param dict classes: Class type dictionary for deserializing complex types. + :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. + """ + + basic_types = {str: "str", int: "int", bool: "bool", float: "float"} + + valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}" r"\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") + + def __init__(self, classes=None): + self.deserialize_type = { + "iso-8601": Deserializer.deserialize_iso, + "rfc-1123": Deserializer.deserialize_rfc, + "unix-time": Deserializer.deserialize_unix, + "duration": Deserializer.deserialize_duration, + "date": Deserializer.deserialize_date, + "time": Deserializer.deserialize_time, + "decimal": Deserializer.deserialize_decimal, + "long": Deserializer.deserialize_long, + "bytearray": Deserializer.deserialize_bytearray, + "base64": Deserializer.deserialize_base64, + "object": self.deserialize_object, + "[]": self.deserialize_iter, + "{}": self.deserialize_dict, + } + self.deserialize_expected_types = { + "duration": (isodate.Duration, datetime.timedelta), + "iso-8601": (datetime.datetime), + } + self.dependencies = dict(classes) if classes else {} + self.key_extractors = [rest_key_extractor, xml_key_extractor] + # Additional properties only works if the "rest_key_extractor" is used to + # extract the keys. Making it to work whatever the key extractor is too much + # complicated, with no real scenario for now. + # So adding a flag to disable additional properties detection. This flag should be + # used if your expect the deserialization to NOT come from a JSON REST syntax. + # Otherwise, result are unexpected + self.additional_properties_detection = True + + def __call__(self, target_obj, response_data, content_type=None): + """Call the deserializer to process a REST response. + + :param str target_obj: Target data type to deserialize to. + :param requests.Response response_data: REST response object. + :param str content_type: Swagger "produces" if available. + :raises: DeserializationError if deserialization fails. + :return: Deserialized object. + """ + data = self._unpack_content(response_data, content_type) + return self._deserialize(target_obj, data) + + def _deserialize(self, target_obj, data): + """Call the deserializer on a model. + + Data needs to be already deserialized as JSON or XML ElementTree + + :param str target_obj: Target data type to deserialize to. + :param object data: Object to deserialize. + :raises: DeserializationError if deserialization fails. + :return: Deserialized object. + """ + # This is already a model, go recursive just in case + if hasattr(data, "_attribute_map"): + constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] + try: + for attr, mapconfig in data._attribute_map.items(): + if attr in constants: + continue + value = getattr(data, attr) + if value is None: + continue + local_type = mapconfig["type"] + internal_data_type = local_type.strip("[]{}") + if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): + continue + setattr(data, attr, self._deserialize(local_type, value)) + return data + except AttributeError: + return + + response, class_name = self._classify_target(target_obj, data) + + if isinstance(response, basestring): + return self.deserialize_data(data, response) + elif isinstance(response, type) and issubclass(response, Enum): + return self.deserialize_enum(data, response) + + if data is None: + return data + try: + attributes = response._attribute_map + d_attrs = {} + for attr, attr_desc in attributes.items(): + # Check empty string. If it's not empty, someone has a real "additionalProperties"... + if attr == "additional_properties" and attr_desc["key"] == "": + continue + raw_value = None + # Enhance attr_desc with some dynamic data + attr_desc = attr_desc.copy() # Do a copy, do not change the real one + internal_data_type = attr_desc["type"].strip("[]{}") + if internal_data_type in self.dependencies: + attr_desc["internalType"] = self.dependencies[internal_data_type] + + for key_extractor in self.key_extractors: + found_value = key_extractor(attr, attr_desc, data) + if found_value is not None: + if raw_value is not None and raw_value != found_value: + msg = ( + "Ignoring extracted value '%s' from %s for key '%s'" + " (duplicate extraction, follow extractors order)" + ) + _LOGGER.warning(msg, found_value, key_extractor, attr) + continue + raw_value = found_value + + value = self.deserialize_data(raw_value, attr_desc["type"]) + d_attrs[attr] = value + except (AttributeError, TypeError, KeyError) as err: + msg = "Unable to deserialize to object: " + class_name + raise_with_traceback(DeserializationError, msg, err) + else: + additional_properties = self._build_additional_properties(attributes, data) + return self._instantiate_model(response, d_attrs, additional_properties) + + def _build_additional_properties(self, attribute_map, data): + if not self.additional_properties_detection: + return None + if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": + # Check empty string. If it's not empty, someone has a real "additionalProperties" + return None + if isinstance(data, ET.Element): + data = {el.tag: el.text for el in data} + + known_keys = { + _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) + for desc in attribute_map.values() + if desc["key"] != "" + } + present_keys = set(data.keys()) + missing_keys = present_keys - known_keys + return {key: data[key] for key in missing_keys} + + def _classify_target(self, target, data): + """Check to see whether the deserialization target object can + be classified into a subclass. + Once classification has been determined, initialize object. + + :param str target: The target object type to deserialize to. + :param str/dict data: The response data to deseralize. + """ + if target is None: + return None, None + + if isinstance(target, basestring): + try: + target = self.dependencies[target] + except KeyError: + return target, target + + try: + target = target._classify(data, self.dependencies) + except AttributeError: + pass # Target is not a Model, no classify + return target, target.__class__.__name__ + + def failsafe_deserialize(self, target_obj, data, content_type=None): + """Ignores any errors encountered in deserialization, + and falls back to not deserializing the object. Recommended + for use in error deserialization, as we want to return the + HttpResponseError to users, and not have them deal with + a deserialization error. + + :param str target_obj: The target object type to deserialize to. + :param str/dict data: The response data to deseralize. + :param str content_type: Swagger "produces" if available. + """ + try: + return self(target_obj, data, content_type=content_type) + except: + _LOGGER.debug( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + @staticmethod + def _unpack_content(raw_data, content_type=None): + """Extract the correct structure for deserialization. + + If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. + if we can't, raise. Your Pipeline should have a RawDeserializer. + + If not a pipeline response and raw_data is bytes or string, use content-type + to decode it. If no content-type, try JSON. + + If raw_data is something else, bypass all logic and return it directly. + + :param raw_data: Data to be processed. + :param content_type: How to parse if raw_data is a string/bytes. + :raises JSONDecodeError: If JSON is requested and parsing is impossible. + :raises UnicodeDecodeError: If bytes is not UTF8 + """ + # Assume this is enough to detect a Pipeline Response without importing it + context = getattr(raw_data, "context", {}) + if context: + if RawDeserializer.CONTEXT_NAME in context: + return context[RawDeserializer.CONTEXT_NAME] + raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") + + # Assume this is enough to recognize universal_http.ClientResponse without importing it + if hasattr(raw_data, "body"): + return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) + + # Assume this enough to recognize requests.Response without importing it. + if hasattr(raw_data, "_content_consumed"): + return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) + + if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): + return RawDeserializer.deserialize_from_text(raw_data, content_type) + return raw_data + + def _instantiate_model(self, response, attrs, additional_properties=None): + """Instantiate a response model passing in deserialized args. + + :param response: The response model class. + :param d_attrs: The deserialized response attributes. + """ + if callable(response): + subtype = getattr(response, "_subtype_map", {}) + try: + readonly = [k for k, v in response._validation.items() if v.get("readonly")] + const = [k for k, v in response._validation.items() if v.get("constant")] + kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} + response_obj = response(**kwargs) + for attr in readonly: + setattr(response_obj, attr, attrs.get(attr)) + if additional_properties: + response_obj.additional_properties = additional_properties + return response_obj + except TypeError as err: + msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) + raise DeserializationError(msg + str(err)) + else: + try: + for attr, value in attrs.items(): + setattr(response, attr, value) + return response + except Exception as exp: + msg = "Unable to populate response model. " + msg += "Type: {}, Error: {}".format(type(response), exp) + raise DeserializationError(msg) + + def deserialize_data(self, data, data_type): + """Process data for deserialization according to data type. + + :param str data: The response string to be deserialized. + :param str data_type: The type to deserialize to. + :raises: DeserializationError if deserialization fails. + :return: Deserialized object. + """ + if data is None: + return data + + try: + if not data_type: + return data + if data_type in self.basic_types.values(): + return self.deserialize_basic(data, data_type) + if data_type in self.deserialize_type: + if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): + return data + + is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] + if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: + return None + data_val = self.deserialize_type[data_type](data) + return data_val + + iter_type = data_type[0] + data_type[-1] + if iter_type in self.deserialize_type: + return self.deserialize_type[iter_type](data, data_type[1:-1]) + + obj_type = self.dependencies[data_type] + if issubclass(obj_type, Enum): + if isinstance(data, ET.Element): + data = data.text + return self.deserialize_enum(data, obj_type) + + except (ValueError, TypeError, AttributeError) as err: + msg = "Unable to deserialize response data." + msg += " Data: {}, {}".format(data, data_type) + raise_with_traceback(DeserializationError, msg, err) + else: + return self._deserialize(obj_type, data) + + def deserialize_iter(self, attr, iter_type): + """Deserialize an iterable. + + :param list attr: Iterable to be deserialized. + :param str iter_type: The type of object in the iterable. + :rtype: list + """ + if attr is None: + return None + if isinstance(attr, ET.Element): # If I receive an element here, get the children + attr = list(attr) + if not isinstance(attr, (list, set)): + raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) + return [self.deserialize_data(a, iter_type) for a in attr] + + def deserialize_dict(self, attr, dict_type): + """Deserialize a dictionary. + + :param dict/list attr: Dictionary to be deserialized. Also accepts + a list of key, value pairs. + :param str dict_type: The object type of the items in the dictionary. + :rtype: dict + """ + if isinstance(attr, list): + return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} + + if isinstance(attr, ET.Element): + # Transform value into {"Key": "value"} + attr = {el.tag: el.text for el in attr} + return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} + + def deserialize_object(self, attr, **kwargs): + """Deserialize a generic object. + This will be handled as a dictionary. + + :param dict attr: Dictionary to be deserialized. + :rtype: dict + :raises: TypeError if non-builtin datatype encountered. + """ + if attr is None: + return None + if isinstance(attr, ET.Element): + # Do no recurse on XML, just return the tree as-is + return attr + if isinstance(attr, basestring): + return self.deserialize_basic(attr, "str") + obj_type = type(attr) + if obj_type in self.basic_types: + return self.deserialize_basic(attr, self.basic_types[obj_type]) + if obj_type is _long_type: + return self.deserialize_long(attr) + + if obj_type == dict: + deserialized = {} + for key, value in attr.items(): + try: + deserialized[key] = self.deserialize_object(value, **kwargs) + except ValueError: + deserialized[key] = None + return deserialized + + if obj_type == list: + deserialized = [] + for obj in attr: + try: + deserialized.append(self.deserialize_object(obj, **kwargs)) + except ValueError: + pass + return deserialized + + else: + error = "Cannot deserialize generic object with type: " + raise TypeError(error + str(obj_type)) + + def deserialize_basic(self, attr, data_type): + """Deserialize basic builtin data type from string. + Will attempt to convert to str, int, float and bool. + This function will also accept '1', '0', 'true' and 'false' as + valid bool values. + + :param str attr: response string to be deserialized. + :param str data_type: deserialization data type. + :rtype: str, int, float or bool + :raises: TypeError if string format is not valid. + """ + # If we're here, data is supposed to be a basic type. + # If it's still an XML node, take the text + if isinstance(attr, ET.Element): + attr = attr.text + if not attr: + if data_type == "str": + # None or '', node is empty string. + return "" + else: + # None or '', node with a strong type is None. + # Don't try to model "empty bool" or "empty int" + return None + + if data_type == "bool": + if attr in [True, False, 1, 0]: + return bool(attr) + elif isinstance(attr, basestring): + if attr.lower() in ["true", "1"]: + return True + elif attr.lower() in ["false", "0"]: + return False + raise TypeError("Invalid boolean value: {}".format(attr)) + + if data_type == "str": + return self.deserialize_unicode(attr) + return eval(data_type)(attr) # nosec + + @staticmethod + def deserialize_unicode(data): + """Preserve unicode objects in Python 2, otherwise return data + as a string. + + :param str data: response string to be deserialized. + :rtype: str or unicode + """ + # We might be here because we have an enum modeled as string, + # and we try to deserialize a partial dict with enum inside + if isinstance(data, Enum): + return data + + # Consider this is real string + try: + if isinstance(data, unicode): + return data + except NameError: + return str(data) + else: + return str(data) + + @staticmethod + def deserialize_enum(data, enum_obj): + """Deserialize string into enum object. + + If the string is not a valid enum value it will be returned as-is + and a warning will be logged. + + :param str data: Response string to be deserialized. If this value is + None or invalid it will be returned as-is. + :param Enum enum_obj: Enum object to deserialize to. + :rtype: Enum + """ + if isinstance(data, enum_obj) or data is None: + return data + if isinstance(data, Enum): + data = data.value + if isinstance(data, int): + # Workaround. We might consider remove it in the future. + # https://github.com/Azure/azure-rest-api-specs/issues/141 + try: + return list(enum_obj.__members__.values())[data] + except IndexError: + error = "{!r} is not a valid index for enum {!r}" + raise DeserializationError(error.format(data, enum_obj)) + try: + return enum_obj(str(data)) + except ValueError: + for enum_value in enum_obj: + if enum_value.value.lower() == str(data).lower(): + return enum_value + # We don't fail anymore for unknown value, we deserialize as a string + _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) + return Deserializer.deserialize_unicode(data) + + @staticmethod + def deserialize_bytearray(attr): + """Deserialize string into bytearray. + + :param str attr: response string to be deserialized. + :rtype: bytearray + :raises: TypeError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + return bytearray(b64decode(attr)) + + @staticmethod + def deserialize_base64(attr): + """Deserialize base64 encoded string into string. + + :param str attr: response string to be deserialized. + :rtype: bytearray + :raises: TypeError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + padding = "=" * (3 - (len(attr) + 3) % 4) + attr = attr + padding + encoded = attr.replace("-", "+").replace("_", "/") + return b64decode(encoded) + + @staticmethod + def deserialize_decimal(attr): + """Deserialize string into Decimal object. + + :param str attr: response string to be deserialized. + :rtype: Decimal + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + return decimal.Decimal(attr) + except decimal.DecimalException as err: + msg = "Invalid decimal {}".format(attr) + raise_with_traceback(DeserializationError, msg, err) + + @staticmethod + def deserialize_long(attr): + """Deserialize string into long (Py2) or int (Py3). + + :param str attr: response string to be deserialized. + :rtype: long or int + :raises: ValueError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + return _long_type(attr) + + @staticmethod + def deserialize_duration(attr): + """Deserialize ISO-8601 formatted string into TimeDelta object. + + :param str attr: response string to be deserialized. + :rtype: TimeDelta + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = isodate.parse_duration(attr) + except (ValueError, OverflowError, AttributeError) as err: + msg = "Cannot deserialize duration object." + raise_with_traceback(DeserializationError, msg, err) + else: + return duration + + @staticmethod + def deserialize_date(attr): + """Deserialize ISO-8601 formatted string into Date object. + + :param str attr: response string to be deserialized. + :rtype: Date + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + if re.search(r"[^\W\d_]", attr, re.I + re.U): + raise DeserializationError("Date must have only digits and -. Received: %s" % attr) + # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. + return isodate.parse_date(attr, defaultmonth=None, defaultday=None) + + @staticmethod + def deserialize_time(attr): + """Deserialize ISO-8601 formatted string into time object. + + :param str attr: response string to be deserialized. + :rtype: datetime.time + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + if re.search(r"[^\W\d_]", attr, re.I + re.U): + raise DeserializationError("Date must have only digits and -. Received: %s" % attr) + return isodate.parse_time(attr) + + @staticmethod + def deserialize_rfc(attr): + """Deserialize RFC-1123 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: Datetime + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + parsed_date = email.utils.parsedate_tz(attr) + date_obj = datetime.datetime( + *parsed_date[:6], tzinfo=_FixedOffset(datetime.timedelta(minutes=(parsed_date[9] or 0) / 60)) + ) + if not date_obj.tzinfo: + date_obj = date_obj.astimezone(tz=TZ_UTC) + except ValueError as err: + msg = "Cannot deserialize to rfc datetime object." + raise_with_traceback(DeserializationError, msg, err) + else: + return date_obj + + @staticmethod + def deserialize_iso(attr): + """Deserialize ISO-8601 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: Datetime + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + attr = attr.upper() + match = Deserializer.valid_date.match(attr) + if not match: + raise ValueError("Invalid datetime string: " + attr) + + check_decimal = attr.split(".") + if len(check_decimal) > 1: + decimal_str = "" + for digit in check_decimal[1]: + if digit.isdigit(): + decimal_str += digit + else: + break + if len(decimal_str) > 6: + attr = attr.replace(decimal_str, decimal_str[0:6]) + + date_obj = isodate.parse_datetime(attr) + test_utc = date_obj.utctimetuple() + if test_utc.tm_year > 9999 or test_utc.tm_year < 1: + raise OverflowError("Hit max or min date") + except (ValueError, OverflowError, AttributeError) as err: + msg = "Cannot deserialize datetime object." + raise_with_traceback(DeserializationError, msg, err) + else: + return date_obj + + @staticmethod + def deserialize_unix(attr): + """Serialize Datetime object into IntTime format. + This is represented as seconds. + + :param int attr: Object to be serialized. + :rtype: Datetime + :raises: DeserializationError if format invalid + """ + if isinstance(attr, ET.Element): + attr = int(attr.text) + try: + date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) + except ValueError as err: + msg = "Cannot deserialize to unix datetime object." + raise_with_traceback(DeserializationError, msg, err) + else: + return date_obj diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/_vendor.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/_vendor.py index ee43e03d9693..0ec6d0317539 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/_vendor.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/_vendor.py @@ -14,10 +14,11 @@ if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports - from msrest import Deserializer, Serializer - from azure.core import PipelineClient + from ._serialization import Deserializer, Serializer + + 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) @@ -25,6 +26,7 @@ def _convert_request(request, files=None): request.set_formdata_body(files) return request + def _format_url_section(template, **kwargs): components = template.split("/") while components: @@ -32,13 +34,13 @@ def _format_url_section(template, **kwargs): return template.format(**kwargs) except KeyError as key: formatted_components = template.split("/") - components = [ - c for c in formatted_components if "{}".format(key.args[0]) not in c - ] + components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] template = "/".join(components) + class MixinABC(ABC): """DO NOT use this class. It is for internal typing use only.""" + _client: "PipelineClient" _config: MySQLManagementClientConfiguration _serialize: "Serializer" diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/_version.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/_version.py index a172f504a7eb..e5754a47ce68 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/_version.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "10.2.0b3" +VERSION = "1.0.0b1" diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/__init__.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/__init__.py index a25065677613..2899d38f999d 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/__init__.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/__init__.py @@ -14,7 +14,8 @@ except ImportError: _patch_all = [] from ._patch import patch_sdk as _patch_sdk -__all__ = ['MySQLManagementClient'] + +__all__ = ["MySQLManagementClient"] __all__.extend([p for p in _patch_all if p not in __all__]) _patch_sdk() diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/_configuration.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/_configuration.py index 87db9668233f..aeda478aee23 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/_configuration.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/_configuration.py @@ -25,18 +25,13 @@ class MySQLManagementClientConfiguration(Configuration): # pylint: disable=too- Note that all parameters used to create this instance are saved as instance attributes. - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: The ID of the target subscription. + :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str """ - def __init__( - self, - credential: "AsyncTokenCredential", - subscription_id: str, - **kwargs: Any - ) -> None: + def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: super(MySQLManagementClientConfiguration, self).__init__(**kwargs) if credential is None: raise ValueError("Parameter 'credential' must not be None.") @@ -45,22 +40,21 @@ def __init__( self.credential = credential self.subscription_id = subscription_id - self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'mgmt-rdbms/{}'.format(VERSION)) + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-rdbms/{}".format(VERSION)) self._configure(**kwargs) - def _configure( - self, - **kwargs: Any - ) -> None: - self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get('retry_policy') or policies.AsyncRetryPolicy(**kwargs) - self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get('redirect_policy') or policies.AsyncRedirectPolicy(**kwargs) - self.authentication_policy = kwargs.get('authentication_policy') + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: - self.authentication_policy = AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs) + self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/_my_sql_management_client.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/_my_sql_management_client.py index b0fb3544f7e6..ba5548eaaa3b 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/_my_sql_management_client.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/_my_sql_management_client.py @@ -9,20 +9,49 @@ from copy import deepcopy from typing import Any, Awaitable, TYPE_CHECKING -from msrest import Deserializer, Serializer - from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient from .. import models +from .._serialization import Deserializer, Serializer from ._configuration import MySQLManagementClientConfiguration -from .operations import AdvisorsOperations, CheckNameAvailabilityOperations, ConfigurationsOperations, DatabasesOperations, FirewallRulesOperations, LocationBasedPerformanceTierOperations, LocationBasedRecommendedActionSessionsOperationStatusOperations, LocationBasedRecommendedActionSessionsResultOperations, LogFilesOperations, MySQLManagementClientOperationsMixin, Operations, PrivateEndpointConnectionsOperations, PrivateLinkResourcesOperations, QueryTextsOperations, RecommendedActionsOperations, RecoverableServersOperations, ReplicasOperations, ServerAdministratorsOperations, ServerBasedPerformanceTierOperations, ServerKeysOperations, ServerParametersOperations, ServerSecurityAlertPoliciesOperations, ServersOperations, TopQueryStatisticsOperations, VirtualNetworkRulesOperations, WaitStatisticsOperations +from .operations import ( + AdvisorsOperations, + CheckNameAvailabilityOperations, + ConfigurationsOperations, + DatabasesOperations, + FirewallRulesOperations, + LocationBasedPerformanceTierOperations, + LocationBasedRecommendedActionSessionsOperationStatusOperations, + LocationBasedRecommendedActionSessionsResultOperations, + LogFilesOperations, + MySQLManagementClientOperationsMixin, + Operations, + PrivateEndpointConnectionsOperations, + PrivateLinkResourcesOperations, + QueryTextsOperations, + RecommendedActionsOperations, + RecoverableServersOperations, + ReplicasOperations, + ServerAdministratorsOperations, + ServerBasedPerformanceTierOperations, + ServerKeysOperations, + ServerParametersOperations, + ServerSecurityAlertPoliciesOperations, + ServersOperations, + TopQueryStatisticsOperations, + VirtualNetworkRulesOperations, + WaitStatisticsOperations, +) if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MySQLManagementClient(MySQLManagementClientOperationsMixin): # pylint: disable=too-many-instance-attributes + +class MySQLManagementClient( + MySQLManagementClientOperationsMixin +): # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes """The Microsoft Azure management API provides create, read, update, and delete functionality for Azure MySQL resources including servers, databases, firewall rules, VNET rules, log files and configurations with new business model. @@ -92,9 +121,9 @@ class MySQLManagementClient(MySQLManagementClientOperationsMixin): # pylint: azure.mgmt.rdbms.mysql.aio.operations.PrivateLinkResourcesOperations :ivar server_keys: ServerKeysOperations operations :vartype server_keys: azure.mgmt.rdbms.mysql.aio.operations.ServerKeysOperations - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: The ID of the target subscription. + :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str :param base_url: Service URL. Default value is "https://management.azure.com". :type base_url: str @@ -109,37 +138,27 @@ def __init__( base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: - self._config = MySQLManagementClientConfiguration(credential=credential, subscription_id=subscription_id, **kwargs) + self._config = MySQLManagementClientConfiguration( + credential=credential, subscription_id=subscription_id, **kwargs + ) self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) self._deserialize = Deserializer(client_models) self._serialize.client_side_validation = False - self.servers = ServersOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.replicas = ReplicasOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.firewall_rules = FirewallRulesOperations( - self._client, self._config, self._serialize, self._deserialize - ) + self.servers = ServersOperations(self._client, self._config, self._serialize, self._deserialize) + self.replicas = ReplicasOperations(self._client, self._config, self._serialize, self._deserialize) + self.firewall_rules = FirewallRulesOperations(self._client, self._config, self._serialize, self._deserialize) self.virtual_network_rules = VirtualNetworkRulesOperations( self._client, self._config, self._serialize, self._deserialize ) - self.databases = DatabasesOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.configurations = ConfigurationsOperations( - self._client, self._config, self._serialize, self._deserialize - ) + self.databases = DatabasesOperations(self._client, self._config, self._serialize, self._deserialize) + self.configurations = ConfigurationsOperations(self._client, self._config, self._serialize, self._deserialize) self.server_parameters = ServerParametersOperations( self._client, self._config, self._serialize, self._deserialize ) - self.log_files = LogFilesOperations( - self._client, self._config, self._serialize, self._deserialize - ) + self.log_files = LogFilesOperations(self._client, self._config, self._serialize, self._deserialize) self.server_administrators = ServerAdministratorsOperations( self._client, self._config, self._serialize, self._deserialize ) @@ -155,29 +174,23 @@ def __init__( self.check_name_availability = CheckNameAvailabilityOperations( 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) self.server_security_alert_policies = ServerSecurityAlertPoliciesOperations( self._client, self._config, self._serialize, self._deserialize ) - self.query_texts = QueryTextsOperations( - self._client, self._config, self._serialize, self._deserialize - ) + self.query_texts = QueryTextsOperations(self._client, self._config, self._serialize, self._deserialize) self.top_query_statistics = TopQueryStatisticsOperations( self._client, self._config, self._serialize, self._deserialize ) - self.wait_statistics = WaitStatisticsOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.advisors = AdvisorsOperations( - self._client, self._config, self._serialize, self._deserialize - ) + self.wait_statistics = WaitStatisticsOperations(self._client, self._config, self._serialize, self._deserialize) + self.advisors = AdvisorsOperations(self._client, self._config, self._serialize, self._deserialize) self.recommended_actions = RecommendedActionsOperations( self._client, self._config, self._serialize, self._deserialize ) - self.location_based_recommended_action_sessions_operation_status = LocationBasedRecommendedActionSessionsOperationStatusOperations( - self._client, self._config, self._serialize, self._deserialize + self.location_based_recommended_action_sessions_operation_status = ( + LocationBasedRecommendedActionSessionsOperationStatusOperations( + self._client, self._config, self._serialize, self._deserialize + ) ) self.location_based_recommended_action_sessions_result = LocationBasedRecommendedActionSessionsResultOperations( self._client, self._config, self._serialize, self._deserialize @@ -188,16 +201,9 @@ def __init__( self.private_link_resources = PrivateLinkResourcesOperations( self._client, self._config, self._serialize, self._deserialize ) - self.server_keys = ServerKeysOperations( - self._client, self._config, self._serialize, self._deserialize - ) + self.server_keys = ServerKeysOperations(self._client, self._config, self._serialize, self._deserialize) - - def _send_request( - self, - request: HttpRequest, - **kwargs: Any - ) -> Awaitable[AsyncHttpResponse]: + def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: """Runs the network request through the client's chained policies. >>> from azure.core.rest import HttpRequest @@ -206,7 +212,7 @@ def _send_request( >>> response = await client._send_request(request) - For more information on this code flow, see https://aka.ms/azsdk/python/protocol/quickstart + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request :param request: The network request you want to make. Required. :type request: ~azure.core.rest.HttpRequest diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/_patch.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/_patch.py index 74e48ecd07cf..f99e77fef986 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/_patch.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/_patch.py @@ -28,4 +28,4 @@ # This file is used for handwritten extensions to the generated code. Example: # https://github.com/Azure/azure-sdk-for-python/blob/main/doc/dev/customize_code/how-to-patch-sdk-code.md def patch_sdk(): - pass \ No newline at end of file + pass diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/_vendor.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/_vendor.py index 67a2959400b5..f7944d3f0612 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/_vendor.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/_vendor.py @@ -14,13 +14,14 @@ if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports - from msrest import Deserializer, Serializer - from azure.core import AsyncPipelineClient + from .._serialization import Deserializer, Serializer + class MixinABC(ABC): """DO NOT use this class. It is for internal typing use only.""" + _client: "AsyncPipelineClient" _config: MySQLManagementClientConfiguration _serialize: "Serializer" diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/__init__.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/__init__.py index 496637630f04..da47a12bde7b 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/__init__.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/__init__.py @@ -27,8 +27,12 @@ from ._my_sql_management_client_operations import MySQLManagementClientOperationsMixin from ._advisors_operations import AdvisorsOperations from ._recommended_actions_operations import RecommendedActionsOperations -from ._location_based_recommended_action_sessions_operation_status_operations import LocationBasedRecommendedActionSessionsOperationStatusOperations -from ._location_based_recommended_action_sessions_result_operations import LocationBasedRecommendedActionSessionsResultOperations +from ._location_based_recommended_action_sessions_operation_status_operations import ( + LocationBasedRecommendedActionSessionsOperationStatusOperations, +) +from ._location_based_recommended_action_sessions_result_operations import ( + LocationBasedRecommendedActionSessionsResultOperations, +) from ._private_endpoint_connections_operations import PrivateEndpointConnectionsOperations from ._private_link_resources_operations import PrivateLinkResourcesOperations from ._server_keys_operations import ServerKeysOperations @@ -36,33 +40,34 @@ from ._patch import __all__ as _patch_all from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import from ._patch import patch_sdk as _patch_sdk + __all__ = [ - 'ServersOperations', - 'ReplicasOperations', - 'FirewallRulesOperations', - 'VirtualNetworkRulesOperations', - 'DatabasesOperations', - 'ConfigurationsOperations', - 'ServerParametersOperations', - 'LogFilesOperations', - 'ServerAdministratorsOperations', - 'RecoverableServersOperations', - 'ServerBasedPerformanceTierOperations', - 'LocationBasedPerformanceTierOperations', - 'CheckNameAvailabilityOperations', - 'Operations', - 'ServerSecurityAlertPoliciesOperations', - 'QueryTextsOperations', - 'TopQueryStatisticsOperations', - 'WaitStatisticsOperations', - 'MySQLManagementClientOperationsMixin', - 'AdvisorsOperations', - 'RecommendedActionsOperations', - 'LocationBasedRecommendedActionSessionsOperationStatusOperations', - 'LocationBasedRecommendedActionSessionsResultOperations', - 'PrivateEndpointConnectionsOperations', - 'PrivateLinkResourcesOperations', - 'ServerKeysOperations', + "ServersOperations", + "ReplicasOperations", + "FirewallRulesOperations", + "VirtualNetworkRulesOperations", + "DatabasesOperations", + "ConfigurationsOperations", + "ServerParametersOperations", + "LogFilesOperations", + "ServerAdministratorsOperations", + "RecoverableServersOperations", + "ServerBasedPerformanceTierOperations", + "LocationBasedPerformanceTierOperations", + "CheckNameAvailabilityOperations", + "Operations", + "ServerSecurityAlertPoliciesOperations", + "QueryTextsOperations", + "TopQueryStatisticsOperations", + "WaitStatisticsOperations", + "MySQLManagementClientOperationsMixin", + "AdvisorsOperations", + "RecommendedActionsOperations", + "LocationBasedRecommendedActionSessionsOperationStatusOperations", + "LocationBasedRecommendedActionSessionsResultOperations", + "PrivateEndpointConnectionsOperations", + "PrivateLinkResourcesOperations", + "ServerKeysOperations", ] __all__.extend([p for p in _patch_all if p not in __all__]) -_patch_sdk() \ No newline at end of file +_patch_sdk() diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_advisors_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_advisors_operations.py index def2c8353c33..e82ea99f8d62 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_advisors_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_advisors_operations.py @@ -9,7 +9,14 @@ from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest @@ -22,9 +29,11 @@ from ..._vendor import _convert_request from ...operations._advisors_operations import build_get_request, build_list_by_server_request from .._vendor import MixinABC -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class AdvisorsOperations: """ .. warning:: @@ -44,50 +53,45 @@ def __init__(self, *args, **kwargs) -> None: self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace_async async def get( - self, - resource_group_name: str, - server_name: str, - advisor_name: str, - **kwargs: Any + self, resource_group_name: str, server_name: str, advisor_name: str, **kwargs: Any ) -> _models.Advisor: """Get a recommendation action advisor. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param advisor_name: The advisor name for recommendation action. + :param advisor_name: The advisor name for recommendation action. Required. :type advisor_name: str - :keyword api_version: Api Version. Default value is "2018-06-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Advisor, or the result of cls(response) + :return: Advisor or the result of cls(response) :rtype: ~azure.mgmt.rdbms.mysql.models.Advisor - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.Advisor] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.Advisor] - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, advisor_name=advisor_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], headers=_headers, params=_params, ) @@ -95,67 +99,63 @@ async def get( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('Advisor', pipeline_response) + deserialized = self._deserialize("Advisor", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/advisors/{advisorName}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/advisors/{advisorName}"} # type: ignore @distributed_trace def list_by_server( - self, - resource_group_name: str, - server_name: str, - **kwargs: Any - ) -> AsyncIterable[_models.AdvisorsResultList]: + self, resource_group_name: str, server_name: str, **kwargs: Any + ) -> AsyncIterable["_models.Advisor"]: """List recommendation action advisors. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :keyword api_version: Api Version. Default value is "2018-06-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either AdvisorsResultList or the result of cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql.models.AdvisorsResultList] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Advisor or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql.models.Advisor] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.AdvisorsResultList] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AdvisorsResultList] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_server_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_server.metadata['url'], + template_url=self.list_by_server.metadata["url"], headers=_headers, params=_params, ) @@ -163,16 +163,7 @@ def prepare_request(next_link=None): request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_by_server_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - server_name=server_name, - api_version=api_version, - template_url=next_link, - headers=_headers, - params=_params, - ) + request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" @@ -188,10 +179,8 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -201,8 +190,6 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list_by_server.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/advisors"} # type: ignore + list_by_server.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/advisors"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_check_name_availability_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_check_name_availability_operations.py index 8566158f8ef6..47a5fb716134 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_check_name_availability_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_check_name_availability_operations.py @@ -6,9 +6,16 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Optional, TypeVar - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest @@ -20,9 +27,11 @@ from ..._vendor import _convert_request from ...operations._check_name_availability_operations import build_execute_request from .._vendor import MixinABC -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class CheckNameAvailabilityOperations: """ .. warning:: @@ -42,46 +51,93 @@ def __init__(self, *args, **kwargs) -> None: self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace_async + @overload async def execute( self, name_availability_request: _models.NameAvailabilityRequest, + *, + content_type: str = "application/json", **kwargs: Any ) -> _models.NameAvailability: """Check the availability of name for resource. :param name_availability_request: The required parameters for checking if resource name is - available. + available. Required. :type name_availability_request: ~azure.mgmt.rdbms.mysql.models.NameAvailabilityRequest - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: NameAvailability or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql.models.NameAvailability + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def execute( + self, name_availability_request: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.NameAvailability: + """Check the availability of name for resource. + + :param name_availability_request: The required parameters for checking if resource name is + available. Required. + :type name_availability_request: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: NameAvailability, or the result of cls(response) + :return: NameAvailability or the result of cls(response) :rtype: ~azure.mgmt.rdbms.mysql.models.NameAvailability - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def execute( + self, name_availability_request: Union[_models.NameAvailabilityRequest, IO], **kwargs: Any + ) -> _models.NameAvailability: + """Check the availability of name for resource. + + :param name_availability_request: The required parameters for checking if resource name is + available. Is either a model type or a IO type. Required. + :type name_availability_request: ~azure.mgmt.rdbms.mysql.models.NameAvailabilityRequest or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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: NameAvailability or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql.models.NameAvailability + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[_models.NameAvailability] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.NameAvailability] - _json = self._serialize.body(name_availability_request, 'NameAvailabilityRequest') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(name_availability_request, (IO, bytes)): + _content = name_availability_request + else: + _json = self._serialize.body(name_availability_request, "NameAvailabilityRequest") request = build_execute_request( subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self.execute.metadata['url'], + content=_content, + template_url=self.execute.metadata["url"], headers=_headers, params=_params, ) @@ -89,22 +145,20 @@ async def execute( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('NameAvailability', pipeline_response) + deserialized = self._deserialize("NameAvailability", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - execute.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/checkNameAvailability"} # type: ignore - + execute.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/checkNameAvailability"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_configurations_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_configurations_operations.py index 3965a610526e..543548aa0796 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_configurations_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_configurations_operations.py @@ -6,10 +6,17 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar, Union, cast +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod @@ -22,11 +29,17 @@ from ... import models as _models from ..._vendor import _convert_request -from ...operations._configurations_operations import build_create_or_update_request_initial, build_get_request, build_list_by_server_request +from ...operations._configurations_operations import ( + build_create_or_update_request, + build_get_request, + build_list_by_server_request, +) from .._vendor import MixinABC -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class ConfigurationsOperations: """ .. warning:: @@ -46,38 +59,47 @@ def __init__(self, *args, **kwargs) -> None: 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") - async def _create_or_update_initial( self, resource_group_name: str, server_name: str, configuration_name: str, - parameters: _models.Configuration, + parameters: Union[_models.Configuration, IO], **kwargs: Any ) -> Optional[_models.Configuration]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[Optional[_models.Configuration]] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.Configuration]] - _json = self._serialize.body(parameters, 'Configuration') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Configuration") - request = build_create_or_update_request_initial( - subscription_id=self._config.subscription_id, + request = build_create_or_update_request( resource_group_name=resource_group_name, server_name=server_name, configuration_name=configuration_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._create_or_update_initial.metadata['url'], + content=_content, + template_url=self._create_or_update_initial.metadata["url"], headers=_headers, params=_params, ) @@ -85,10 +107,9 @@ async def _create_or_update_initial( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202]: @@ -97,38 +118,40 @@ async def _create_or_update_initial( deserialized = None if response.status_code == 200: - deserialized = self._deserialize('Configuration', pipeline_response) + deserialized = self._deserialize("Configuration", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _create_or_update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/configurations/{configurationName}"} # type: ignore - + _create_or_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/configurations/{configurationName}"} # type: ignore - @distributed_trace_async + @overload async def begin_create_or_update( self, resource_group_name: str, server_name: str, configuration_name: str, parameters: _models.Configuration, + *, + content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.Configuration]: """Updates a configuration of a server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param configuration_name: The name of the server configuration. + :param configuration_name: The name of the server configuration. Required. :type configuration_name: str - :param parameters: The required parameters for updating a server configuration. + :param parameters: The required parameters for updating a server configuration. Required. :type parameters: ~azure.mgmt.rdbms.mysql.models.Configuration - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :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 @@ -140,20 +163,94 @@ async def begin_create_or_update( :return: An instance of AsyncLROPoller that returns either Configuration or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql.models.Configuration] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + configuration_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.Configuration]: + """Updates a configuration of a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param configuration_name: The name of the server configuration. Required. + :type configuration_name: str + :param parameters: The required parameters for updating a server configuration. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :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 Configuration or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql.models.Configuration] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + configuration_name: str, + parameters: Union[_models.Configuration, IO], + **kwargs: Any + ) -> AsyncLROPoller[_models.Configuration]: + """Updates a configuration of a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param configuration_name: The name of the server configuration. Required. + :type configuration_name: str + :param parameters: The required parameters for updating a server configuration. Is either a + model type or a IO type. Required. + :type parameters: ~azure.mgmt.rdbms.mysql.models.Configuration or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either Configuration or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql.models.Configuration] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[_models.Configuration] - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Configuration] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = await self._create_or_update_initial( # type: ignore resource_group_name=resource_group_name, @@ -162,83 +259,75 @@ async def begin_create_or_update( parameters=parameters, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize('Configuration', pipeline_response) + deserialized = self._deserialize("Configuration", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - if polling is True: - polling_method = cast(AsyncPollingMethod, AsyncARMPolling( - lro_delay, - - - **kwargs - )) # type: AsyncPollingMethod - elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: polling_method = polling + polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_create_or_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/configurations/{configurationName}"} # type: ignore + begin_create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/configurations/{configurationName}"} # type: ignore @distributed_trace_async async def get( - self, - resource_group_name: str, - server_name: str, - configuration_name: str, - **kwargs: Any + self, resource_group_name: str, server_name: str, configuration_name: str, **kwargs: Any ) -> _models.Configuration: """Gets information about a configuration of server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param configuration_name: The name of the server configuration. + :param configuration_name: The name of the server configuration. Required. :type configuration_name: str - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Configuration, or the result of cls(response) + :return: Configuration or the result of cls(response) :rtype: ~azure.mgmt.rdbms.mysql.models.Configuration - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.Configuration] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.Configuration] - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, configuration_name=configuration_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], headers=_headers, params=_params, ) @@ -246,68 +335,63 @@ async def get( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('Configuration', pipeline_response) + deserialized = self._deserialize("Configuration", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/configurations/{configurationName}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/configurations/{configurationName}"} # type: ignore @distributed_trace def list_by_server( - self, - resource_group_name: str, - server_name: str, - **kwargs: Any - ) -> AsyncIterable[_models.ConfigurationListResult]: + self, resource_group_name: str, server_name: str, **kwargs: Any + ) -> AsyncIterable["_models.Configuration"]: """List all the configurations in a given server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ConfigurationListResult or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql.models.ConfigurationListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Configuration or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql.models.Configuration] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.ConfigurationListResult] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ConfigurationListResult] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_server_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_server.metadata['url'], + template_url=self.list_by_server.metadata["url"], headers=_headers, params=_params, ) @@ -315,16 +399,7 @@ def prepare_request(next_link=None): request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_by_server_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - server_name=server_name, - api_version=api_version, - template_url=next_link, - headers=_headers, - params=_params, - ) + request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" @@ -340,10 +415,8 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -353,8 +426,6 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list_by_server.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/configurations"} # type: ignore + list_by_server.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/configurations"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_databases_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_databases_operations.py index 4969670fdb84..00dc8cf5d649 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_databases_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_databases_operations.py @@ -6,10 +6,17 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar, Union, cast +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod @@ -22,11 +29,18 @@ from ... import models as _models from ..._vendor import _convert_request -from ...operations._databases_operations import build_create_or_update_request_initial, build_delete_request_initial, build_get_request, build_list_by_server_request +from ...operations._databases_operations import ( + build_create_or_update_request, + build_delete_request, + build_get_request, + build_list_by_server_request, +) from .._vendor import MixinABC -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class DatabasesOperations: """ .. warning:: @@ -46,38 +60,47 @@ def __init__(self, *args, **kwargs) -> None: 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") - async def _create_or_update_initial( self, resource_group_name: str, server_name: str, database_name: str, - parameters: _models.Database, + parameters: Union[_models.Database, IO], **kwargs: Any ) -> Optional[_models.Database]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[Optional[_models.Database]] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.Database]] - _json = self._serialize.body(parameters, 'Database') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Database") - request = build_create_or_update_request_initial( - subscription_id=self._config.subscription_id, + request = build_create_or_update_request( resource_group_name=resource_group_name, server_name=server_name, database_name=database_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._create_or_update_initial.metadata['url'], + content=_content, + template_url=self._create_or_update_initial.metadata["url"], headers=_headers, params=_params, ) @@ -85,10 +108,9 @@ async def _create_or_update_initial( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 201, 202]: @@ -97,41 +119,120 @@ async def _create_or_update_initial( deserialized = None if response.status_code == 200: - deserialized = self._deserialize('Database', pipeline_response) + deserialized = self._deserialize("Database", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('Database', pipeline_response) + deserialized = self._deserialize("Database", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _create_or_update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/databases/{databaseName}"} # type: ignore + _create_or_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/databases/{databaseName}"} # type: ignore - - @distributed_trace_async + @overload async def begin_create_or_update( self, resource_group_name: str, server_name: str, database_name: str, parameters: _models.Database, + *, + content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.Database]: """Creates a new database or updates an existing database. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param database_name: The name of the database. + :param database_name: The name of the database. Required. :type database_name: str - :param parameters: The required parameters for creating or updating a database. + :param parameters: The required parameters for creating or updating a database. Required. :type parameters: ~azure.mgmt.rdbms.mysql.models.Database - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :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 Database or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql.models.Database] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + database_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.Database]: + """Creates a new database or updates an existing database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param database_name: The name of the database. Required. + :type database_name: str + :param parameters: The required parameters for creating or updating a database. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :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 Database or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql.models.Database] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + database_name: str, + parameters: Union[_models.Database, IO], + **kwargs: Any + ) -> AsyncLROPoller[_models.Database]: + """Creates a new database or updates an existing database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param database_name: The name of the database. Required. + :type database_name: str + :param parameters: The required parameters for creating or updating a database. Is either a + model type or a IO type. Required. + :type parameters: ~azure.mgmt.rdbms.mysql.models.Database or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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 @@ -143,20 +244,17 @@ async def begin_create_or_update( :return: An instance of AsyncLROPoller that returns either Database or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql.models.Database] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[_models.Database] - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Database] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = await self._create_or_update_initial( # type: ignore resource_group_name=resource_group_name, @@ -165,66 +263,60 @@ async def begin_create_or_update( parameters=parameters, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize('Database', pipeline_response) + deserialized = self._deserialize("Database", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - if polling is True: - polling_method = cast(AsyncPollingMethod, AsyncARMPolling( - lro_delay, - - - **kwargs - )) # type: AsyncPollingMethod - elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: polling_method = polling + polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_create_or_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/databases/{databaseName}"} # type: ignore + begin_create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/databases/{databaseName}"} # type: ignore async def _delete_initial( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - server_name: str, - database_name: str, - **kwargs: Any + self, resource_group_name: str, server_name: str, database_name: str, **kwargs: Any ) -> None: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] - - request = build_delete_request_initial( - subscription_id=self._config.subscription_id, + request = build_delete_request( resource_group_name=resource_group_name, server_name=server_name, database_name=database_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._delete_initial.metadata['url'], + template_url=self._delete_initial.metadata["url"], headers=_headers, params=_params, ) @@ -232,10 +324,9 @@ async def _delete_initial( # pylint: disable=inconsistent-return-statements request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: @@ -245,28 +336,21 @@ async def _delete_initial( # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - _delete_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/databases/{databaseName}"} # type: ignore - + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/databases/{databaseName}"} # type: ignore @distributed_trace_async - async def begin_delete( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - server_name: str, - database_name: str, - **kwargs: Any + async def begin_delete( + self, resource_group_name: str, server_name: str, database_name: str, **kwargs: Any ) -> AsyncLROPoller[None]: """Deletes a database. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param database_name: The name of the database. + :param database_name: The name of the database. Required. :type database_name: str - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function 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 @@ -277,100 +361,89 @@ async def begin_delete( # pylint: disable=inconsistent-return-statements Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = await self._delete_initial( # type: ignore resource_group_name=resource_group_name, server_name=server_name, database_name=database_name, api_version=api_version, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - if polling is True: - polling_method = cast(AsyncPollingMethod, AsyncARMPolling( - lro_delay, - - - **kwargs - )) # type: AsyncPollingMethod - elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: polling_method = polling + polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_delete.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/databases/{databaseName}"} # type: ignore + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/databases/{databaseName}"} # type: ignore @distributed_trace_async async def get( - self, - resource_group_name: str, - server_name: str, - database_name: str, - **kwargs: Any + self, resource_group_name: str, server_name: str, database_name: str, **kwargs: Any ) -> _models.Database: """Gets information about a database. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param database_name: The name of the database. + :param database_name: The name of the database. Required. :type database_name: str - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Database, or the result of cls(response) + :return: Database or the result of cls(response) :rtype: ~azure.mgmt.rdbms.mysql.models.Database - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.Database] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.Database] - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, database_name=database_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], headers=_headers, params=_params, ) @@ -378,67 +451,63 @@ async def get( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('Database', pipeline_response) + deserialized = self._deserialize("Database", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/databases/{databaseName}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/databases/{databaseName}"} # type: ignore @distributed_trace def list_by_server( - self, - resource_group_name: str, - server_name: str, - **kwargs: Any - ) -> AsyncIterable[_models.DatabaseListResult]: + self, resource_group_name: str, server_name: str, **kwargs: Any + ) -> AsyncIterable["_models.Database"]: """List all the databases in a given server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either DatabaseListResult or the result of cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql.models.DatabaseListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Database or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql.models.Database] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.DatabaseListResult] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.DatabaseListResult] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_server_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_server.metadata['url'], + template_url=self.list_by_server.metadata["url"], headers=_headers, params=_params, ) @@ -446,16 +515,7 @@ def prepare_request(next_link=None): request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_by_server_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - server_name=server_name, - api_version=api_version, - template_url=next_link, - headers=_headers, - params=_params, - ) + request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" @@ -471,10 +531,8 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -484,8 +542,6 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list_by_server.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/databases"} # type: ignore + list_by_server.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/databases"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_firewall_rules_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_firewall_rules_operations.py index bd7100f2813b..f3051f9fcdc6 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_firewall_rules_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_firewall_rules_operations.py @@ -6,10 +6,17 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar, Union, cast +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod @@ -22,11 +29,18 @@ from ... import models as _models from ..._vendor import _convert_request -from ...operations._firewall_rules_operations import build_create_or_update_request_initial, build_delete_request_initial, build_get_request, build_list_by_server_request +from ...operations._firewall_rules_operations import ( + build_create_or_update_request, + build_delete_request, + build_get_request, + build_list_by_server_request, +) from .._vendor import MixinABC -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class FirewallRulesOperations: """ .. warning:: @@ -46,38 +60,47 @@ def __init__(self, *args, **kwargs) -> None: 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") - async def _create_or_update_initial( self, resource_group_name: str, server_name: str, firewall_rule_name: str, - parameters: _models.FirewallRule, + parameters: Union[_models.FirewallRule, IO], **kwargs: Any ) -> Optional[_models.FirewallRule]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[Optional[_models.FirewallRule]] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.FirewallRule]] - _json = self._serialize.body(parameters, 'FirewallRule') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "FirewallRule") - request = build_create_or_update_request_initial( - subscription_id=self._config.subscription_id, + request = build_create_or_update_request( resource_group_name=resource_group_name, server_name=server_name, firewall_rule_name=firewall_rule_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._create_or_update_initial.metadata['url'], + content=_content, + template_url=self._create_or_update_initial.metadata["url"], headers=_headers, params=_params, ) @@ -85,10 +108,9 @@ async def _create_or_update_initial( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 201, 202]: @@ -97,41 +119,82 @@ async def _create_or_update_initial( deserialized = None if response.status_code == 200: - deserialized = self._deserialize('FirewallRule', pipeline_response) + deserialized = self._deserialize("FirewallRule", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('FirewallRule', pipeline_response) + deserialized = self._deserialize("FirewallRule", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _create_or_update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/firewallRules/{firewallRuleName}"} # type: ignore + _create_or_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/firewallRules/{firewallRuleName}"} # type: ignore - - @distributed_trace_async + @overload async def begin_create_or_update( self, resource_group_name: str, server_name: str, firewall_rule_name: str, parameters: _models.FirewallRule, + *, + content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.FirewallRule]: """Creates a new firewall rule or updates an existing firewall rule. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param firewall_rule_name: The name of the server firewall rule. + :param firewall_rule_name: The name of the server firewall rule. Required. :type firewall_rule_name: str - :param parameters: The required parameters for creating or updating a firewall rule. + :param parameters: The required parameters for creating or updating a firewall rule. Required. :type parameters: ~azure.mgmt.rdbms.mysql.models.FirewallRule - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :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 FirewallRule or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql.models.FirewallRule] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + firewall_rule_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.FirewallRule]: + """Creates a new firewall rule or updates an existing firewall rule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param firewall_rule_name: The name of the server firewall rule. Required. + :type firewall_rule_name: str + :param parameters: The required parameters for creating or updating a firewall rule. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :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 @@ -143,20 +206,55 @@ async def begin_create_or_update( :return: An instance of AsyncLROPoller that returns either FirewallRule or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql.models.FirewallRule] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + firewall_rule_name: str, + parameters: Union[_models.FirewallRule, IO], + **kwargs: Any + ) -> AsyncLROPoller[_models.FirewallRule]: + """Creates a new firewall rule or updates an existing firewall rule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param firewall_rule_name: The name of the server firewall rule. Required. + :type firewall_rule_name: str + :param parameters: The required parameters for creating or updating a firewall rule. Is either + a model type or a IO type. Required. + :type parameters: ~azure.mgmt.rdbms.mysql.models.FirewallRule or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either FirewallRule or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql.models.FirewallRule] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[_models.FirewallRule] - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.FirewallRule] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = await self._create_or_update_initial( # type: ignore resource_group_name=resource_group_name, @@ -165,66 +263,60 @@ async def begin_create_or_update( parameters=parameters, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize('FirewallRule', pipeline_response) + deserialized = self._deserialize("FirewallRule", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - if polling is True: - polling_method = cast(AsyncPollingMethod, AsyncARMPolling( - lro_delay, - - - **kwargs - )) # type: AsyncPollingMethod - elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: polling_method = polling + polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_create_or_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/firewallRules/{firewallRuleName}"} # type: ignore + begin_create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/firewallRules/{firewallRuleName}"} # type: ignore async def _delete_initial( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - server_name: str, - firewall_rule_name: str, - **kwargs: Any + self, resource_group_name: str, server_name: str, firewall_rule_name: str, **kwargs: Any ) -> None: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] - - request = build_delete_request_initial( - subscription_id=self._config.subscription_id, + request = build_delete_request( resource_group_name=resource_group_name, server_name=server_name, firewall_rule_name=firewall_rule_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._delete_initial.metadata['url'], + template_url=self._delete_initial.metadata["url"], headers=_headers, params=_params, ) @@ -232,10 +324,9 @@ async def _delete_initial( # pylint: disable=inconsistent-return-statements request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: @@ -245,28 +336,21 @@ async def _delete_initial( # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - _delete_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/firewallRules/{firewallRuleName}"} # type: ignore - + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/firewallRules/{firewallRuleName}"} # type: ignore @distributed_trace_async - async def begin_delete( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - server_name: str, - firewall_rule_name: str, - **kwargs: Any + async def begin_delete( + self, resource_group_name: str, server_name: str, firewall_rule_name: str, **kwargs: Any ) -> AsyncLROPoller[None]: """Deletes a server firewall rule. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param firewall_rule_name: The name of the server firewall rule. + :param firewall_rule_name: The name of the server firewall rule. Required. :type firewall_rule_name: str - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function 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 @@ -277,100 +361,89 @@ async def begin_delete( # pylint: disable=inconsistent-return-statements Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = await self._delete_initial( # type: ignore resource_group_name=resource_group_name, server_name=server_name, firewall_rule_name=firewall_rule_name, api_version=api_version, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - if polling is True: - polling_method = cast(AsyncPollingMethod, AsyncARMPolling( - lro_delay, - - - **kwargs - )) # type: AsyncPollingMethod - elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: polling_method = polling + polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_delete.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/firewallRules/{firewallRuleName}"} # type: ignore + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/firewallRules/{firewallRuleName}"} # type: ignore @distributed_trace_async async def get( - self, - resource_group_name: str, - server_name: str, - firewall_rule_name: str, - **kwargs: Any + self, resource_group_name: str, server_name: str, firewall_rule_name: str, **kwargs: Any ) -> _models.FirewallRule: """Gets information about a server firewall rule. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param firewall_rule_name: The name of the server firewall rule. + :param firewall_rule_name: The name of the server firewall rule. Required. :type firewall_rule_name: str - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: FirewallRule, or the result of cls(response) + :return: FirewallRule or the result of cls(response) :rtype: ~azure.mgmt.rdbms.mysql.models.FirewallRule - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.FirewallRule] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.FirewallRule] - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, firewall_rule_name=firewall_rule_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], headers=_headers, params=_params, ) @@ -378,68 +451,63 @@ async def get( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('FirewallRule', pipeline_response) + deserialized = self._deserialize("FirewallRule", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/firewallRules/{firewallRuleName}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/firewallRules/{firewallRuleName}"} # type: ignore @distributed_trace def list_by_server( - self, - resource_group_name: str, - server_name: str, - **kwargs: Any - ) -> AsyncIterable[_models.FirewallRuleListResult]: + self, resource_group_name: str, server_name: str, **kwargs: Any + ) -> AsyncIterable["_models.FirewallRule"]: """List all the firewall rules in a given server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either FirewallRuleListResult or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql.models.FirewallRuleListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either FirewallRule or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql.models.FirewallRule] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.FirewallRuleListResult] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.FirewallRuleListResult] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_server_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_server.metadata['url'], + template_url=self.list_by_server.metadata["url"], headers=_headers, params=_params, ) @@ -447,16 +515,7 @@ def prepare_request(next_link=None): request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_by_server_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - server_name=server_name, - api_version=api_version, - template_url=next_link, - headers=_headers, - params=_params, - ) + request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" @@ -472,10 +531,8 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -485,8 +542,6 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list_by_server.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/firewallRules"} # type: ignore + list_by_server.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/firewallRules"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_location_based_performance_tier_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_location_based_performance_tier_operations.py index efe475c5ef6c..840a20d97711 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_location_based_performance_tier_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_location_based_performance_tier_operations.py @@ -9,7 +9,14 @@ from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest @@ -21,9 +28,11 @@ from ..._vendor import _convert_request from ...operations._location_based_performance_tier_operations import build_list_request from .._vendor import MixinABC -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class LocationBasedPerformanceTierOperations: """ .. warning:: @@ -43,45 +52,41 @@ def __init__(self, *args, **kwargs) -> None: self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace - def list( - self, - location_name: str, - **kwargs: Any - ) -> AsyncIterable[_models.PerformanceTierListResult]: + def list(self, location_name: str, **kwargs: Any) -> AsyncIterable["_models.PerformanceTierProperties"]: """List all the performance tiers at specified location in a given subscription. - :param location_name: The name of the location. + :param location_name: The name of the location. Required. :type location_name: str - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PerformanceTierListResult or the result of + :return: An iterator like instance of either PerformanceTierProperties or the result of cls(response) :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql.models.PerformanceTierListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql.models.PerformanceTierProperties] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.PerformanceTierListResult] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PerformanceTierListResult] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( - subscription_id=self._config.subscription_id, location_name=location_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list.metadata['url'], + template_url=self.list.metadata["url"], headers=_headers, params=_params, ) @@ -89,15 +94,7 @@ def prepare_request(next_link=None): request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_request( - subscription_id=self._config.subscription_id, - location_name=location_name, - api_version=api_version, - template_url=next_link, - headers=_headers, - params=_params, - ) + request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" @@ -113,10 +110,8 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -126,8 +121,6 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/locations/{locationName}/performanceTiers"} # type: ignore + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/locations/{locationName}/performanceTiers"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_location_based_recommended_action_sessions_operation_status_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_location_based_recommended_action_sessions_operation_status_operations.py index 73daee01ceda..ca767bafc806 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_location_based_recommended_action_sessions_operation_status_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_location_based_recommended_action_sessions_operation_status_operations.py @@ -8,7 +8,14 @@ # -------------------------------------------------------------------------- from typing import Any, Callable, Dict, Optional, TypeVar -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest @@ -20,9 +27,11 @@ from ..._vendor import _convert_request from ...operations._location_based_recommended_action_sessions_operation_status_operations import build_get_request from .._vendor import MixinABC -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class LocationBasedRecommendedActionSessionsOperationStatusOperations: """ .. warning:: @@ -42,46 +51,41 @@ def __init__(self, *args, **kwargs) -> None: self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace_async async def get( - self, - location_name: str, - operation_id: str, - **kwargs: Any + self, location_name: str, operation_id: str, **kwargs: Any ) -> _models.RecommendedActionSessionsOperationStatus: """Recommendation action session operation status. - :param location_name: The name of the location. + :param location_name: The name of the location. Required. :type location_name: str - :param operation_id: The operation identifier. + :param operation_id: The operation identifier. Required. :type operation_id: str - :keyword api_version: Api Version. Default value is "2018-06-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RecommendedActionSessionsOperationStatus, or the result of cls(response) + :return: RecommendedActionSessionsOperationStatus or the result of cls(response) :rtype: ~azure.mgmt.rdbms.mysql.models.RecommendedActionSessionsOperationStatus - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.RecommendedActionSessionsOperationStatus] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RecommendedActionSessionsOperationStatus] - request = build_get_request( - subscription_id=self._config.subscription_id, location_name=location_name, operation_id=operation_id, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], headers=_headers, params=_params, ) @@ -89,22 +93,20 @@ async def get( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('RecommendedActionSessionsOperationStatus', pipeline_response) + deserialized = self._deserialize("RecommendedActionSessionsOperationStatus", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/locations/{locationName}/recommendedActionSessionsAzureAsyncOperation/{operationId}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/locations/{locationName}/recommendedActionSessionsAzureAsyncOperation/{operationId}"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_location_based_recommended_action_sessions_result_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_location_based_recommended_action_sessions_result_operations.py index f059fa483915..ca9b8a351f42 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_location_based_recommended_action_sessions_result_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_location_based_recommended_action_sessions_result_operations.py @@ -9,7 +9,14 @@ from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest @@ -21,9 +28,11 @@ from ..._vendor import _convert_request from ...operations._location_based_recommended_action_sessions_result_operations import build_list_request from .._vendor import MixinABC -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class LocationBasedRecommendedActionSessionsResultOperations: """ .. warning:: @@ -43,49 +52,46 @@ def __init__(self, *args, **kwargs) -> None: self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace def list( - self, - location_name: str, - operation_id: str, - **kwargs: Any - ) -> AsyncIterable[_models.RecommendationActionsResultList]: + self, location_name: str, operation_id: str, **kwargs: Any + ) -> AsyncIterable["_models.RecommendationAction"]: """Recommendation action session operation result. - :param location_name: The name of the location. + :param location_name: The name of the location. Required. :type location_name: str - :param operation_id: The operation identifier. + :param operation_id: The operation identifier. Required. :type operation_id: str - :keyword api_version: Api Version. Default value is "2018-06-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RecommendationActionsResultList or the result of + :return: An iterator like instance of either RecommendationAction or the result of cls(response) :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql.models.RecommendationActionsResultList] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql.models.RecommendationAction] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.RecommendationActionsResultList] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RecommendationActionsResultList] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( - subscription_id=self._config.subscription_id, location_name=location_name, operation_id=operation_id, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list.metadata['url'], + template_url=self.list.metadata["url"], headers=_headers, params=_params, ) @@ -93,16 +99,7 @@ def prepare_request(next_link=None): request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_request( - subscription_id=self._config.subscription_id, - location_name=location_name, - operation_id=operation_id, - api_version=api_version, - template_url=next_link, - headers=_headers, - params=_params, - ) + request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" @@ -118,10 +115,8 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -131,8 +126,6 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/locations/{locationName}/recommendedActionSessionsOperationResults/{operationId}"} # type: ignore + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/locations/{locationName}/recommendedActionSessionsOperationResults/{operationId}"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_log_files_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_log_files_operations.py index 6a46f9992df7..89f68eff37a1 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_log_files_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_log_files_operations.py @@ -9,7 +9,14 @@ from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest @@ -21,9 +28,11 @@ from ..._vendor import _convert_request from ...operations._log_files_operations import build_list_by_server_request from .._vendor import MixinABC -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class LogFilesOperations: """ .. warning:: @@ -43,48 +52,45 @@ def __init__(self, *args, **kwargs) -> None: self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace def list_by_server( - self, - resource_group_name: str, - server_name: str, - **kwargs: Any - ) -> AsyncIterable[_models.LogFileListResult]: + self, resource_group_name: str, server_name: str, **kwargs: Any + ) -> AsyncIterable["_models.LogFile"]: """List all the log files in a given server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either LogFileListResult or the result of cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql.models.LogFileListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either LogFile or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql.models.LogFile] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.LogFileListResult] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.LogFileListResult] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_server_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_server.metadata['url'], + template_url=self.list_by_server.metadata["url"], headers=_headers, params=_params, ) @@ -92,16 +98,7 @@ def prepare_request(next_link=None): request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_by_server_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - server_name=server_name, - api_version=api_version, - template_url=next_link, - headers=_headers, - params=_params, - ) + request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" @@ -117,10 +114,8 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -130,8 +125,6 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list_by_server.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/logFiles"} # type: ignore + list_by_server.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/logFiles"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_my_sql_management_client_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_my_sql_management_client_operations.py index be9fae67cfb0..e66e23ffe577 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_my_sql_management_client_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_my_sql_management_client_operations.py @@ -8,7 +8,14 @@ # -------------------------------------------------------------------------- from typing import Any, Callable, Dict, Optional, TypeVar, Union, cast -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod @@ -20,52 +27,53 @@ from ... import models as _models from ..._vendor import _convert_request -from ...operations._my_sql_management_client_operations import build_create_recommended_action_session_request_initial, build_reset_query_performance_insight_data_request +from ...operations._my_sql_management_client_operations import ( + build_create_recommended_action_session_request, + build_reset_query_performance_insight_data_request, +) from .._vendor import MixinABC -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class MySQLManagementClientOperationsMixin(MixinABC): +class MySQLManagementClientOperationsMixin(MixinABC): @distributed_trace_async async def reset_query_performance_insight_data( - self, - resource_group_name: str, - server_name: str, - **kwargs: Any + self, resource_group_name: str, server_name: str, **kwargs: Any ) -> _models.QueryPerformanceInsightResetDataResult: """Reset data for Query Performance Insight. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :keyword api_version: Api Version. Default value is "2018-06-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: QueryPerformanceInsightResetDataResult, or the result of cls(response) + :return: QueryPerformanceInsightResetDataResult or the result of cls(response) :rtype: ~azure.mgmt.rdbms.mysql.models.QueryPerformanceInsightResetDataResult - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.QueryPerformanceInsightResetDataResult] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.QueryPerformanceInsightResetDataResult] - request = build_reset_query_performance_insight_data_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.reset_query_performance_insight_data.metadata['url'], + template_url=self.reset_query_performance_insight_data.metadata["url"], headers=_headers, params=_params, ) @@ -73,54 +81,49 @@ async def reset_query_performance_insight_data( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('QueryPerformanceInsightResetDataResult', pipeline_response) + deserialized = self._deserialize("QueryPerformanceInsightResetDataResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - reset_query_performance_insight_data.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/resetQueryPerformanceInsightData"} # type: ignore - + reset_query_performance_insight_data.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/resetQueryPerformanceInsightData"} # type: ignore async def _create_recommended_action_session_initial( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - server_name: str, - advisor_name: str, - database_name: str, - **kwargs: Any + self, resource_group_name: str, server_name: str, advisor_name: str, database_name: str, **kwargs: Any ) -> None: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] - - request = build_create_recommended_action_session_request_initial( - subscription_id=self._config.subscription_id, + request = build_create_recommended_action_session_request( resource_group_name=resource_group_name, server_name=server_name, advisor_name=advisor_name, - api_version=api_version, + subscription_id=self._config.subscription_id, database_name=database_name, - template_url=self._create_recommended_action_session_initial.metadata['url'], + api_version=api_version, + template_url=self._create_recommended_action_session_initial.metadata["url"], headers=_headers, params=_params, ) @@ -128,10 +131,9 @@ async def _create_recommended_action_session_initial( # pylint: disable=inconsi request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202]: @@ -141,31 +143,23 @@ async def _create_recommended_action_session_initial( # pylint: disable=inconsi if cls: return cls(pipeline_response, None, {}) - _create_recommended_action_session_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/advisors/{advisorName}/createRecommendedActionSession"} # type: ignore - + _create_recommended_action_session_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/advisors/{advisorName}/createRecommendedActionSession"} # type: ignore @distributed_trace_async - async def begin_create_recommended_action_session( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - server_name: str, - advisor_name: str, - database_name: str, - **kwargs: Any + async def begin_create_recommended_action_session( + self, resource_group_name: str, server_name: str, advisor_name: str, database_name: str, **kwargs: Any ) -> AsyncLROPoller[None]: """Create recommendation action session for the advisor. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param advisor_name: The advisor name for recommendation action. + :param advisor_name: The advisor name for recommendation action. Required. :type advisor_name: str - :param database_name: The name of the database. + :param database_name: The name of the database. Required. :type database_name: str - :keyword api_version: Api Version. Default value is "2018-06-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function 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 @@ -176,19 +170,16 @@ async def begin_create_recommended_action_session( # pylint: disable=inconsiste Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = await self._create_recommended_action_session_initial( # type: ignore resource_group_name=resource_group_name, @@ -196,34 +187,30 @@ async def begin_create_recommended_action_session( # pylint: disable=inconsiste advisor_name=advisor_name, database_name=database_name, api_version=api_version, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - if polling is True: - polling_method = cast(AsyncPollingMethod, AsyncARMPolling( - lro_delay, - - - **kwargs - )) # type: AsyncPollingMethod - elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: polling_method = polling + polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_create_recommended_action_session.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/advisors/{advisorName}/createRecommendedActionSession"} # type: ignore + begin_create_recommended_action_session.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/advisors/{advisorName}/createRecommendedActionSession"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_operations.py index deccd8d6e217..aca4ad8f2c39 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_operations.py @@ -8,7 +8,14 @@ # -------------------------------------------------------------------------- from typing import Any, Callable, Dict, Optional, TypeVar -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest @@ -20,9 +27,11 @@ from ..._vendor import _convert_request from ...operations._operations import build_list_request from .._vendor import MixinABC -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class Operations: """ .. warning:: @@ -42,37 +51,32 @@ def __init__(self, *args, **kwargs) -> None: self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace_async - async def list( - self, - **kwargs: Any - ) -> _models.OperationListResult: + async def list(self, **kwargs: Any) -> _models.OperationListResult: """Lists all of the available REST API operations. - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: OperationListResult, or the result of cls(response) + :return: OperationListResult or the result of cls(response) :rtype: ~azure.mgmt.rdbms.mysql.models.OperationListResult - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.OperationListResult] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.OperationListResult] - request = build_list_request( api_version=api_version, - template_url=self.list.metadata['url'], + template_url=self.list.metadata["url"], headers=_headers, params=_params, ) @@ -80,22 +84,20 @@ async def list( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('OperationListResult', pipeline_response) + deserialized = self._deserialize("OperationListResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - list.metadata = {'url': "/providers/Microsoft.DBforMySQL/operations"} # type: ignore - + list.metadata = {"url": "/providers/Microsoft.DBforMySQL/operations"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_patch.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_patch.py index 0ad201a8c586..f7dd32510333 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_patch.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_patch.py @@ -10,6 +10,7 @@ __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. diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_private_endpoint_connections_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_private_endpoint_connections_operations.py index 6ec1a6324ef5..a755ed6d4b1e 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_private_endpoint_connections_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_private_endpoint_connections_operations.py @@ -6,10 +6,17 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar, Union, cast +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod @@ -22,11 +29,19 @@ from ... import models as _models from ..._vendor import _convert_request -from ...operations._private_endpoint_connections_operations import build_create_or_update_request_initial, build_delete_request_initial, build_get_request, build_list_by_server_request, build_update_tags_request_initial +from ...operations._private_endpoint_connections_operations import ( + build_create_or_update_request, + build_delete_request, + build_get_request, + build_list_by_server_request, + build_update_tags_request, +) from .._vendor import MixinABC -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class PrivateEndpointConnectionsOperations: """ .. warning:: @@ -46,50 +61,45 @@ def __init__(self, *args, **kwargs) -> None: self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace_async async def get( - self, - resource_group_name: str, - server_name: str, - private_endpoint_connection_name: str, - **kwargs: Any + self, resource_group_name: str, server_name: str, private_endpoint_connection_name: str, **kwargs: Any ) -> _models.PrivateEndpointConnection: """Gets a private endpoint connection. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param private_endpoint_connection_name: The name of the private endpoint connection. + :param private_endpoint_connection_name: The name of the private endpoint connection. Required. :type private_endpoint_connection_name: str - :keyword api_version: Api Version. Default value is "2018-06-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: PrivateEndpointConnection, or the result of cls(response) + :return: PrivateEndpointConnection or the result of cls(response) :rtype: ~azure.mgmt.rdbms.mysql.models.PrivateEndpointConnection - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.PrivateEndpointConnection] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PrivateEndpointConnection] - request = build_get_request( resource_group_name=resource_group_name, server_name=server_name, private_endpoint_connection_name=private_endpoint_connection_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], headers=_headers, params=_params, ) @@ -97,49 +107,56 @@ async def get( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore async def _create_or_update_initial( self, resource_group_name: str, server_name: str, private_endpoint_connection_name: str, - parameters: _models.PrivateEndpointConnection, + parameters: Union[_models.PrivateEndpointConnection, IO], **kwargs: Any ) -> Optional[_models.PrivateEndpointConnection]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[Optional[_models.PrivateEndpointConnection]] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.PrivateEndpointConnection]] - _json = self._serialize.body(parameters, 'PrivateEndpointConnection') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PrivateEndpointConnection") - request = build_create_or_update_request_initial( + request = build_create_or_update_request( resource_group_name=resource_group_name, server_name=server_name, private_endpoint_connection_name=private_endpoint_connection_name, @@ -147,7 +164,8 @@ async def _create_or_update_initial( api_version=api_version, content_type=content_type, json=_json, - template_url=self._create_or_update_initial.metadata['url'], + content=_content, + template_url=self._create_or_update_initial.metadata["url"], headers=_headers, params=_params, ) @@ -155,10 +173,9 @@ async def _create_or_update_initial( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202]: @@ -167,38 +184,80 @@ async def _create_or_update_initial( deserialized = None if response.status_code == 200: - deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _create_or_update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore - + _create_or_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore - @distributed_trace_async + @overload async def begin_create_or_update( self, resource_group_name: str, server_name: str, private_endpoint_connection_name: str, parameters: _models.PrivateEndpointConnection, + *, + content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.PrivateEndpointConnection]: """Approve or reject a private endpoint connection with a given name. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param private_endpoint_connection_name: + :param private_endpoint_connection_name: Required. :type private_endpoint_connection_name: str - :param parameters: + :param parameters: Required. :type parameters: ~azure.mgmt.rdbms.mysql.models.PrivateEndpointConnection - :keyword api_version: Api Version. Default value is "2018-06-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either PrivateEndpointConnection or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql.models.PrivateEndpointConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + private_endpoint_connection_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.PrivateEndpointConnection]: + """Approve or reject a private endpoint connection with a given name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param private_endpoint_connection_name: Required. + :type private_endpoint_connection_name: str + :param parameters: Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :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 @@ -211,20 +270,55 @@ async def begin_create_or_update( result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql.models.PrivateEndpointConnection] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + private_endpoint_connection_name: str, + parameters: Union[_models.PrivateEndpointConnection, IO], + **kwargs: Any + ) -> AsyncLROPoller[_models.PrivateEndpointConnection]: + """Approve or reject a private endpoint connection with a given name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param private_endpoint_connection_name: Required. + :type private_endpoint_connection_name: str + :param parameters: Is either a model type or a IO type. Required. + :type parameters: ~azure.mgmt.rdbms.mysql.models.PrivateEndpointConnection or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either PrivateEndpointConnection or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql.models.PrivateEndpointConnection] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[_models.PrivateEndpointConnection] - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.PrivateEndpointConnection] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = await self._create_or_update_initial( # type: ignore resource_group_name=resource_group_name, @@ -233,66 +327,60 @@ async def begin_create_or_update( parameters=parameters, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - if polling is True: - polling_method = cast(AsyncPollingMethod, AsyncARMPolling( - lro_delay, - - - **kwargs - )) # type: AsyncPollingMethod - elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: polling_method = polling + polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_create_or_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore + begin_create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore async def _delete_initial( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - server_name: str, - private_endpoint_connection_name: str, - **kwargs: Any + self, resource_group_name: str, server_name: str, private_endpoint_connection_name: str, **kwargs: Any ) -> None: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] - - request = build_delete_request_initial( + request = build_delete_request( resource_group_name=resource_group_name, server_name=server_name, private_endpoint_connection_name=private_endpoint_connection_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._delete_initial.metadata['url'], + template_url=self._delete_initial.metadata["url"], headers=_headers, params=_params, ) @@ -300,10 +388,9 @@ async def _delete_initial( # pylint: disable=inconsistent-return-statements request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: @@ -313,28 +400,21 @@ async def _delete_initial( # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - _delete_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore - + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore @distributed_trace_async - async def begin_delete( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - server_name: str, - private_endpoint_connection_name: str, - **kwargs: Any + async def begin_delete( + self, resource_group_name: str, server_name: str, private_endpoint_connection_name: str, **kwargs: Any ) -> AsyncLROPoller[None]: """Deletes a private endpoint connection with a given name. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param private_endpoint_connection_name: + :param private_endpoint_connection_name: Required. :type private_endpoint_connection_name: str - :keyword api_version: Api Version. Default value is "2018-06-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function 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 @@ -345,88 +425,91 @@ async def begin_delete( # pylint: disable=inconsistent-return-statements Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = await self._delete_initial( # type: ignore resource_group_name=resource_group_name, server_name=server_name, private_endpoint_connection_name=private_endpoint_connection_name, api_version=api_version, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - if polling is True: - polling_method = cast(AsyncPollingMethod, AsyncARMPolling( - lro_delay, - - - **kwargs - )) # type: AsyncPollingMethod - elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: polling_method = polling + polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_delete.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore async def _update_tags_initial( self, resource_group_name: str, server_name: str, private_endpoint_connection_name: str, - parameters: _models.TagsObject, + parameters: Union[_models.TagsObject, IO], **kwargs: Any ) -> _models.PrivateEndpointConnection: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[_models.PrivateEndpointConnection] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.PrivateEndpointConnection] - _json = self._serialize.body(parameters, 'TagsObject') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "TagsObject") - request = build_update_tags_request_initial( - subscription_id=self._config.subscription_id, + request = build_update_tags_request( resource_group_name=resource_group_name, server_name=server_name, private_endpoint_connection_name=private_endpoint_connection_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._update_tags_initial.metadata['url'], + content=_content, + template_url=self._update_tags_initial.metadata["url"], headers=_headers, params=_params, ) @@ -434,33 +517,33 @@ async def _update_tags_initial( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _update_tags_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore - + _update_tags_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore - @distributed_trace_async + @overload async def begin_update_tags( self, resource_group_name: str, server_name: str, private_endpoint_connection_name: str, parameters: _models.TagsObject, + *, + content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.PrivateEndpointConnection]: """Updates tags on private endpoint connection. @@ -468,17 +551,61 @@ async def begin_update_tags( Updates private endpoint connection with the specified tags. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param private_endpoint_connection_name: + :param private_endpoint_connection_name: Required. :type private_endpoint_connection_name: str :param parameters: Parameters supplied to the Update private endpoint connection Tags - operation. + operation. Required. :type parameters: ~azure.mgmt.rdbms.mysql.models.TagsObject - :keyword api_version: Api Version. Default value is "2018-06-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either PrivateEndpointConnection or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql.models.PrivateEndpointConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_update_tags( + self, + resource_group_name: str, + server_name: str, + private_endpoint_connection_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.PrivateEndpointConnection]: + """Updates tags on private endpoint connection. + + Updates private endpoint connection with the specified tags. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param private_endpoint_connection_name: Required. + :type private_endpoint_connection_name: str + :param parameters: Parameters supplied to the Update private endpoint connection Tags + operation. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :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 @@ -491,20 +618,58 @@ async def begin_update_tags( result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql.models.PrivateEndpointConnection] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_update_tags( + self, + resource_group_name: str, + server_name: str, + private_endpoint_connection_name: str, + parameters: Union[_models.TagsObject, IO], + **kwargs: Any + ) -> AsyncLROPoller[_models.PrivateEndpointConnection]: + """Updates tags on private endpoint connection. + + Updates private endpoint connection with the specified tags. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param private_endpoint_connection_name: Required. + :type private_endpoint_connection_name: str + :param parameters: Parameters supplied to the Update private endpoint connection Tags + operation. Is either a model type or a IO type. Required. + :type parameters: ~azure.mgmt.rdbms.mysql.models.TagsObject or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either PrivateEndpointConnection or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql.models.PrivateEndpointConnection] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[_models.PrivateEndpointConnection] - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.PrivateEndpointConnection] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = await self._update_tags_initial( # type: ignore resource_group_name=resource_group_name, @@ -513,82 +678,77 @@ async def begin_update_tags( parameters=parameters, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - if polling is True: - polling_method = cast(AsyncPollingMethod, AsyncARMPolling( - lro_delay, - - - **kwargs - )) # type: AsyncPollingMethod - elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: polling_method = polling + polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_update_tags.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore + begin_update_tags.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore @distributed_trace def list_by_server( - self, - resource_group_name: str, - server_name: str, - **kwargs: Any - ) -> AsyncIterable[_models.PrivateEndpointConnectionListResult]: + self, resource_group_name: str, server_name: str, **kwargs: Any + ) -> AsyncIterable["_models.PrivateEndpointConnection"]: """Gets all private endpoint connections on a server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :keyword api_version: Api Version. Default value is "2018-06-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PrivateEndpointConnectionListResult or the result - of cls(response) + :return: An iterator like instance of either PrivateEndpointConnection or the result of + cls(response) :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql.models.PrivateEndpointConnectionListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql.models.PrivateEndpointConnection] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.PrivateEndpointConnectionListResult] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PrivateEndpointConnectionListResult] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_server_request( resource_group_name=resource_group_name, server_name=server_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_server.metadata['url'], + template_url=self.list_by_server.metadata["url"], headers=_headers, params=_params, ) @@ -596,16 +756,7 @@ def prepare_request(next_link=None): request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_by_server_request( - resource_group_name=resource_group_name, - server_name=server_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - template_url=next_link, - headers=_headers, - params=_params, - ) + request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" @@ -621,10 +772,8 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -634,8 +783,6 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list_by_server.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateEndpointConnections"} # type: ignore + list_by_server.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateEndpointConnections"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_private_link_resources_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_private_link_resources_operations.py index cdc219ab9e88..336bf3f61bfd 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_private_link_resources_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_private_link_resources_operations.py @@ -9,7 +9,14 @@ from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest @@ -22,9 +29,11 @@ from ..._vendor import _convert_request from ...operations._private_link_resources_operations import build_get_request, build_list_by_server_request from .._vendor import MixinABC -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class PrivateLinkResourcesOperations: """ .. warning:: @@ -44,49 +53,46 @@ def __init__(self, *args, **kwargs) -> None: self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace def list_by_server( - self, - resource_group_name: str, - server_name: str, - **kwargs: Any - ) -> AsyncIterable[_models.PrivateLinkResourceListResult]: + self, resource_group_name: str, server_name: str, **kwargs: Any + ) -> AsyncIterable["_models.PrivateLinkResource"]: """Gets the private link resources for MySQL server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :keyword api_version: Api Version. Default value is "2018-06-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PrivateLinkResourceListResult or the result of - cls(response) + :return: An iterator like instance of either PrivateLinkResource or the result of cls(response) :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql.models.PrivateLinkResourceListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql.models.PrivateLinkResource] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.PrivateLinkResourceListResult] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PrivateLinkResourceListResult] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_server_request( resource_group_name=resource_group_name, server_name=server_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_server.metadata['url'], + template_url=self.list_by_server.metadata["url"], headers=_headers, params=_params, ) @@ -94,16 +100,7 @@ def prepare_request(next_link=None): request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_by_server_request( - resource_group_name=resource_group_name, - server_name=server_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - template_url=next_link, - headers=_headers, - params=_params, - ) + request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" @@ -119,10 +116,8 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -132,55 +127,49 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list_by_server.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateLinkResources"} # type: ignore + list_by_server.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateLinkResources"} # type: ignore @distributed_trace_async async def get( - self, - resource_group_name: str, - server_name: str, - group_name: str, - **kwargs: Any + self, resource_group_name: str, server_name: str, group_name: str, **kwargs: Any ) -> _models.PrivateLinkResource: """Gets a private link resource for MySQL server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param group_name: The name of the private link resource. + :param group_name: The name of the private link resource. Required. :type group_name: str - :keyword api_version: Api Version. Default value is "2018-06-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: PrivateLinkResource, or the result of cls(response) + :return: PrivateLinkResource or the result of cls(response) :rtype: ~azure.mgmt.rdbms.mysql.models.PrivateLinkResource - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.PrivateLinkResource] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PrivateLinkResource] - request = build_get_request( resource_group_name=resource_group_name, server_name=server_name, group_name=group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], headers=_headers, params=_params, ) @@ -188,22 +177,20 @@ async def get( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('PrivateLinkResource', pipeline_response) + deserialized = self._deserialize("PrivateLinkResource", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateLinkResources/{groupName}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateLinkResources/{groupName}"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_query_texts_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_query_texts_operations.py index 3edd6e0b99ff..af9a83e72979 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_query_texts_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_query_texts_operations.py @@ -9,7 +9,14 @@ from typing import Any, AsyncIterable, Callable, Dict, List, Optional, TypeVar from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest @@ -22,9 +29,11 @@ from ..._vendor import _convert_request from ...operations._query_texts_operations import build_get_request, build_list_by_server_request from .._vendor import MixinABC -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class QueryTextsOperations: """ .. warning:: @@ -44,50 +53,43 @@ def __init__(self, *args, **kwargs) -> None: self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace_async - async def get( - self, - resource_group_name: str, - server_name: str, - query_id: str, - **kwargs: Any - ) -> _models.QueryText: + async def get(self, resource_group_name: str, server_name: str, query_id: str, **kwargs: Any) -> _models.QueryText: """Retrieve the Query-Store query texts for the queryId. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param query_id: The Query-Store query identifier. + :param query_id: The Query-Store query identifier. Required. :type query_id: str - :keyword api_version: Api Version. Default value is "2018-06-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: QueryText, or the result of cls(response) + :return: QueryText or the result of cls(response) :rtype: ~azure.mgmt.rdbms.mysql.models.QueryText - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.QueryText] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.QueryText] - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, query_id=query_id, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], headers=_headers, params=_params, ) @@ -95,72 +97,66 @@ async def get( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('QueryText', pipeline_response) + deserialized = self._deserialize("QueryText", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/queryTexts/{queryId}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/queryTexts/{queryId}"} # type: ignore @distributed_trace def list_by_server( - self, - resource_group_name: str, - server_name: str, - query_ids: List[str], - **kwargs: Any - ) -> AsyncIterable[_models.QueryTextsResultList]: + self, resource_group_name: str, server_name: str, query_ids: List[str], **kwargs: Any + ) -> AsyncIterable["_models.QueryText"]: """Retrieve the Query-Store query texts for specified queryIds. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param query_ids: The query identifiers. + :param query_ids: The query identifiers. Required. :type query_ids: list[str] - :keyword api_version: Api Version. Default value is "2018-06-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either QueryTextsResultList or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql.models.QueryTextsResultList] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either QueryText or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql.models.QueryText] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.QueryTextsResultList] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.QueryTextsResultList] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_server_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, - api_version=api_version, + subscription_id=self._config.subscription_id, query_ids=query_ids, - template_url=self.list_by_server.metadata['url'], + api_version=api_version, + template_url=self.list_by_server.metadata["url"], headers=_headers, params=_params, ) @@ -168,17 +164,7 @@ def prepare_request(next_link=None): request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_by_server_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - server_name=server_name, - api_version=api_version, - query_ids=query_ids, - template_url=next_link, - headers=_headers, - params=_params, - ) + request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" @@ -194,10 +180,8 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -207,8 +191,6 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list_by_server.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/queryTexts"} # type: ignore + list_by_server.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/queryTexts"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_recommended_actions_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_recommended_actions_operations.py index e1a0166eea46..eba33cd92eca 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_recommended_actions_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_recommended_actions_operations.py @@ -9,7 +9,14 @@ from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest @@ -22,9 +29,11 @@ from ..._vendor import _convert_request from ...operations._recommended_actions_operations import build_get_request, build_list_by_server_request from .._vendor import MixinABC -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class RecommendedActionsOperations: """ .. warning:: @@ -44,54 +53,48 @@ def __init__(self, *args, **kwargs) -> None: self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace_async async def get( - self, - resource_group_name: str, - server_name: str, - advisor_name: str, - recommended_action_name: str, - **kwargs: Any + self, resource_group_name: str, server_name: str, advisor_name: str, recommended_action_name: str, **kwargs: Any ) -> _models.RecommendationAction: """Retrieve recommended actions from the advisor. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param advisor_name: The advisor name for recommendation action. + :param advisor_name: The advisor name for recommendation action. Required. :type advisor_name: str - :param recommended_action_name: The recommended action name. + :param recommended_action_name: The recommended action name. Required. :type recommended_action_name: str - :keyword api_version: Api Version. Default value is "2018-06-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RecommendationAction, or the result of cls(response) + :return: RecommendationAction or the result of cls(response) :rtype: ~azure.mgmt.rdbms.mysql.models.RecommendationAction - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.RecommendationAction] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RecommendationAction] - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, advisor_name=advisor_name, recommended_action_name=recommended_action_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], headers=_headers, params=_params, ) @@ -99,25 +102,23 @@ async def get( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('RecommendationAction', pipeline_response) + deserialized = self._deserialize("RecommendationAction", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/advisors/{advisorName}/recommendedActions/{recommendedActionName}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/advisors/{advisorName}/recommendedActions/{recommendedActionName}"} # type: ignore @distributed_trace def list_by_server( @@ -127,48 +128,50 @@ def list_by_server( advisor_name: str, session_id: Optional[str] = None, **kwargs: Any - ) -> AsyncIterable[_models.RecommendationActionsResultList]: + ) -> AsyncIterable["_models.RecommendationAction"]: """Retrieve recommended actions from the advisor. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param advisor_name: The advisor name for recommendation action. + :param advisor_name: The advisor name for recommendation action. Required. :type advisor_name: str :param session_id: The recommendation action session identifier. Default value is None. :type session_id: str - :keyword api_version: Api Version. Default value is "2018-06-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RecommendationActionsResultList or the result of + :return: An iterator like instance of either RecommendationAction or the result of cls(response) :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql.models.RecommendationActionsResultList] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql.models.RecommendationAction] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.RecommendationActionsResultList] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RecommendationActionsResultList] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_server_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, advisor_name=advisor_name, - api_version=api_version, + subscription_id=self._config.subscription_id, session_id=session_id, - template_url=self.list_by_server.metadata['url'], + api_version=api_version, + template_url=self.list_by_server.metadata["url"], headers=_headers, params=_params, ) @@ -176,18 +179,7 @@ def prepare_request(next_link=None): request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_by_server_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - server_name=server_name, - advisor_name=advisor_name, - api_version=api_version, - session_id=session_id, - template_url=next_link, - headers=_headers, - params=_params, - ) + request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" @@ -203,10 +195,8 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -216,8 +206,6 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list_by_server.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/advisors/{advisorName}/recommendedActions"} # type: ignore + list_by_server.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/advisors/{advisorName}/recommendedActions"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_recoverable_servers_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_recoverable_servers_operations.py index e0c245523bd7..23b5bfcd7427 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_recoverable_servers_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_recoverable_servers_operations.py @@ -8,7 +8,14 @@ # -------------------------------------------------------------------------- from typing import Any, Callable, Dict, Optional, TypeVar -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest @@ -20,9 +27,11 @@ from ..._vendor import _convert_request from ...operations._recoverable_servers_operations import build_get_request from .._vendor import MixinABC -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class RecoverableServersOperations: """ .. warning:: @@ -42,46 +51,40 @@ def __init__(self, *args, **kwargs) -> None: self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace_async - async def get( - self, - resource_group_name: str, - server_name: str, - **kwargs: Any - ) -> _models.RecoverableServerResource: + async def get(self, resource_group_name: str, server_name: str, **kwargs: Any) -> _models.RecoverableServerResource: """Gets a recoverable MySQL Server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RecoverableServerResource, or the result of cls(response) + :return: RecoverableServerResource or the result of cls(response) :rtype: ~azure.mgmt.rdbms.mysql.models.RecoverableServerResource - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.RecoverableServerResource] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RecoverableServerResource] - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], headers=_headers, params=_params, ) @@ -89,22 +92,20 @@ async def get( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('RecoverableServerResource', pipeline_response) + deserialized = self._deserialize("RecoverableServerResource", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/recoverableServers"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/recoverableServers"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_replicas_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_replicas_operations.py index 0e2cf54dac2c..a18d3f11b36b 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_replicas_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_replicas_operations.py @@ -9,7 +9,14 @@ from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest @@ -21,9 +28,11 @@ from ..._vendor import _convert_request from ...operations._replicas_operations import build_list_by_server_request from .._vendor import MixinABC -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class ReplicasOperations: """ .. warning:: @@ -43,48 +52,45 @@ def __init__(self, *args, **kwargs) -> None: self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace def list_by_server( - self, - resource_group_name: str, - server_name: str, - **kwargs: Any - ) -> AsyncIterable[_models.ServerListResult]: + self, resource_group_name: str, server_name: str, **kwargs: Any + ) -> AsyncIterable["_models.Server"]: """List all the replicas for a given server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ServerListResult or the result of cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql.models.ServerListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Server or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql.models.Server] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.ServerListResult] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ServerListResult] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_server_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_server.metadata['url'], + template_url=self.list_by_server.metadata["url"], headers=_headers, params=_params, ) @@ -92,16 +98,7 @@ def prepare_request(next_link=None): request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_by_server_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - server_name=server_name, - api_version=api_version, - template_url=next_link, - headers=_headers, - params=_params, - ) + request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" @@ -117,10 +114,8 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -130,8 +125,6 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list_by_server.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/replicas"} # type: ignore + list_by_server.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/replicas"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_server_administrators_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_server_administrators_operations.py index ea9a2ac1d08d..c414503023c6 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_server_administrators_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_server_administrators_operations.py @@ -6,10 +6,17 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar, Union, cast +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod @@ -22,11 +29,18 @@ from ... import models as _models from ..._vendor import _convert_request -from ...operations._server_administrators_operations import build_create_or_update_request_initial, build_delete_request_initial, build_get_request, build_list_request +from ...operations._server_administrators_operations import ( + build_create_or_update_request, + build_delete_request, + build_get_request, + build_list_request, +) from .._vendor import MixinABC -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class ServerAdministratorsOperations: """ .. warning:: @@ -46,46 +60,42 @@ def __init__(self, *args, **kwargs) -> None: self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace_async async def get( - self, - resource_group_name: str, - server_name: str, - **kwargs: Any + self, resource_group_name: str, server_name: str, **kwargs: Any ) -> _models.ServerAdministratorResource: """Gets information about a AAD server administrator. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: ServerAdministratorResource, or the result of cls(response) + :return: ServerAdministratorResource or the result of cls(response) :rtype: ~azure.mgmt.rdbms.mysql.models.ServerAdministratorResource - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.ServerAdministratorResource] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ServerAdministratorResource] - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], headers=_headers, params=_params, ) @@ -93,55 +103,63 @@ async def get( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('ServerAdministratorResource', pipeline_response) + deserialized = self._deserialize("ServerAdministratorResource", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/administrators/activeDirectory"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/administrators/activeDirectory"} # type: ignore async def _create_or_update_initial( self, resource_group_name: str, server_name: str, - properties: _models.ServerAdministratorResource, + properties: Union[_models.ServerAdministratorResource, IO], **kwargs: Any ) -> _models.ServerAdministratorResource: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[_models.ServerAdministratorResource] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ServerAdministratorResource] - _json = self._serialize.body(properties, 'ServerAdministratorResource') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(properties, (IO, bytes)): + _content = properties + else: + _json = self._serialize.body(properties, "ServerAdministratorResource") - request = build_create_or_update_request_initial( - subscription_id=self._config.subscription_id, + request = build_create_or_update_request( resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._create_or_update_initial.metadata['url'], + content=_content, + template_url=self._create_or_update_initial.metadata["url"], headers=_headers, params=_params, ) @@ -149,10 +167,9 @@ async def _create_or_update_initial( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202]: @@ -160,40 +177,118 @@ async def _create_or_update_initial( raise HttpResponseError(response=response, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('ServerAdministratorResource', pipeline_response) + deserialized = self._deserialize("ServerAdministratorResource", pipeline_response) if response.status_code == 202: - deserialized = self._deserialize('ServerAdministratorResource', pipeline_response) + deserialized = self._deserialize("ServerAdministratorResource", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _create_or_update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/administrators/activeDirectory"} # type: ignore - + _create_or_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/administrators/activeDirectory"} # type: ignore - @distributed_trace_async + @overload async def begin_create_or_update( self, resource_group_name: str, server_name: str, properties: _models.ServerAdministratorResource, + *, + content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.ServerAdministratorResource]: """Creates or update active directory administrator on an existing server. The update action will overwrite the existing administrator. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str :param properties: The required parameters for creating or updating an AAD server - administrator. + administrator. Required. :type properties: ~azure.mgmt.rdbms.mysql.models.ServerAdministratorResource - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :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 ServerAdministratorResource or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql.models.ServerAdministratorResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + properties: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.ServerAdministratorResource]: + """Creates or update active directory administrator on an existing server. The update action will + overwrite the existing administrator. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param properties: The required parameters for creating or updating an AAD server + administrator. Required. + :type properties: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either ServerAdministratorResource or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql.models.ServerAdministratorResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + properties: Union[_models.ServerAdministratorResource, IO], + **kwargs: Any + ) -> AsyncLROPoller[_models.ServerAdministratorResource]: + """Creates or update active directory administrator on an existing server. The update action will + overwrite the existing administrator. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param properties: The required parameters for creating or updating an AAD server + administrator. Is either a model type or a IO type. Required. + :type properties: ~azure.mgmt.rdbms.mysql.models.ServerAdministratorResource or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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 @@ -206,20 +301,17 @@ async def begin_create_or_update( result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql.models.ServerAdministratorResource] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[_models.ServerAdministratorResource] - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ServerAdministratorResource] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = await self._create_or_update_initial( # type: ignore resource_group_name=resource_group_name, @@ -227,64 +319,59 @@ async def begin_create_or_update( properties=properties, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize('ServerAdministratorResource', pipeline_response) + deserialized = self._deserialize("ServerAdministratorResource", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - if polling is True: - polling_method = cast(AsyncPollingMethod, AsyncARMPolling( - lro_delay, - - - **kwargs - )) # type: AsyncPollingMethod - elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: polling_method = polling + polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_create_or_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/administrators/activeDirectory"} # type: ignore + begin_create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/administrators/activeDirectory"} # type: ignore async def _delete_initial( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - server_name: str, - **kwargs: Any + self, resource_group_name: str, server_name: str, **kwargs: Any ) -> None: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] - - request = build_delete_request_initial( - subscription_id=self._config.subscription_id, + request = build_delete_request( resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._delete_initial.metadata['url'], + template_url=self._delete_initial.metadata["url"], headers=_headers, params=_params, ) @@ -292,10 +379,9 @@ async def _delete_initial( # pylint: disable=inconsistent-return-statements request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: @@ -305,25 +391,17 @@ async def _delete_initial( # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - _delete_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/administrators/activeDirectory"} # type: ignore - + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/administrators/activeDirectory"} # type: ignore @distributed_trace_async - async def begin_delete( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - server_name: str, - **kwargs: Any - ) -> AsyncLROPoller[None]: + async def begin_delete(self, resource_group_name: str, server_name: str, **kwargs: Any) -> AsyncLROPoller[None]: """Deletes server active directory administrator. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function 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 @@ -334,98 +412,90 @@ async def begin_delete( # pylint: disable=inconsistent-return-statements Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = await self._delete_initial( # type: ignore resource_group_name=resource_group_name, server_name=server_name, api_version=api_version, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - if polling is True: - polling_method = cast(AsyncPollingMethod, AsyncARMPolling( - lro_delay, - - - **kwargs - )) # type: AsyncPollingMethod - elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: polling_method = polling + polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_delete.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/administrators/activeDirectory"} # type: ignore + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/administrators/activeDirectory"} # type: ignore @distributed_trace def list( - self, - resource_group_name: str, - server_name: str, - **kwargs: Any - ) -> AsyncIterable[_models.ServerAdministratorResourceListResult]: + self, resource_group_name: str, server_name: str, **kwargs: Any + ) -> AsyncIterable["_models.ServerAdministratorResource"]: """Returns a list of server Administrators. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ServerAdministratorResourceListResult or the - result of cls(response) + :return: An iterator like instance of either ServerAdministratorResource or the result of + cls(response) :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql.models.ServerAdministratorResourceListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql.models.ServerAdministratorResource] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.ServerAdministratorResourceListResult] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ServerAdministratorResourceListResult] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list.metadata['url'], + template_url=self.list.metadata["url"], headers=_headers, params=_params, ) @@ -433,16 +503,7 @@ def prepare_request(next_link=None): request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - server_name=server_name, - api_version=api_version, - template_url=next_link, - headers=_headers, - params=_params, - ) + request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" @@ -458,10 +519,8 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -471,8 +530,6 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/administrators"} # type: ignore + list.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/administrators"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_server_based_performance_tier_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_server_based_performance_tier_operations.py index 20086d235be3..600916356acb 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_server_based_performance_tier_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_server_based_performance_tier_operations.py @@ -9,7 +9,14 @@ from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest @@ -21,9 +28,11 @@ from ..._vendor import _convert_request from ...operations._server_based_performance_tier_operations import build_list_request from .._vendor import MixinABC -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class ServerBasedPerformanceTierOperations: """ .. warning:: @@ -43,49 +52,47 @@ def __init__(self, *args, **kwargs) -> None: self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace def list( - self, - resource_group_name: str, - server_name: str, - **kwargs: Any - ) -> AsyncIterable[_models.PerformanceTierListResult]: + self, resource_group_name: str, server_name: str, **kwargs: Any + ) -> AsyncIterable["_models.PerformanceTierProperties"]: """List all the performance tiers for a MySQL server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PerformanceTierListResult or the result of + :return: An iterator like instance of either PerformanceTierProperties or the result of cls(response) :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql.models.PerformanceTierListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql.models.PerformanceTierProperties] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.PerformanceTierListResult] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PerformanceTierListResult] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list.metadata['url'], + template_url=self.list.metadata["url"], headers=_headers, params=_params, ) @@ -93,16 +100,7 @@ def prepare_request(next_link=None): request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - server_name=server_name, - api_version=api_version, - template_url=next_link, - headers=_headers, - params=_params, - ) + request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" @@ -118,10 +116,8 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -131,8 +127,6 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/performanceTiers"} # type: ignore + list.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/performanceTiers"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_server_keys_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_server_keys_operations.py index 263f8bc3f87e..81ff1818f58e 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_server_keys_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_server_keys_operations.py @@ -6,10 +6,17 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar, Union, cast +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod @@ -22,11 +29,18 @@ from ... import models as _models from ..._vendor import _convert_request -from ...operations._server_keys_operations import build_create_or_update_request_initial, build_delete_request_initial, build_get_request, build_list_request +from ...operations._server_keys_operations import ( + build_create_or_update_request, + build_delete_request, + build_get_request, + build_list_request, +) from .._vendor import MixinABC -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class ServerKeysOperations: """ .. warning:: @@ -46,48 +60,43 @@ def __init__(self, *args, **kwargs) -> None: self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace - def list( - self, - resource_group_name: str, - server_name: str, - **kwargs: Any - ) -> AsyncIterable[_models.ServerKeyListResult]: + def list(self, resource_group_name: str, server_name: str, **kwargs: Any) -> AsyncIterable["_models.ServerKey"]: """Gets a list of Server keys. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :keyword api_version: Api Version. Default value is "2020-01-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ServerKeyListResult or the result of cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql.models.ServerKeyListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either ServerKey or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql.models.ServerKey] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2020-01-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.ServerKeyListResult] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-01-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ServerKeyListResult] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list.metadata['url'], + template_url=self.list.metadata["url"], headers=_headers, params=_params, ) @@ -95,16 +104,7 @@ def prepare_request(next_link=None): request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - server_name=server_name, - api_version=api_version, - template_url=next_link, - headers=_headers, - params=_params, - ) + request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" @@ -120,10 +120,8 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -133,55 +131,47 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/keys"} # type: ignore + list.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/keys"} # type: ignore @distributed_trace_async - async def get( - self, - resource_group_name: str, - server_name: str, - key_name: str, - **kwargs: Any - ) -> _models.ServerKey: + async def get(self, resource_group_name: str, server_name: str, key_name: str, **kwargs: Any) -> _models.ServerKey: """Gets a MySQL Server key. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param key_name: The name of the MySQL Server key to be retrieved. + :param key_name: The name of the MySQL Server key to be retrieved. Required. :type key_name: str - :keyword api_version: Api Version. Default value is "2020-01-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: ServerKey, or the result of cls(response) + :return: ServerKey or the result of cls(response) :rtype: ~azure.mgmt.rdbms.mysql.models.ServerKey - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2020-01-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.ServerKey] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-01-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ServerKey] - request = build_get_request( resource_group_name=resource_group_name, server_name=server_name, key_name=key_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], headers=_headers, params=_params, ) @@ -189,57 +179,65 @@ async def get( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('ServerKey', pipeline_response) + deserialized = self._deserialize("ServerKey", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/keys/{keyName}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/keys/{keyName}"} # type: ignore async def _create_or_update_initial( self, server_name: str, key_name: str, resource_group_name: str, - parameters: _models.ServerKey, + parameters: Union[_models.ServerKey, IO], **kwargs: Any ) -> _models.ServerKey: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2020-01-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[_models.ServerKey] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-01-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ServerKey] - _json = self._serialize.body(parameters, 'ServerKey') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ServerKey") - request = build_create_or_update_request_initial( + request = build_create_or_update_request( server_name=server_name, key_name=key_name, - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._create_or_update_initial.metadata['url'], + content=_content, + template_url=self._create_or_update_initial.metadata["url"], headers=_headers, params=_params, ) @@ -247,10 +245,9 @@ async def _create_or_update_initial( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202]: @@ -258,41 +255,44 @@ async def _create_or_update_initial( raise HttpResponseError(response=response, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('ServerKey', pipeline_response) + deserialized = self._deserialize("ServerKey", pipeline_response) if response.status_code == 202: - deserialized = self._deserialize('ServerKey', pipeline_response) + deserialized = self._deserialize("ServerKey", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _create_or_update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/keys/{keyName}"} # type: ignore - + _create_or_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/keys/{keyName}"} # type: ignore - @distributed_trace_async + @overload async def begin_create_or_update( self, server_name: str, key_name: str, resource_group_name: str, parameters: _models.ServerKey, + *, + content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.ServerKey]: """Creates or updates a MySQL Server key. - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str :param key_name: The name of the MySQL Server key to be operated on (updated or created). + Required. :type key_name: str :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param parameters: The requested MySQL Server key resource state. + :param parameters: The requested MySQL Server key resource state. Required. :type parameters: ~azure.mgmt.rdbms.mysql.models.ServerKey - :keyword api_version: Api Version. Default value is "2020-01-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :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 @@ -304,20 +304,96 @@ async def begin_create_or_update( :return: An instance of AsyncLROPoller that returns either ServerKey or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql.models.ServerKey] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_or_update( + self, + server_name: str, + key_name: str, + resource_group_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.ServerKey]: + """Creates or updates a MySQL Server key. + + :param server_name: The name of the server. Required. + :type server_name: str + :param key_name: The name of the MySQL Server key to be operated on (updated or created). + Required. + :type key_name: str + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param parameters: The requested MySQL Server key resource state. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :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 ServerKey or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql.models.ServerKey] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_or_update( + self, + server_name: str, + key_name: str, + resource_group_name: str, + parameters: Union[_models.ServerKey, IO], + **kwargs: Any + ) -> AsyncLROPoller[_models.ServerKey]: + """Creates or updates a MySQL Server key. + + :param server_name: The name of the server. Required. + :type server_name: str + :param key_name: The name of the MySQL Server key to be operated on (updated or created). + Required. + :type key_name: str + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param parameters: The requested MySQL Server key resource state. Is either a model type or a + IO type. Required. + :type parameters: ~azure.mgmt.rdbms.mysql.models.ServerKey or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either ServerKey or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql.models.ServerKey] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2020-01-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[_models.ServerKey] - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-01-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ServerKey] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = await self._create_or_update_initial( # type: ignore server_name=server_name, @@ -326,66 +402,60 @@ async def begin_create_or_update( parameters=parameters, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize('ServerKey', pipeline_response) + deserialized = self._deserialize("ServerKey", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - if polling is True: - polling_method = cast(AsyncPollingMethod, AsyncARMPolling( - lro_delay, - - - **kwargs - )) # type: AsyncPollingMethod - elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: polling_method = polling + polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_create_or_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/keys/{keyName}"} # type: ignore + begin_create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/keys/{keyName}"} # type: ignore async def _delete_initial( # pylint: disable=inconsistent-return-statements - self, - server_name: str, - key_name: str, - resource_group_name: str, - **kwargs: Any + self, server_name: str, key_name: str, resource_group_name: str, **kwargs: Any ) -> None: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2020-01-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-01-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] - - request = build_delete_request_initial( + request = build_delete_request( server_name=server_name, key_name=key_name, - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._delete_initial.metadata['url'], + template_url=self._delete_initial.metadata["url"], headers=_headers, params=_params, ) @@ -393,10 +463,9 @@ async def _delete_initial( # pylint: disable=inconsistent-return-statements request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: @@ -406,28 +475,21 @@ async def _delete_initial( # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - _delete_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/keys/{keyName}"} # type: ignore - + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/keys/{keyName}"} # type: ignore @distributed_trace_async - async def begin_delete( # pylint: disable=inconsistent-return-statements - self, - server_name: str, - key_name: str, - resource_group_name: str, - **kwargs: Any + async def begin_delete( + self, server_name: str, key_name: str, resource_group_name: str, **kwargs: Any ) -> AsyncLROPoller[None]: """Deletes the MySQL Server key with the given name. - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param key_name: The name of the MySQL Server key to be deleted. + :param key_name: The name of the MySQL Server key to be deleted. Required. :type key_name: str :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :keyword api_version: Api Version. Default value is "2020-01-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function 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 @@ -438,53 +500,46 @@ async def begin_delete( # pylint: disable=inconsistent-return-statements Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2020-01-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-01-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = await self._delete_initial( # type: ignore server_name=server_name, key_name=key_name, resource_group_name=resource_group_name, api_version=api_version, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - if polling is True: - polling_method = cast(AsyncPollingMethod, AsyncARMPolling( - lro_delay, - - - **kwargs - )) # type: AsyncPollingMethod - elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: polling_method = polling + polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_delete.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/keys/{keyName}"} # type: ignore + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/keys/{keyName}"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_server_parameters_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_server_parameters_operations.py index e984c90b12d8..5923d1706222 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_server_parameters_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_server_parameters_operations.py @@ -6,9 +6,16 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Optional, TypeVar, Union, cast +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod @@ -20,11 +27,13 @@ from ... import models as _models from ..._vendor import _convert_request -from ...operations._server_parameters_operations import build_list_update_configurations_request_initial +from ...operations._server_parameters_operations import build_list_update_configurations_request from .._vendor import MixinABC -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class ServerParametersOperations: """ .. warning:: @@ -44,36 +53,45 @@ def __init__(self, *args, **kwargs) -> None: 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") - async def _list_update_configurations_initial( self, resource_group_name: str, server_name: str, - value: _models.ConfigurationListResult, + value: Union[_models.ConfigurationListResult, IO], **kwargs: Any ) -> Optional[_models.ConfigurationListResult]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[Optional[_models.ConfigurationListResult]] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.ConfigurationListResult]] - _json = self._serialize.body(value, 'ConfigurationListResult') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(value, (IO, bytes)): + _content = value + else: + _json = self._serialize.body(value, "ConfigurationListResult") - request = build_list_update_configurations_request_initial( - subscription_id=self._config.subscription_id, + request = build_list_update_configurations_request( resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._list_update_configurations_initial.metadata['url'], + content=_content, + template_url=self._list_update_configurations_initial.metadata["url"], headers=_headers, params=_params, ) @@ -81,10 +99,9 @@ async def _list_update_configurations_initial( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202]: @@ -93,35 +110,37 @@ async def _list_update_configurations_initial( deserialized = None if response.status_code == 200: - deserialized = self._deserialize('ConfigurationListResult', pipeline_response) + deserialized = self._deserialize("ConfigurationListResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _list_update_configurations_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/updateConfigurations"} # type: ignore - + _list_update_configurations_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/updateConfigurations"} # type: ignore - @distributed_trace_async + @overload async def begin_list_update_configurations( self, resource_group_name: str, server_name: str, value: _models.ConfigurationListResult, + *, + content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.ConfigurationListResult]: """Update a list of configurations in a given server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param value: The parameters for updating a list of server configuration. + :param value: The parameters for updating a list of server configuration. Required. :type value: ~azure.mgmt.rdbms.mysql.models.ConfigurationListResult - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :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 @@ -134,20 +153,90 @@ async def begin_list_update_configurations( result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql.models.ConfigurationListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_list_update_configurations( + self, + resource_group_name: str, + server_name: str, + value: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.ConfigurationListResult]: + """Update a list of configurations in a given server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param value: The parameters for updating a list of server configuration. Required. + :type value: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either ConfigurationListResult or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql.models.ConfigurationListResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_list_update_configurations( + self, + resource_group_name: str, + server_name: str, + value: Union[_models.ConfigurationListResult, IO], + **kwargs: Any + ) -> AsyncLROPoller[_models.ConfigurationListResult]: + """Update a list of configurations in a given server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param value: The parameters for updating a list of server configuration. Is either a model + type or a IO type. Required. + :type value: ~azure.mgmt.rdbms.mysql.models.ConfigurationListResult or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either ConfigurationListResult or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql.models.ConfigurationListResult] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[_models.ConfigurationListResult] - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ConfigurationListResult] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = await self._list_update_configurations_initial( # type: ignore resource_group_name=resource_group_name, @@ -155,36 +244,35 @@ async def begin_list_update_configurations( value=value, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize('ConfigurationListResult', pipeline_response) + deserialized = self._deserialize("ConfigurationListResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - if polling is True: - polling_method = cast(AsyncPollingMethod, AsyncARMPolling( - lro_delay, - lro_options={'final-state-via': 'azure-async-operation'}, - - **kwargs - )) # type: AsyncPollingMethod - elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: polling_method = polling + polling_method = cast( + AsyncPollingMethod, + AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs), + ) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_list_update_configurations.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/updateConfigurations"} # type: ignore + begin_list_update_configurations.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/updateConfigurations"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_server_security_alert_policies_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_server_security_alert_policies_operations.py index 3ee496e40f79..6a5f2a2c7f53 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_server_security_alert_policies_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_server_security_alert_policies_operations.py @@ -6,10 +6,17 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar, Union, cast +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod @@ -22,11 +29,17 @@ from ... import models as _models from ..._vendor import _convert_request -from ...operations._server_security_alert_policies_operations import build_create_or_update_request_initial, build_get_request, build_list_by_server_request +from ...operations._server_security_alert_policies_operations import ( + build_create_or_update_request, + build_get_request, + build_list_by_server_request, +) from .._vendor import MixinABC -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class ServerSecurityAlertPoliciesOperations: """ .. warning:: @@ -46,50 +59,49 @@ def __init__(self, *args, **kwargs) -> None: self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace_async async def get( self, resource_group_name: str, server_name: str, - security_alert_policy_name: Union[str, "_models.SecurityAlertPolicyName"], + security_alert_policy_name: Union[str, _models.SecurityAlertPolicyName], **kwargs: Any ) -> _models.ServerSecurityAlertPolicy: """Get a server's security alert policy. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param security_alert_policy_name: The name of the security alert policy. + :param security_alert_policy_name: The name of the security alert policy. "Default" Required. :type security_alert_policy_name: str or ~azure.mgmt.rdbms.mysql.models.SecurityAlertPolicyName - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: ServerSecurityAlertPolicy, or the result of cls(response) + :return: ServerSecurityAlertPolicy or the result of cls(response) :rtype: ~azure.mgmt.rdbms.mysql.models.ServerSecurityAlertPolicy - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.ServerSecurityAlertPolicy] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ServerSecurityAlertPolicy] - request = build_get_request( resource_group_name=resource_group_name, server_name=server_name, security_alert_policy_name=security_alert_policy_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], headers=_headers, params=_params, ) @@ -97,49 +109,56 @@ async def get( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('ServerSecurityAlertPolicy', pipeline_response) + deserialized = self._deserialize("ServerSecurityAlertPolicy", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/securityAlertPolicies/{securityAlertPolicyName}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/securityAlertPolicies/{securityAlertPolicyName}"} # type: ignore async def _create_or_update_initial( self, resource_group_name: str, server_name: str, - security_alert_policy_name: Union[str, "_models.SecurityAlertPolicyName"], - parameters: _models.ServerSecurityAlertPolicy, + security_alert_policy_name: Union[str, _models.SecurityAlertPolicyName], + parameters: Union[_models.ServerSecurityAlertPolicy, IO], **kwargs: Any ) -> Optional[_models.ServerSecurityAlertPolicy]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[Optional[_models.ServerSecurityAlertPolicy]] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.ServerSecurityAlertPolicy]] - _json = self._serialize.body(parameters, 'ServerSecurityAlertPolicy') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ServerSecurityAlertPolicy") - request = build_create_or_update_request_initial( + request = build_create_or_update_request( resource_group_name=resource_group_name, server_name=server_name, security_alert_policy_name=security_alert_policy_name, @@ -147,7 +166,8 @@ async def _create_or_update_initial( api_version=api_version, content_type=content_type, json=_json, - template_url=self._create_or_update_initial.metadata['url'], + content=_content, + template_url=self._create_or_update_initial.metadata["url"], headers=_headers, params=_params, ) @@ -155,10 +175,9 @@ async def _create_or_update_initial( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202]: @@ -167,38 +186,40 @@ async def _create_or_update_initial( deserialized = None if response.status_code == 200: - deserialized = self._deserialize('ServerSecurityAlertPolicy', pipeline_response) + deserialized = self._deserialize("ServerSecurityAlertPolicy", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _create_or_update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/securityAlertPolicies/{securityAlertPolicyName}"} # type: ignore - + _create_or_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/securityAlertPolicies/{securityAlertPolicyName}"} # type: ignore - @distributed_trace_async + @overload async def begin_create_or_update( self, resource_group_name: str, server_name: str, - security_alert_policy_name: Union[str, "_models.SecurityAlertPolicyName"], + security_alert_policy_name: Union[str, _models.SecurityAlertPolicyName], parameters: _models.ServerSecurityAlertPolicy, + *, + content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.ServerSecurityAlertPolicy]: """Creates or updates a threat detection policy. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param security_alert_policy_name: The name of the threat detection policy. + :param security_alert_policy_name: The name of the threat detection policy. "Default" Required. :type security_alert_policy_name: str or ~azure.mgmt.rdbms.mysql.models.SecurityAlertPolicyName - :param parameters: The server security alert policy. + :param parameters: The server security alert policy. Required. :type parameters: ~azure.mgmt.rdbms.mysql.models.ServerSecurityAlertPolicy - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :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 @@ -211,20 +232,96 @@ async def begin_create_or_update( result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql.models.ServerSecurityAlertPolicy] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + security_alert_policy_name: Union[str, _models.SecurityAlertPolicyName], + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.ServerSecurityAlertPolicy]: + """Creates or updates a threat detection policy. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param security_alert_policy_name: The name of the threat detection policy. "Default" Required. + :type security_alert_policy_name: str or ~azure.mgmt.rdbms.mysql.models.SecurityAlertPolicyName + :param parameters: The server security alert policy. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :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 ServerSecurityAlertPolicy or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql.models.ServerSecurityAlertPolicy] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + security_alert_policy_name: Union[str, _models.SecurityAlertPolicyName], + parameters: Union[_models.ServerSecurityAlertPolicy, IO], + **kwargs: Any + ) -> AsyncLROPoller[_models.ServerSecurityAlertPolicy]: + """Creates or updates a threat detection policy. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param security_alert_policy_name: The name of the threat detection policy. "Default" Required. + :type security_alert_policy_name: str or ~azure.mgmt.rdbms.mysql.models.SecurityAlertPolicyName + :param parameters: The server security alert policy. Is either a model type or a IO type. + Required. + :type parameters: ~azure.mgmt.rdbms.mysql.models.ServerSecurityAlertPolicy or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either ServerSecurityAlertPolicy or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql.models.ServerSecurityAlertPolicy] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[_models.ServerSecurityAlertPolicy] - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ServerSecurityAlertPolicy] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = await self._create_or_update_initial( # type: ignore resource_group_name=resource_group_name, @@ -233,82 +330,77 @@ async def begin_create_or_update( parameters=parameters, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize('ServerSecurityAlertPolicy', pipeline_response) + deserialized = self._deserialize("ServerSecurityAlertPolicy", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - if polling is True: - polling_method = cast(AsyncPollingMethod, AsyncARMPolling( - lro_delay, - - - **kwargs - )) # type: AsyncPollingMethod - elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: polling_method = polling + polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_create_or_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/securityAlertPolicies/{securityAlertPolicyName}"} # type: ignore + begin_create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/securityAlertPolicies/{securityAlertPolicyName}"} # type: ignore @distributed_trace def list_by_server( - self, - resource_group_name: str, - server_name: str, - **kwargs: Any - ) -> AsyncIterable[_models.ServerSecurityAlertPolicyListResult]: + self, resource_group_name: str, server_name: str, **kwargs: Any + ) -> AsyncIterable["_models.ServerSecurityAlertPolicy"]: """Get the server's threat detection policies. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ServerSecurityAlertPolicyListResult or the result - of cls(response) + :return: An iterator like instance of either ServerSecurityAlertPolicy or the result of + cls(response) :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql.models.ServerSecurityAlertPolicyListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql.models.ServerSecurityAlertPolicy] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.ServerSecurityAlertPolicyListResult] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ServerSecurityAlertPolicyListResult] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_server_request( resource_group_name=resource_group_name, server_name=server_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_server.metadata['url'], + template_url=self.list_by_server.metadata["url"], headers=_headers, params=_params, ) @@ -316,16 +408,7 @@ def prepare_request(next_link=None): request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_by_server_request( - resource_group_name=resource_group_name, - server_name=server_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - template_url=next_link, - headers=_headers, - params=_params, - ) + request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" @@ -341,10 +424,8 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -354,8 +435,6 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list_by_server.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/securityAlertPolicies"} # type: ignore + list_by_server.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/securityAlertPolicies"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_servers_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_servers_operations.py index a582c6d76f9c..f68ce90e687e 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_servers_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_servers_operations.py @@ -6,10 +6,17 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar, Union, cast +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod @@ -22,11 +29,24 @@ from ... import models as _models from ..._vendor import _convert_request -from ...operations._servers_operations import build_create_request_initial, build_delete_request_initial, build_get_request, build_list_by_resource_group_request, build_list_request, build_restart_request_initial, build_start_request_initial, build_stop_request_initial, build_update_request_initial, build_upgrade_request_initial +from ...operations._servers_operations import ( + build_create_request, + build_delete_request, + build_get_request, + build_list_by_resource_group_request, + build_list_request, + build_restart_request, + build_start_request, + build_stop_request, + build_update_request, + build_upgrade_request, +) from .._vendor import MixinABC -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class ServersOperations: """ .. warning:: @@ -46,36 +66,41 @@ def __init__(self, *args, **kwargs) -> None: 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") - async def _create_initial( - self, - resource_group_name: str, - server_name: str, - parameters: _models.ServerForCreate, - **kwargs: Any + self, resource_group_name: str, server_name: str, parameters: Union[_models.ServerForCreate, IO], **kwargs: Any ) -> Optional[_models.Server]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[Optional[_models.Server]] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.Server]] - _json = self._serialize.body(parameters, 'ServerForCreate') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ServerForCreate") - request = build_create_request_initial( - subscription_id=self._config.subscription_id, + request = build_create_request( resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._create_initial.metadata['url'], + content=_content, + template_url=self._create_initial.metadata["url"], headers=_headers, params=_params, ) @@ -83,10 +108,9 @@ async def _create_initial( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 201, 202]: @@ -95,39 +119,110 @@ async def _create_initial( deserialized = None if response.status_code == 200: - deserialized = self._deserialize('Server', pipeline_response) + deserialized = self._deserialize("Server", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('Server', pipeline_response) + deserialized = self._deserialize("Server", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _create_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}"} # type: ignore - + _create_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}"} # type: ignore - @distributed_trace_async + @overload async def begin_create( self, resource_group_name: str, server_name: str, parameters: _models.ServerForCreate, + *, + content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.Server]: """Creates a new server or updates an existing server. The update action will overwrite the existing server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param parameters: The required parameters for creating or updating a server. + :param parameters: The required parameters for creating or updating a server. Required. :type parameters: ~azure.mgmt.rdbms.mysql.models.ServerForCreate - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :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 Server or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql.models.Server] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create( + self, + resource_group_name: str, + server_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.Server]: + """Creates a new server or updates an existing server. The update action will overwrite the + existing server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param parameters: The required parameters for creating or updating a server. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :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 Server or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql.models.Server] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create( + self, resource_group_name: str, server_name: str, parameters: Union[_models.ServerForCreate, IO], **kwargs: Any + ) -> AsyncLROPoller[_models.Server]: + """Creates a new server or updates an existing server. The update action will overwrite the + existing server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param parameters: The required parameters for creating or updating a server. Is either a model + type or a IO type. Required. + :type parameters: ~azure.mgmt.rdbms.mysql.models.ServerForCreate or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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 @@ -139,20 +234,17 @@ async def begin_create( :return: An instance of AsyncLROPoller that returns either Server or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql.models.Server] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[_models.Server] - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Server] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = await self._create_initial( # type: ignore resource_group_name=resource_group_name, @@ -160,69 +252,75 @@ async def begin_create( parameters=parameters, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize('Server', pipeline_response) + deserialized = self._deserialize("Server", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - if polling is True: - polling_method = cast(AsyncPollingMethod, AsyncARMPolling( - lro_delay, - - - **kwargs - )) # type: AsyncPollingMethod - elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: polling_method = polling + polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_create.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}"} # type: ignore + begin_create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}"} # type: ignore async def _update_initial( self, resource_group_name: str, server_name: str, - parameters: _models.ServerUpdateParameters, + parameters: Union[_models.ServerUpdateParameters, IO], **kwargs: Any ) -> Optional[_models.Server]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[Optional[_models.Server]] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.Server]] - _json = self._serialize.body(parameters, 'ServerUpdateParameters') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ServerUpdateParameters") - request = build_update_request_initial( - subscription_id=self._config.subscription_id, + request = build_update_request( resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._update_initial.metadata['url'], + content=_content, + template_url=self._update_initial.metadata["url"], headers=_headers, params=_params, ) @@ -230,10 +328,9 @@ async def _update_initial( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202]: @@ -242,36 +339,38 @@ async def _update_initial( deserialized = None if response.status_code == 200: - deserialized = self._deserialize('Server', pipeline_response) + deserialized = self._deserialize("Server", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}"} # type: ignore - + _update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}"} # type: ignore - @distributed_trace_async + @overload async def begin_update( self, resource_group_name: str, server_name: str, parameters: _models.ServerUpdateParameters, + *, + content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.Server]: """Updates an existing server. The request body can contain one to many of the properties present in the normal server definition. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param parameters: The required parameters for updating a server. + :param parameters: The required parameters for updating a server. Required. :type parameters: ~azure.mgmt.rdbms.mysql.models.ServerUpdateParameters - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :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 @@ -283,20 +382,90 @@ async def begin_update( :return: An instance of AsyncLROPoller that returns either Server or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql.models.Server] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_update( + self, + resource_group_name: str, + server_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.Server]: + """Updates an existing server. The request body can contain one to many of the properties present + in the normal server definition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param parameters: The required parameters for updating a server. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :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 Server or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql.models.Server] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_update( + self, + resource_group_name: str, + server_name: str, + parameters: Union[_models.ServerUpdateParameters, IO], + **kwargs: Any + ) -> AsyncLROPoller[_models.Server]: + """Updates an existing server. The request body can contain one to many of the properties present + in the normal server definition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param parameters: The required parameters for updating a server. Is either a model type or a + IO type. Required. + :type parameters: ~azure.mgmt.rdbms.mysql.models.ServerUpdateParameters or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either Server or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql.models.Server] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[_models.Server] - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Server] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = await self._update_initial( # type: ignore resource_group_name=resource_group_name, @@ -304,64 +473,59 @@ async def begin_update( parameters=parameters, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize('Server', pipeline_response) + deserialized = self._deserialize("Server", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - if polling is True: - polling_method = cast(AsyncPollingMethod, AsyncARMPolling( - lro_delay, - - - **kwargs - )) # type: AsyncPollingMethod - elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: polling_method = polling + polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}"} # type: ignore + begin_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}"} # type: ignore async def _delete_initial( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - server_name: str, - **kwargs: Any + self, resource_group_name: str, server_name: str, **kwargs: Any ) -> None: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] - - request = build_delete_request_initial( - subscription_id=self._config.subscription_id, + request = build_delete_request( resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._delete_initial.metadata['url'], + template_url=self._delete_initial.metadata["url"], headers=_headers, params=_params, ) @@ -369,10 +533,9 @@ async def _delete_initial( # pylint: disable=inconsistent-return-statements request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: @@ -382,25 +545,17 @@ async def _delete_initial( # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - _delete_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}"} # type: ignore - + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}"} # type: ignore @distributed_trace_async - async def begin_delete( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - server_name: str, - **kwargs: Any - ) -> AsyncLROPoller[None]: + async def begin_delete(self, resource_group_name: str, server_name: str, **kwargs: Any) -> AsyncLROPoller[None]: """Deletes a server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function 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 @@ -411,95 +566,83 @@ async def begin_delete( # pylint: disable=inconsistent-return-statements Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = await self._delete_initial( # type: ignore resource_group_name=resource_group_name, server_name=server_name, api_version=api_version, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - if polling is True: - polling_method = cast(AsyncPollingMethod, AsyncARMPolling( - lro_delay, - - - **kwargs - )) # type: AsyncPollingMethod - elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: polling_method = polling + polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_delete.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}"} # type: ignore + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}"} # type: ignore @distributed_trace_async - async def get( - self, - resource_group_name: str, - server_name: str, - **kwargs: Any - ) -> _models.Server: + async def get(self, resource_group_name: str, server_name: str, **kwargs: Any) -> _models.Server: """Gets information about a server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Server, or the result of cls(response) + :return: Server or the result of cls(response) :rtype: ~azure.mgmt.rdbms.mysql.models.Server - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.Server] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.Server] - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], headers=_headers, params=_params, ) @@ -507,63 +650,58 @@ async def get( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('Server', pipeline_response) + deserialized = self._deserialize("Server", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}"} # type: ignore @distributed_trace - def list_by_resource_group( - self, - resource_group_name: str, - **kwargs: Any - ) -> AsyncIterable[_models.ServerListResult]: + def list_by_resource_group(self, resource_group_name: str, **kwargs: Any) -> AsyncIterable["_models.Server"]: """List all the servers in a given resource group. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ServerListResult or the result of cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql.models.ServerListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Server or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql.models.Server] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.ServerListResult] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ServerListResult] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_resource_group_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata['url'], + template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) @@ -571,15 +709,7 @@ def prepare_request(next_link=None): request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_by_resource_group_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - api_version=api_version, - template_url=next_link, - headers=_headers, - params=_params, - ) + request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" @@ -595,10 +725,8 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -608,45 +736,40 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list_by_resource_group.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers"} # type: ignore + list_by_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers"} # type: ignore @distributed_trace - def list( - self, - **kwargs: Any - ) -> AsyncIterable[_models.ServerListResult]: + def list(self, **kwargs: Any) -> AsyncIterable["_models.Server"]: """List all the servers in a given subscription. - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ServerListResult or the result of cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql.models.ServerListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Server or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql.models.Server] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.ServerListResult] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ServerListResult] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list.metadata['url'], + template_url=self.list.metadata["url"], headers=_headers, params=_params, ) @@ -654,14 +777,7 @@ def prepare_request(next_link=None): request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_request( - subscription_id=self._config.subscription_id, - api_version=api_version, - template_url=next_link, - headers=_headers, - params=_params, - ) + request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" @@ -677,10 +793,8 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -690,36 +804,33 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/servers"} # type: ignore + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/servers"} # type: ignore async def _restart_initial( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - server_name: str, - **kwargs: Any + self, resource_group_name: str, server_name: str, **kwargs: Any ) -> None: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] - - request = build_restart_request_initial( - subscription_id=self._config.subscription_id, + request = build_restart_request( resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._restart_initial.metadata['url'], + template_url=self._restart_initial.metadata["url"], headers=_headers, params=_params, ) @@ -727,10 +838,9 @@ async def _restart_initial( # pylint: disable=inconsistent-return-statements request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202]: @@ -740,25 +850,17 @@ async def _restart_initial( # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - _restart_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/restart"} # type: ignore - + _restart_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/restart"} # type: ignore @distributed_trace_async - async def begin_restart( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - server_name: str, - **kwargs: Any - ) -> AsyncLROPoller[None]: + async def begin_restart(self, resource_group_name: str, server_name: str, **kwargs: Any) -> AsyncLROPoller[None]: """Restarts a server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function 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 @@ -769,80 +871,72 @@ async def begin_restart( # pylint: disable=inconsistent-return-statements Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = await self._restart_initial( # type: ignore resource_group_name=resource_group_name, server_name=server_name, api_version=api_version, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - if polling is True: - polling_method = cast(AsyncPollingMethod, AsyncARMPolling( - lro_delay, - - - **kwargs - )) # type: AsyncPollingMethod - elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: polling_method = polling + polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_restart.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/restart"} # type: ignore + begin_restart.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/restart"} # type: ignore async def _start_initial( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - server_name: str, - **kwargs: Any + self, resource_group_name: str, server_name: str, **kwargs: Any ) -> None: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2020-01-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-01-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] - - request = build_start_request_initial( - subscription_id=self._config.subscription_id, + request = build_start_request( resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._start_initial.metadata['url'], + template_url=self._start_initial.metadata["url"], headers=_headers, params=_params, ) @@ -850,38 +944,30 @@ async def _start_initial( # pylint: disable=inconsistent-return-statements request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.CloudErrorAutoGenerated, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - _start_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/start"} # type: ignore - + _start_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/start"} # type: ignore @distributed_trace_async - async def begin_start( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - server_name: str, - **kwargs: Any - ) -> AsyncLROPoller[None]: + async def begin_start(self, resource_group_name: str, server_name: str, **kwargs: Any) -> AsyncLROPoller[None]: """Starts a stopped server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :keyword api_version: Api Version. Default value is "2020-01-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function 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 @@ -892,80 +978,72 @@ async def begin_start( # pylint: disable=inconsistent-return-statements Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2020-01-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-01-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = await self._start_initial( # type: ignore resource_group_name=resource_group_name, server_name=server_name, api_version=api_version, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - if polling is True: - polling_method = cast(AsyncPollingMethod, AsyncARMPolling( - lro_delay, - - - **kwargs - )) # type: AsyncPollingMethod - elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: polling_method = polling + polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_start.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/start"} # type: ignore + begin_start.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/start"} # type: ignore async def _stop_initial( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - server_name: str, - **kwargs: Any + self, resource_group_name: str, server_name: str, **kwargs: Any ) -> None: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2020-01-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-01-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] - - request = build_stop_request_initial( - subscription_id=self._config.subscription_id, + request = build_stop_request( resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._stop_initial.metadata['url'], + template_url=self._stop_initial.metadata["url"], headers=_headers, params=_params, ) @@ -973,38 +1051,30 @@ async def _stop_initial( # pylint: disable=inconsistent-return-statements request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.CloudErrorAutoGenerated, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - _stop_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/stop"} # type: ignore - + _stop_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/stop"} # type: ignore @distributed_trace_async - async def begin_stop( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - server_name: str, - **kwargs: Any - ) -> AsyncLROPoller[None]: + async def begin_stop(self, resource_group_name: str, server_name: str, **kwargs: Any) -> AsyncLROPoller[None]: """Stops a running server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :keyword api_version: Api Version. Default value is "2020-01-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function 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 @@ -1015,85 +1085,88 @@ async def begin_stop( # pylint: disable=inconsistent-return-statements Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2020-01-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-01-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = await self._stop_initial( # type: ignore resource_group_name=resource_group_name, server_name=server_name, api_version=api_version, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - if polling is True: - polling_method = cast(AsyncPollingMethod, AsyncARMPolling( - lro_delay, - - - **kwargs - )) # type: AsyncPollingMethod - elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: polling_method = polling + polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_stop.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/stop"} # type: ignore + begin_stop.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/stop"} # type: ignore async def _upgrade_initial( # pylint: disable=inconsistent-return-statements self, resource_group_name: str, server_name: str, - parameters: _models.ServerUpgradeParameters, + parameters: Union[_models.ServerUpgradeParameters, IO], **kwargs: Any ) -> None: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2020-01-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[None] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-01-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[None] - _json = self._serialize.body(parameters, 'ServerUpgradeParameters') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ServerUpgradeParameters") - request = build_upgrade_request_initial( - subscription_id=self._config.subscription_id, + request = build_upgrade_request( resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._upgrade_initial.metadata['url'], + content=_content, + template_url=self._upgrade_initial.metadata["url"], headers=_headers, params=_params, ) @@ -1101,41 +1174,43 @@ async def _upgrade_initial( # pylint: disable=inconsistent-return-statements request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.CloudErrorAutoGenerated, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - _upgrade_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/upgrade"} # type: ignore - + _upgrade_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/upgrade"} # type: ignore - @distributed_trace_async - async def begin_upgrade( # pylint: disable=inconsistent-return-statements + @overload + async def begin_upgrade( self, resource_group_name: str, server_name: str, parameters: _models.ServerUpgradeParameters, + *, + content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[None]: """Upgrade server version. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param parameters: The required parameters for updating a server. + :param parameters: The required parameters for updating a server. Required. :type parameters: ~azure.mgmt.rdbms.mysql.models.ServerUpgradeParameters - :keyword api_version: Api Version. Default value is "2020-01-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :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 @@ -1146,20 +1221,86 @@ async def begin_upgrade( # pylint: disable=inconsistent-return-statements Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_upgrade( + self, + resource_group_name: str, + server_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Upgrade server version. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param parameters: The required parameters for updating a server. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :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: + """ + + @distributed_trace_async + async def begin_upgrade( + self, + resource_group_name: str, + server_name: str, + parameters: Union[_models.ServerUpgradeParameters, IO], + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Upgrade server version. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param parameters: The required parameters for updating a server. Is either a model type or a + IO type. Required. + :type parameters: ~azure.mgmt.rdbms.mysql.models.ServerUpgradeParameters or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2020-01-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[None] - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-01-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = await self._upgrade_initial( # type: ignore resource_group_name=resource_group_name, @@ -1167,34 +1308,30 @@ async def begin_upgrade( # pylint: disable=inconsistent-return-statements parameters=parameters, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - if polling is True: - polling_method = cast(AsyncPollingMethod, AsyncARMPolling( - lro_delay, - - - **kwargs - )) # type: AsyncPollingMethod - elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: polling_method = polling + polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_upgrade.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/upgrade"} # type: ignore + begin_upgrade.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/upgrade"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_top_query_statistics_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_top_query_statistics_operations.py index 2566b15d66b5..605e21ee6aa1 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_top_query_statistics_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_top_query_statistics_operations.py @@ -6,10 +6,17 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest @@ -22,9 +29,11 @@ from ..._vendor import _convert_request from ...operations._top_query_statistics_operations import build_get_request, build_list_by_server_request from .._vendor import MixinABC -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class TopQueryStatisticsOperations: """ .. warning:: @@ -44,50 +53,45 @@ def __init__(self, *args, **kwargs) -> None: self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace_async async def get( - self, - resource_group_name: str, - server_name: str, - query_statistic_id: str, - **kwargs: Any + self, resource_group_name: str, server_name: str, query_statistic_id: str, **kwargs: Any ) -> _models.QueryStatistic: """Retrieve the query statistic for specified identifier. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param query_statistic_id: The Query Statistic identifier. + :param query_statistic_id: The Query Statistic identifier. Required. :type query_statistic_id: str - :keyword api_version: Api Version. Default value is "2018-06-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: QueryStatistic, or the result of cls(response) + :return: QueryStatistic or the result of cls(response) :rtype: ~azure.mgmt.rdbms.mysql.models.QueryStatistic - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.QueryStatistic] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.QueryStatistic] - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, query_statistic_id=query_statistic_id, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], headers=_headers, params=_params, ) @@ -95,75 +99,140 @@ async def get( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('QueryStatistic', pipeline_response) + deserialized = self._deserialize("QueryStatistic", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/topQueryStatistics/{queryStatisticId}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/topQueryStatistics/{queryStatisticId}"} # type: ignore - @distributed_trace + @overload def list_by_server( self, resource_group_name: str, server_name: str, parameters: _models.TopQueryStatisticsInput, + *, + content_type: str = "application/json", **kwargs: Any - ) -> AsyncIterable[_models.TopQueryStatisticsResultList]: + ) -> AsyncIterable["_models.QueryStatistic"]: """Retrieve the Query-Store top queries for specified metric and aggregation. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param parameters: The required parameters for retrieving top query statistics. + :param parameters: The required parameters for retrieving top query statistics. Required. :type parameters: ~azure.mgmt.rdbms.mysql.models.TopQueryStatisticsInput - :keyword api_version: Api Version. Default value is "2018-06-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either QueryStatistic or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql.models.QueryStatistic] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def list_by_server( + self, + resource_group_name: str, + server_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncIterable["_models.QueryStatistic"]: + """Retrieve the Query-Store top queries for specified metric and aggregation. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param parameters: The required parameters for retrieving top query statistics. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either QueryStatistic or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql.models.QueryStatistic] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def list_by_server( + self, + resource_group_name: str, + server_name: str, + parameters: Union[_models.TopQueryStatisticsInput, IO], + **kwargs: Any + ) -> AsyncIterable["_models.QueryStatistic"]: + """Retrieve the Query-Store top queries for specified metric and aggregation. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param parameters: The required parameters for retrieving top query statistics. Is either a + model type or a IO type. Required. + :type parameters: ~azure.mgmt.rdbms.mysql.models.TopQueryStatisticsInput or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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: An iterator like instance of either TopQueryStatisticsResultList or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql.models.TopQueryStatisticsResultList] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either QueryStatistic or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql.models.QueryStatistic] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[_models.TopQueryStatisticsResultList] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.TopQueryStatisticsResultList] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "TopQueryStatisticsInput") + def prepare_request(next_link=None): if not next_link: - _json = self._serialize.body(parameters, 'TopQueryStatisticsInput') - + request = build_list_by_server_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self.list_by_server.metadata['url'], + content=_content, + template_url=self.list_by_server.metadata["url"], headers=_headers, params=_params, ) @@ -171,19 +240,7 @@ def prepare_request(next_link=None): request.url = self._client.format_url(request.url) # type: ignore else: - _json = self._serialize.body(parameters, 'TopQueryStatisticsInput') - - request = build_list_by_server_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - server_name=server_name, - api_version=api_version, - content_type=content_type, - json=_json, - template_url=next_link, - headers=_headers, - params=_params, - ) + request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" @@ -199,10 +256,8 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -212,8 +267,6 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list_by_server.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/topQueryStatistics"} # type: ignore + list_by_server.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/topQueryStatistics"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_virtual_network_rules_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_virtual_network_rules_operations.py index 16f417299a37..79aac939b573 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_virtual_network_rules_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_virtual_network_rules_operations.py @@ -6,10 +6,17 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar, Union, cast +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod @@ -22,11 +29,18 @@ from ... import models as _models from ..._vendor import _convert_request -from ...operations._virtual_network_rules_operations import build_create_or_update_request_initial, build_delete_request_initial, build_get_request, build_list_by_server_request +from ...operations._virtual_network_rules_operations import ( + build_create_or_update_request, + build_delete_request, + build_get_request, + build_list_by_server_request, +) from .._vendor import MixinABC -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class VirtualNetworkRulesOperations: """ .. warning:: @@ -46,50 +60,45 @@ def __init__(self, *args, **kwargs) -> None: self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace_async async def get( - self, - resource_group_name: str, - server_name: str, - virtual_network_rule_name: str, - **kwargs: Any + self, resource_group_name: str, server_name: str, virtual_network_rule_name: str, **kwargs: Any ) -> _models.VirtualNetworkRule: """Gets a virtual network rule. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param virtual_network_rule_name: The name of the virtual network rule. + :param virtual_network_rule_name: The name of the virtual network rule. Required. :type virtual_network_rule_name: str - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: VirtualNetworkRule, or the result of cls(response) + :return: VirtualNetworkRule or the result of cls(response) :rtype: ~azure.mgmt.rdbms.mysql.models.VirtualNetworkRule - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.VirtualNetworkRule] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.VirtualNetworkRule] - request = build_get_request( resource_group_name=resource_group_name, server_name=server_name, - subscription_id=self._config.subscription_id, virtual_network_rule_name=virtual_network_rule_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], headers=_headers, params=_params, ) @@ -97,57 +106,65 @@ async def get( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('VirtualNetworkRule', pipeline_response) + deserialized = self._deserialize("VirtualNetworkRule", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}"} # type: ignore async def _create_or_update_initial( self, resource_group_name: str, server_name: str, virtual_network_rule_name: str, - parameters: _models.VirtualNetworkRule, + parameters: Union[_models.VirtualNetworkRule, IO], **kwargs: Any ) -> Optional[_models.VirtualNetworkRule]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[Optional[_models.VirtualNetworkRule]] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.VirtualNetworkRule]] - _json = self._serialize.body(parameters, 'VirtualNetworkRule') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "VirtualNetworkRule") - request = build_create_or_update_request_initial( + request = build_create_or_update_request( resource_group_name=resource_group_name, server_name=server_name, - subscription_id=self._config.subscription_id, virtual_network_rule_name=virtual_network_rule_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._create_or_update_initial.metadata['url'], + content=_content, + template_url=self._create_or_update_initial.metadata["url"], headers=_headers, params=_params, ) @@ -155,10 +172,9 @@ async def _create_or_update_initial( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 201, 202]: @@ -167,41 +183,82 @@ async def _create_or_update_initial( deserialized = None if response.status_code == 200: - deserialized = self._deserialize('VirtualNetworkRule', pipeline_response) + deserialized = self._deserialize("VirtualNetworkRule", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('VirtualNetworkRule', pipeline_response) + deserialized = self._deserialize("VirtualNetworkRule", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _create_or_update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}"} # type: ignore + _create_or_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}"} # type: ignore - - @distributed_trace_async + @overload async def begin_create_or_update( self, resource_group_name: str, server_name: str, virtual_network_rule_name: str, parameters: _models.VirtualNetworkRule, + *, + content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.VirtualNetworkRule]: """Creates or updates an existing virtual network rule. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param virtual_network_rule_name: The name of the virtual network rule. + :param virtual_network_rule_name: The name of the virtual network rule. Required. :type virtual_network_rule_name: str - :param parameters: The requested virtual Network Rule Resource state. + :param parameters: The requested virtual Network Rule Resource state. Required. :type parameters: ~azure.mgmt.rdbms.mysql.models.VirtualNetworkRule - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :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 VirtualNetworkRule or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql.models.VirtualNetworkRule] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + virtual_network_rule_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.VirtualNetworkRule]: + """Creates or updates an existing virtual network rule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param virtual_network_rule_name: The name of the virtual network rule. Required. + :type virtual_network_rule_name: str + :param parameters: The requested virtual Network Rule Resource state. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :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 @@ -213,20 +270,55 @@ async def begin_create_or_update( :return: An instance of AsyncLROPoller that returns either VirtualNetworkRule or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql.models.VirtualNetworkRule] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + virtual_network_rule_name: str, + parameters: Union[_models.VirtualNetworkRule, IO], + **kwargs: Any + ) -> AsyncLROPoller[_models.VirtualNetworkRule]: + """Creates or updates an existing virtual network rule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param virtual_network_rule_name: The name of the virtual network rule. Required. + :type virtual_network_rule_name: str + :param parameters: The requested virtual Network Rule Resource state. Is either a model type or + a IO type. Required. + :type parameters: ~azure.mgmt.rdbms.mysql.models.VirtualNetworkRule or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either VirtualNetworkRule or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql.models.VirtualNetworkRule] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[_models.VirtualNetworkRule] - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.VirtualNetworkRule] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = await self._create_or_update_initial( # type: ignore resource_group_name=resource_group_name, @@ -235,66 +327,60 @@ async def begin_create_or_update( parameters=parameters, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize('VirtualNetworkRule', pipeline_response) + deserialized = self._deserialize("VirtualNetworkRule", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - if polling is True: - polling_method = cast(AsyncPollingMethod, AsyncARMPolling( - lro_delay, - - - **kwargs - )) # type: AsyncPollingMethod - elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: polling_method = polling + polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_create_or_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}"} # type: ignore + begin_create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}"} # type: ignore async def _delete_initial( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - server_name: str, - virtual_network_rule_name: str, - **kwargs: Any + self, resource_group_name: str, server_name: str, virtual_network_rule_name: str, **kwargs: Any ) -> None: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] - - request = build_delete_request_initial( + request = build_delete_request( resource_group_name=resource_group_name, server_name=server_name, virtual_network_rule_name=virtual_network_rule_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._delete_initial.metadata['url'], + template_url=self._delete_initial.metadata["url"], headers=_headers, params=_params, ) @@ -302,10 +388,9 @@ async def _delete_initial( # pylint: disable=inconsistent-return-statements request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: @@ -315,28 +400,21 @@ async def _delete_initial( # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - _delete_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}"} # type: ignore - + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}"} # type: ignore @distributed_trace_async - async def begin_delete( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - server_name: str, - virtual_network_rule_name: str, - **kwargs: Any + async def begin_delete( + self, resource_group_name: str, server_name: str, virtual_network_rule_name: str, **kwargs: Any ) -> AsyncLROPoller[None]: """Deletes the virtual network rule with the given name. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param virtual_network_rule_name: The name of the virtual network rule. + :param virtual_network_rule_name: The name of the virtual network rule. Required. :type virtual_network_rule_name: str - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function 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 @@ -347,99 +425,90 @@ async def begin_delete( # pylint: disable=inconsistent-return-statements Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = await self._delete_initial( # type: ignore resource_group_name=resource_group_name, server_name=server_name, virtual_network_rule_name=virtual_network_rule_name, api_version=api_version, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - if polling is True: - polling_method = cast(AsyncPollingMethod, AsyncARMPolling( - lro_delay, - - - **kwargs - )) # type: AsyncPollingMethod - elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: polling_method = polling + polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_delete.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}"} # type: ignore + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}"} # type: ignore @distributed_trace def list_by_server( - self, - resource_group_name: str, - server_name: str, - **kwargs: Any - ) -> AsyncIterable[_models.VirtualNetworkRuleListResult]: + self, resource_group_name: str, server_name: str, **kwargs: Any + ) -> AsyncIterable["_models.VirtualNetworkRule"]: """Gets a list of virtual network rules in a server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either VirtualNetworkRuleListResult or the result of - cls(response) + :return: An iterator like instance of either VirtualNetworkRule or the result of cls(response) :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql.models.VirtualNetworkRuleListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql.models.VirtualNetworkRule] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.VirtualNetworkRuleListResult] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.VirtualNetworkRuleListResult] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_server_request( resource_group_name=resource_group_name, server_name=server_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_server.metadata['url'], + template_url=self.list_by_server.metadata["url"], headers=_headers, params=_params, ) @@ -447,16 +516,7 @@ def prepare_request(next_link=None): request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_by_server_request( - resource_group_name=resource_group_name, - server_name=server_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - template_url=next_link, - headers=_headers, - params=_params, - ) + request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" @@ -472,10 +532,8 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -485,8 +543,6 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list_by_server.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/virtualNetworkRules"} # type: ignore + list_by_server.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/virtualNetworkRules"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_wait_statistics_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_wait_statistics_operations.py index 15ac3b2ca3b1..42e013182c80 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_wait_statistics_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/aio/operations/_wait_statistics_operations.py @@ -6,10 +6,17 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest @@ -22,9 +29,11 @@ from ..._vendor import _convert_request from ...operations._wait_statistics_operations import build_get_request, build_list_by_server_request from .._vendor import MixinABC -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class WaitStatisticsOperations: """ .. warning:: @@ -44,50 +53,45 @@ def __init__(self, *args, **kwargs) -> None: self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace_async async def get( - self, - resource_group_name: str, - server_name: str, - wait_statistics_id: str, - **kwargs: Any + self, resource_group_name: str, server_name: str, wait_statistics_id: str, **kwargs: Any ) -> _models.WaitStatistic: """Retrieve wait statistics for specified identifier. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param wait_statistics_id: The Wait Statistic identifier. + :param wait_statistics_id: The Wait Statistic identifier. Required. :type wait_statistics_id: str - :keyword api_version: Api Version. Default value is "2018-06-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: WaitStatistic, or the result of cls(response) + :return: WaitStatistic or the result of cls(response) :rtype: ~azure.mgmt.rdbms.mysql.models.WaitStatistic - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.WaitStatistic] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.WaitStatistic] - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, wait_statistics_id=wait_statistics_id, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], headers=_headers, params=_params, ) @@ -95,75 +99,140 @@ async def get( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('WaitStatistic', pipeline_response) + deserialized = self._deserialize("WaitStatistic", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/waitStatistics/{waitStatisticsId}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/waitStatistics/{waitStatisticsId}"} # type: ignore - @distributed_trace + @overload def list_by_server( self, resource_group_name: str, server_name: str, parameters: _models.WaitStatisticsInput, + *, + content_type: str = "application/json", **kwargs: Any - ) -> AsyncIterable[_models.WaitStatisticsResultList]: + ) -> AsyncIterable["_models.WaitStatistic"]: """Retrieve wait statistics for specified aggregation window. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param parameters: The required parameters for retrieving wait statistics. + :param parameters: The required parameters for retrieving wait statistics. Required. :type parameters: ~azure.mgmt.rdbms.mysql.models.WaitStatisticsInput - :keyword api_version: Api Version. Default value is "2018-06-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either WaitStatistic or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql.models.WaitStatistic] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def list_by_server( + self, + resource_group_name: str, + server_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncIterable["_models.WaitStatistic"]: + """Retrieve wait statistics for specified aggregation window. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param parameters: The required parameters for retrieving wait statistics. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either WaitStatistic or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql.models.WaitStatistic] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def list_by_server( + self, + resource_group_name: str, + server_name: str, + parameters: Union[_models.WaitStatisticsInput, IO], + **kwargs: Any + ) -> AsyncIterable["_models.WaitStatistic"]: + """Retrieve wait statistics for specified aggregation window. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param parameters: The required parameters for retrieving wait statistics. Is either a model + type or a IO type. Required. + :type parameters: ~azure.mgmt.rdbms.mysql.models.WaitStatisticsInput or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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: An iterator like instance of either WaitStatisticsResultList or the result of - cls(response) - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql.models.WaitStatisticsResultList] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either WaitStatistic or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql.models.WaitStatistic] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[_models.WaitStatisticsResultList] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.WaitStatisticsResultList] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "WaitStatisticsInput") + def prepare_request(next_link=None): if not next_link: - _json = self._serialize.body(parameters, 'WaitStatisticsInput') - + request = build_list_by_server_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self.list_by_server.metadata['url'], + content=_content, + template_url=self.list_by_server.metadata["url"], headers=_headers, params=_params, ) @@ -171,19 +240,7 @@ def prepare_request(next_link=None): request.url = self._client.format_url(request.url) # type: ignore else: - _json = self._serialize.body(parameters, 'WaitStatisticsInput') - - request = build_list_by_server_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - server_name=server_name, - api_version=api_version, - content_type=content_type, - json=_json, - template_url=next_link, - headers=_headers, - params=_params, - ) + request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" @@ -199,10 +256,8 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -212,8 +267,6 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list_by_server.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/waitStatistics"} # type: ignore + list_by_server.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/waitStatistics"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/models/__init__.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/models/__init__.py index ffc391b8797d..fffdfd77bc01 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/models/__init__.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/models/__init__.py @@ -76,122 +76,120 @@ from ._models_py3 import WaitStatisticsInput from ._models_py3 import WaitStatisticsResultList - -from ._my_sql_management_client_enums import ( - CreateMode, - GeoRedundantBackup, - IdentityType, - InfrastructureEncryption, - MinimalTlsVersionEnum, - OperationOrigin, - PrivateEndpointProvisioningState, - PrivateLinkServiceConnectionStateActionsRequire, - PrivateLinkServiceConnectionStateStatus, - PublicNetworkAccessEnum, - QueryPerformanceInsightResetDataResultState, - SecurityAlertPolicyName, - ServerKeyType, - ServerSecurityAlertPolicyState, - ServerState, - ServerVersion, - SkuTier, - SslEnforcementEnum, - StorageAutogrow, - VirtualNetworkRuleState, -) +from ._my_sql_management_client_enums import CreateMode +from ._my_sql_management_client_enums import GeoRedundantBackup +from ._my_sql_management_client_enums import IdentityType +from ._my_sql_management_client_enums import InfrastructureEncryption +from ._my_sql_management_client_enums import MinimalTlsVersionEnum +from ._my_sql_management_client_enums import OperationOrigin +from ._my_sql_management_client_enums import PrivateEndpointProvisioningState +from ._my_sql_management_client_enums import PrivateLinkServiceConnectionStateActionsRequire +from ._my_sql_management_client_enums import PrivateLinkServiceConnectionStateStatus +from ._my_sql_management_client_enums import PublicNetworkAccessEnum +from ._my_sql_management_client_enums import QueryPerformanceInsightResetDataResultState +from ._my_sql_management_client_enums import SecurityAlertPolicyName +from ._my_sql_management_client_enums import ServerKeyType +from ._my_sql_management_client_enums import ServerSecurityAlertPolicyState +from ._my_sql_management_client_enums import ServerState +from ._my_sql_management_client_enums import ServerVersion +from ._my_sql_management_client_enums import SkuTier +from ._my_sql_management_client_enums import SslEnforcementEnum +from ._my_sql_management_client_enums import StorageAutogrow +from ._my_sql_management_client_enums import VirtualNetworkRuleState from ._patch import __all__ as _patch_all from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import from ._patch import patch_sdk as _patch_sdk + __all__ = [ - 'Advisor', - 'AdvisorsResultList', - 'CloudErrorAutoGenerated', - 'Configuration', - 'ConfigurationListResult', - 'Database', - 'DatabaseListResult', - 'ErrorAdditionalInfo', - 'ErrorResponse', - 'FirewallRule', - 'FirewallRuleListResult', - 'LogFile', - 'LogFileListResult', - 'NameAvailability', - 'NameAvailabilityRequest', - 'Operation', - 'OperationDisplay', - 'OperationListResult', - 'PerformanceTierListResult', - 'PerformanceTierProperties', - 'PerformanceTierServiceLevelObjectives', - 'PrivateEndpointConnection', - 'PrivateEndpointConnectionListResult', - 'PrivateEndpointProperty', - 'PrivateLinkResource', - 'PrivateLinkResourceListResult', - 'PrivateLinkResourceProperties', - 'PrivateLinkServiceConnectionStateProperty', - 'ProxyResource', - 'QueryPerformanceInsightResetDataResult', - 'QueryStatistic', - 'QueryText', - 'QueryTextsResultList', - 'RecommendationAction', - 'RecommendationActionsResultList', - 'RecommendedActionSessionsOperationStatus', - 'RecoverableServerResource', - 'Resource', - 'ResourceIdentity', - 'Server', - 'ServerAdministratorResource', - 'ServerAdministratorResourceListResult', - 'ServerForCreate', - 'ServerKey', - 'ServerKeyListResult', - 'ServerListResult', - 'ServerPrivateEndpointConnection', - 'ServerPrivateEndpointConnectionProperties', - 'ServerPrivateLinkServiceConnectionStateProperty', - 'ServerPropertiesForCreate', - 'ServerPropertiesForDefaultCreate', - 'ServerPropertiesForGeoRestore', - 'ServerPropertiesForReplica', - 'ServerPropertiesForRestore', - 'ServerSecurityAlertPolicy', - 'ServerSecurityAlertPolicyListResult', - 'ServerUpdateParameters', - 'ServerUpgradeParameters', - 'Sku', - 'StorageProfile', - 'TagsObject', - 'TopQueryStatisticsInput', - 'TopQueryStatisticsResultList', - 'TrackedResource', - 'VirtualNetworkRule', - 'VirtualNetworkRuleListResult', - 'WaitStatistic', - 'WaitStatisticsInput', - 'WaitStatisticsResultList', - 'CreateMode', - 'GeoRedundantBackup', - 'IdentityType', - 'InfrastructureEncryption', - 'MinimalTlsVersionEnum', - 'OperationOrigin', - 'PrivateEndpointProvisioningState', - 'PrivateLinkServiceConnectionStateActionsRequire', - 'PrivateLinkServiceConnectionStateStatus', - 'PublicNetworkAccessEnum', - 'QueryPerformanceInsightResetDataResultState', - 'SecurityAlertPolicyName', - 'ServerKeyType', - 'ServerSecurityAlertPolicyState', - 'ServerState', - 'ServerVersion', - 'SkuTier', - 'SslEnforcementEnum', - 'StorageAutogrow', - 'VirtualNetworkRuleState', + "Advisor", + "AdvisorsResultList", + "CloudErrorAutoGenerated", + "Configuration", + "ConfigurationListResult", + "Database", + "DatabaseListResult", + "ErrorAdditionalInfo", + "ErrorResponse", + "FirewallRule", + "FirewallRuleListResult", + "LogFile", + "LogFileListResult", + "NameAvailability", + "NameAvailabilityRequest", + "Operation", + "OperationDisplay", + "OperationListResult", + "PerformanceTierListResult", + "PerformanceTierProperties", + "PerformanceTierServiceLevelObjectives", + "PrivateEndpointConnection", + "PrivateEndpointConnectionListResult", + "PrivateEndpointProperty", + "PrivateLinkResource", + "PrivateLinkResourceListResult", + "PrivateLinkResourceProperties", + "PrivateLinkServiceConnectionStateProperty", + "ProxyResource", + "QueryPerformanceInsightResetDataResult", + "QueryStatistic", + "QueryText", + "QueryTextsResultList", + "RecommendationAction", + "RecommendationActionsResultList", + "RecommendedActionSessionsOperationStatus", + "RecoverableServerResource", + "Resource", + "ResourceIdentity", + "Server", + "ServerAdministratorResource", + "ServerAdministratorResourceListResult", + "ServerForCreate", + "ServerKey", + "ServerKeyListResult", + "ServerListResult", + "ServerPrivateEndpointConnection", + "ServerPrivateEndpointConnectionProperties", + "ServerPrivateLinkServiceConnectionStateProperty", + "ServerPropertiesForCreate", + "ServerPropertiesForDefaultCreate", + "ServerPropertiesForGeoRestore", + "ServerPropertiesForReplica", + "ServerPropertiesForRestore", + "ServerSecurityAlertPolicy", + "ServerSecurityAlertPolicyListResult", + "ServerUpdateParameters", + "ServerUpgradeParameters", + "Sku", + "StorageProfile", + "TagsObject", + "TopQueryStatisticsInput", + "TopQueryStatisticsResultList", + "TrackedResource", + "VirtualNetworkRule", + "VirtualNetworkRuleListResult", + "WaitStatistic", + "WaitStatisticsInput", + "WaitStatisticsResultList", + "CreateMode", + "GeoRedundantBackup", + "IdentityType", + "InfrastructureEncryption", + "MinimalTlsVersionEnum", + "OperationOrigin", + "PrivateEndpointProvisioningState", + "PrivateLinkServiceConnectionStateActionsRequire", + "PrivateLinkServiceConnectionStateStatus", + "PublicNetworkAccessEnum", + "QueryPerformanceInsightResetDataResultState", + "SecurityAlertPolicyName", + "ServerKeyType", + "ServerSecurityAlertPolicyState", + "ServerState", + "ServerVersion", + "SkuTier", + "SslEnforcementEnum", + "StorageAutogrow", + "VirtualNetworkRuleState", ] __all__.extend([p for p in _patch_all if p not in __all__]) -_patch_sdk() \ No newline at end of file +_patch_sdk() diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/models/_models_py3.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/models/_models_py3.py index d71696722d0e..58462e660a7a 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/models/_models_py3.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/models/_models_py3.py @@ -1,4 +1,5 @@ # coding=utf-8 +# pylint: disable=too-many-lines # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. @@ -7,17 +8,22 @@ # -------------------------------------------------------------------------- import datetime +import sys from typing import Any, Dict, List, Optional, TYPE_CHECKING, Union -from azure.core.exceptions import HttpResponseError -import msrest.serialization +from .. import _serialization if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports - import __init__ as _models + from .. import models as _models +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object -class Resource(msrest.serialization.Model): +class Resource(_serialization.Model): """Common fields that are returned in the response for all Azure Resource Manager resources. Variables are only populated by the server, and will be ignored when sending a request. @@ -33,24 +39,20 @@ class Resource(msrest.serialization.Model): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(Resource, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.id = None self.name = None self.type = None @@ -72,24 +74,20 @@ class ProxyResource(Resource): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(ProxyResource, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) class Advisor(ProxyResource): @@ -106,37 +104,32 @@ class Advisor(ProxyResource): "Microsoft.Storage/storageAccounts". :vartype type: str :ivar properties: The properties of a recommendation action advisor. - :vartype properties: any + :vartype properties: JSON """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'properties': {'key': 'properties', 'type': 'object'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "properties": {"key": "properties", "type": "object"}, } - def __init__( - self, - *, - properties: Optional[Any] = None, - **kwargs - ): + def __init__(self, *, properties: Optional[JSON] = None, **kwargs): """ :keyword properties: The properties of a recommendation action advisor. - :paramtype properties: any + :paramtype properties: JSON """ - super(Advisor, self).__init__(**kwargs) + super().__init__(**kwargs) self.properties = properties -class AdvisorsResultList(msrest.serialization.Model): +class AdvisorsResultList(_serialization.Model): """A list of query statistics. Variables are only populated by the server, and will be ignored when sending a request. @@ -148,27 +141,23 @@ class AdvisorsResultList(msrest.serialization.Model): """ _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, + "value": {"readonly": True}, + "next_link": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[Advisor]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[Advisor]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(AdvisorsResultList, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.value = None self.next_link = None -class CloudErrorAutoGenerated(msrest.serialization.Model): +class CloudErrorAutoGenerated(_serialization.Model): """An error response from the Batch service. :ivar error: Error message. @@ -176,20 +165,15 @@ class CloudErrorAutoGenerated(msrest.serialization.Model): """ _attribute_map = { - 'error': {'key': 'error', 'type': 'ErrorResponse'}, + "error": {"key": "error", "type": "ErrorResponse"}, } - def __init__( - self, - *, - error: Optional["_models.ErrorResponse"] = None, - **kwargs - ): + def __init__(self, *, error: Optional["_models.ErrorResponse"] = None, **kwargs): """ :keyword error: Error message. :paramtype error: ~azure.mgmt.rdbms.mysql.models.ErrorResponse """ - super(CloudErrorAutoGenerated, self).__init__(**kwargs) + super().__init__(**kwargs) self.error = error @@ -221,41 +205,35 @@ class Configuration(ProxyResource): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'description': {'readonly': True}, - 'default_value': {'readonly': True}, - 'data_type': {'readonly': True}, - 'allowed_values': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "description": {"readonly": True}, + "default_value": {"readonly": True}, + "data_type": {"readonly": True}, + "allowed_values": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'value': {'key': 'properties.value', 'type': 'str'}, - 'description': {'key': 'properties.description', 'type': 'str'}, - 'default_value': {'key': 'properties.defaultValue', 'type': 'str'}, - 'data_type': {'key': 'properties.dataType', 'type': 'str'}, - 'allowed_values': {'key': 'properties.allowedValues', 'type': 'str'}, - 'source': {'key': 'properties.source', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "value": {"key": "properties.value", "type": "str"}, + "description": {"key": "properties.description", "type": "str"}, + "default_value": {"key": "properties.defaultValue", "type": "str"}, + "data_type": {"key": "properties.dataType", "type": "str"}, + "allowed_values": {"key": "properties.allowedValues", "type": "str"}, + "source": {"key": "properties.source", "type": "str"}, } - def __init__( - self, - *, - value: Optional[str] = None, - source: Optional[str] = None, - **kwargs - ): + def __init__(self, *, value: Optional[str] = None, source: Optional[str] = None, **kwargs): """ :keyword value: Value of the configuration. :paramtype value: str :keyword source: Source of the configuration. :paramtype source: str """ - super(Configuration, self).__init__(**kwargs) + super().__init__(**kwargs) self.value = value self.description = None self.default_value = None @@ -264,7 +242,7 @@ def __init__( self.source = source -class ConfigurationListResult(msrest.serialization.Model): +class ConfigurationListResult(_serialization.Model): """A list of server configurations. :ivar value: The list of server configurations. @@ -272,20 +250,15 @@ class ConfigurationListResult(msrest.serialization.Model): """ _attribute_map = { - 'value': {'key': 'value', 'type': '[Configuration]'}, + "value": {"key": "value", "type": "[Configuration]"}, } - def __init__( - self, - *, - value: Optional[List["_models.Configuration"]] = None, - **kwargs - ): + def __init__(self, *, value: Optional[List["_models.Configuration"]] = None, **kwargs): """ :keyword value: The list of server configurations. :paramtype value: list[~azure.mgmt.rdbms.mysql.models.Configuration] """ - super(ConfigurationListResult, self).__init__(**kwargs) + super().__init__(**kwargs) self.value = value @@ -309,38 +282,32 @@ class Database(ProxyResource): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'charset': {'key': 'properties.charset', 'type': 'str'}, - 'collation': {'key': 'properties.collation', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "charset": {"key": "properties.charset", "type": "str"}, + "collation": {"key": "properties.collation", "type": "str"}, } - def __init__( - self, - *, - charset: Optional[str] = None, - collation: Optional[str] = None, - **kwargs - ): + def __init__(self, *, charset: Optional[str] = None, collation: Optional[str] = None, **kwargs): """ :keyword charset: The charset of the database. :paramtype charset: str :keyword collation: The collation of the database. :paramtype collation: str """ - super(Database, self).__init__(**kwargs) + super().__init__(**kwargs) self.charset = charset self.collation = collation -class DatabaseListResult(msrest.serialization.Model): +class DatabaseListResult(_serialization.Model): """A List of databases. :ivar value: The list of databases housed in a server. @@ -348,24 +315,19 @@ class DatabaseListResult(msrest.serialization.Model): """ _attribute_map = { - 'value': {'key': 'value', 'type': '[Database]'}, + "value": {"key": "value", "type": "[Database]"}, } - def __init__( - self, - *, - value: Optional[List["_models.Database"]] = None, - **kwargs - ): + def __init__(self, *, value: Optional[List["_models.Database"]] = None, **kwargs): """ :keyword value: The list of databases housed in a server. :paramtype value: list[~azure.mgmt.rdbms.mysql.models.Database] """ - super(DatabaseListResult, self).__init__(**kwargs) + super().__init__(**kwargs) self.value = value -class ErrorAdditionalInfo(msrest.serialization.Model): +class ErrorAdditionalInfo(_serialization.Model): """The resource management error additional info. Variables are only populated by the server, and will be ignored when sending a request. @@ -373,31 +335,27 @@ class ErrorAdditionalInfo(msrest.serialization.Model): :ivar type: The additional info type. :vartype type: str :ivar info: The additional info. - :vartype info: any + :vartype info: JSON """ _validation = { - 'type': {'readonly': True}, - 'info': {'readonly': True}, + "type": {"readonly": True}, + "info": {"readonly": True}, } _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'info': {'key': 'info', 'type': 'object'}, + "type": {"key": "type", "type": "str"}, + "info": {"key": "info", "type": "object"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(ErrorAdditionalInfo, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.type = None self.info = None -class ErrorResponse(msrest.serialization.Model): +class ErrorResponse(_serialization.Model): """Common error response for all Azure Resource Manager APIs to return error details for failed operations. (This also follows the OData error response format.). Variables are only populated by the server, and will be ignored when sending a request. @@ -415,28 +373,24 @@ class ErrorResponse(msrest.serialization.Model): """ _validation = { - 'code': {'readonly': True}, - 'message': {'readonly': True}, - 'target': {'readonly': True}, - 'details': {'readonly': True}, - 'additional_info': {'readonly': True}, + "code": {"readonly": True}, + "message": {"readonly": True}, + "target": {"readonly": True}, + "details": {"readonly": True}, + "additional_info": {"readonly": True}, } _attribute_map = { - 'code': {'key': 'code', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, - 'target': {'key': 'target', 'type': 'str'}, - 'details': {'key': 'details', 'type': '[ErrorResponse]'}, - 'additional_info': {'key': 'additionalInfo', 'type': '[ErrorAdditionalInfo]'}, + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, + "target": {"key": "target", "type": "str"}, + "details": {"key": "details", "type": "[ErrorResponse]"}, + "additional_info": {"key": "additionalInfo", "type": "[ErrorAdditionalInfo]"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(ErrorResponse, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.code = None self.message = None self.target = None @@ -459,51 +413,51 @@ class FirewallRule(ProxyResource): :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts". :vartype type: str - :ivar start_ip_address: Required. The start IP address of the server firewall rule. Must be - IPv4 format. + :ivar start_ip_address: The start IP address of the server firewall rule. Must be IPv4 format. + Required. :vartype start_ip_address: str - :ivar end_ip_address: Required. The end IP address of the server firewall rule. Must be IPv4 - format. + :ivar end_ip_address: The end IP address of the server firewall rule. Must be IPv4 format. + Required. :vartype end_ip_address: str """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'start_ip_address': {'required': True, 'pattern': r'^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$'}, - 'end_ip_address': {'required': True, 'pattern': r'^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$'}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "start_ip_address": { + "required": True, + "pattern": r"^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$", + }, + "end_ip_address": { + "required": True, + "pattern": r"^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$", + }, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'start_ip_address': {'key': 'properties.startIpAddress', 'type': 'str'}, - 'end_ip_address': {'key': 'properties.endIpAddress', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "start_ip_address": {"key": "properties.startIpAddress", "type": "str"}, + "end_ip_address": {"key": "properties.endIpAddress", "type": "str"}, } - def __init__( - self, - *, - start_ip_address: str, - end_ip_address: str, - **kwargs - ): + def __init__(self, *, start_ip_address: str, end_ip_address: str, **kwargs): """ - :keyword start_ip_address: Required. The start IP address of the server firewall rule. Must be - IPv4 format. + :keyword start_ip_address: The start IP address of the server firewall rule. Must be IPv4 + format. Required. :paramtype start_ip_address: str - :keyword end_ip_address: Required. The end IP address of the server firewall rule. Must be IPv4 - format. + :keyword end_ip_address: The end IP address of the server firewall rule. Must be IPv4 format. + Required. :paramtype end_ip_address: str """ - super(FirewallRule, self).__init__(**kwargs) + super().__init__(**kwargs) self.start_ip_address = start_ip_address self.end_ip_address = end_ip_address -class FirewallRuleListResult(msrest.serialization.Model): +class FirewallRuleListResult(_serialization.Model): """A list of firewall rules. :ivar value: The list of firewall rules in a server. @@ -511,20 +465,15 @@ class FirewallRuleListResult(msrest.serialization.Model): """ _attribute_map = { - 'value': {'key': 'value', 'type': '[FirewallRule]'}, + "value": {"key": "value", "type": "[FirewallRule]"}, } - def __init__( - self, - *, - value: Optional[List["_models.FirewallRule"]] = None, - **kwargs - ): + def __init__(self, *, value: Optional[List["_models.FirewallRule"]] = None, **kwargs): """ :keyword value: The list of firewall rules in a server. :paramtype value: list[~azure.mgmt.rdbms.mysql.models.FirewallRule] """ - super(FirewallRuleListResult, self).__init__(**kwargs) + super().__init__(**kwargs) self.value = value @@ -542,7 +491,7 @@ class LogFile(ProxyResource): "Microsoft.Storage/storageAccounts". :vartype type: str :ivar size_in_kb: Size of the log file. - :vartype size_in_kb: long + :vartype size_in_kb: int :ivar created_time: Creation timestamp of the log file. :vartype created_time: ~datetime.datetime :ivar last_modified_time: Last modified timestamp of the log file. @@ -554,22 +503,22 @@ class LogFile(ProxyResource): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'created_time': {'readonly': True}, - 'last_modified_time': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "created_time": {"readonly": True}, + "last_modified_time": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'size_in_kb': {'key': 'properties.sizeInKB', 'type': 'long'}, - 'created_time': {'key': 'properties.createdTime', 'type': 'iso-8601'}, - 'last_modified_time': {'key': 'properties.lastModifiedTime', 'type': 'iso-8601'}, - 'type_properties_type': {'key': 'properties.type', 'type': 'str'}, - 'url': {'key': 'properties.url', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "size_in_kb": {"key": "properties.sizeInKB", "type": "int"}, + "created_time": {"key": "properties.createdTime", "type": "iso-8601"}, + "last_modified_time": {"key": "properties.lastModifiedTime", "type": "iso-8601"}, + "type_properties_type": {"key": "properties.type", "type": "str"}, + "url": {"key": "properties.url", "type": "str"}, } def __init__( @@ -582,13 +531,13 @@ def __init__( ): """ :keyword size_in_kb: Size of the log file. - :paramtype size_in_kb: long + :paramtype size_in_kb: int :keyword type_properties_type: Type of the log file. :paramtype type_properties_type: str :keyword url: The url to download the log file from. :paramtype url: str """ - super(LogFile, self).__init__(**kwargs) + super().__init__(**kwargs) self.size_in_kb = size_in_kb self.created_time = None self.last_modified_time = None @@ -596,7 +545,7 @@ def __init__( self.url = url -class LogFileListResult(msrest.serialization.Model): +class LogFileListResult(_serialization.Model): """A list of log files. :ivar value: The list of log files. @@ -604,24 +553,19 @@ class LogFileListResult(msrest.serialization.Model): """ _attribute_map = { - 'value': {'key': 'value', 'type': '[LogFile]'}, + "value": {"key": "value", "type": "[LogFile]"}, } - def __init__( - self, - *, - value: Optional[List["_models.LogFile"]] = None, - **kwargs - ): + def __init__(self, *, value: Optional[List["_models.LogFile"]] = None, **kwargs): """ :keyword value: The list of log files. :paramtype value: list[~azure.mgmt.rdbms.mysql.models.LogFile] """ - super(LogFileListResult, self).__init__(**kwargs) + super().__init__(**kwargs) self.value = value -class NameAvailability(msrest.serialization.Model): +class NameAvailability(_serialization.Model): """Represents a resource name availability. :ivar message: Error Message. @@ -633,9 +577,9 @@ class NameAvailability(msrest.serialization.Model): """ _attribute_map = { - 'message': {'key': 'message', 'type': 'str'}, - 'name_available': {'key': 'nameAvailable', 'type': 'bool'}, - 'reason': {'key': 'reason', 'type': 'str'}, + "message": {"key": "message", "type": "str"}, + "name_available": {"key": "nameAvailable", "type": "bool"}, + "reason": {"key": "reason", "type": "str"}, } def __init__( @@ -654,51 +598,45 @@ def __init__( :keyword reason: Reason for name being unavailable. :paramtype reason: str """ - super(NameAvailability, self).__init__(**kwargs) + super().__init__(**kwargs) self.message = message self.name_available = name_available self.reason = reason -class NameAvailabilityRequest(msrest.serialization.Model): +class NameAvailabilityRequest(_serialization.Model): """Request from client to check resource name availability. All required parameters must be populated in order to send to Azure. - :ivar name: Required. Resource name to verify. + :ivar name: Resource name to verify. Required. :vartype name: str :ivar type: Resource type used for verification. :vartype type: str """ _validation = { - 'name': {'required': True}, + "name": {"required": True}, } _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, } - def __init__( - self, - *, - name: str, - type: Optional[str] = None, - **kwargs - ): + def __init__(self, *, name: str, type: Optional[str] = None, **kwargs): """ - :keyword name: Required. Resource name to verify. + :keyword name: Resource name to verify. Required. :paramtype name: str :keyword type: Resource type used for verification. :paramtype type: str """ - super(NameAvailabilityRequest, self).__init__(**kwargs) + super().__init__(**kwargs) self.name = name self.type = type -class Operation(msrest.serialization.Model): +class Operation(_serialization.Model): """REST API operation definition. Variables are only populated by the server, and will be ignored when sending a request. @@ -708,40 +646,36 @@ class Operation(msrest.serialization.Model): :ivar display: The localized display information for this particular operation or action. :vartype display: ~azure.mgmt.rdbms.mysql.models.OperationDisplay :ivar origin: The intended executor of the operation. Known values are: "NotSpecified", "user", - "system". + and "system". :vartype origin: str or ~azure.mgmt.rdbms.mysql.models.OperationOrigin :ivar properties: Additional descriptions for the operation. - :vartype properties: dict[str, any] + :vartype properties: dict[str, JSON] """ _validation = { - 'name': {'readonly': True}, - 'display': {'readonly': True}, - 'origin': {'readonly': True}, - 'properties': {'readonly': True}, + "name": {"readonly": True}, + "display": {"readonly": True}, + "origin": {"readonly": True}, + "properties": {"readonly": True}, } _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'display': {'key': 'display', 'type': 'OperationDisplay'}, - 'origin': {'key': 'origin', 'type': 'str'}, - 'properties': {'key': 'properties', 'type': '{object}'}, + "name": {"key": "name", "type": "str"}, + "display": {"key": "display", "type": "OperationDisplay"}, + "origin": {"key": "origin", "type": "str"}, + "properties": {"key": "properties", "type": "{object}"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(Operation, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.name = None self.display = None self.origin = None self.properties = None -class OperationDisplay(msrest.serialization.Model): +class OperationDisplay(_serialization.Model): """Display metadata associated with the operation. Variables are only populated by the server, and will be ignored when sending a request. @@ -757,33 +691,29 @@ class OperationDisplay(msrest.serialization.Model): """ _validation = { - 'provider': {'readonly': True}, - 'resource': {'readonly': True}, - 'operation': {'readonly': True}, - 'description': {'readonly': True}, + "provider": {"readonly": True}, + "resource": {"readonly": True}, + "operation": {"readonly": True}, + "description": {"readonly": True}, } _attribute_map = { - 'provider': {'key': 'provider', 'type': 'str'}, - 'resource': {'key': 'resource', 'type': 'str'}, - 'operation': {'key': 'operation', 'type': 'str'}, - 'description': {'key': 'description', 'type': 'str'}, + "provider": {"key": "provider", "type": "str"}, + "resource": {"key": "resource", "type": "str"}, + "operation": {"key": "operation", "type": "str"}, + "description": {"key": "description", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(OperationDisplay, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.provider = None self.resource = None self.operation = None self.description = None -class OperationListResult(msrest.serialization.Model): +class OperationListResult(_serialization.Model): """A list of resource provider operations. :ivar value: The list of resource provider operations. @@ -791,24 +721,19 @@ class OperationListResult(msrest.serialization.Model): """ _attribute_map = { - 'value': {'key': 'value', 'type': '[Operation]'}, + "value": {"key": "value", "type": "[Operation]"}, } - def __init__( - self, - *, - value: Optional[List["_models.Operation"]] = None, - **kwargs - ): + def __init__(self, *, value: Optional[List["_models.Operation"]] = None, **kwargs): """ :keyword value: The list of resource provider operations. :paramtype value: list[~azure.mgmt.rdbms.mysql.models.Operation] """ - super(OperationListResult, self).__init__(**kwargs) + super().__init__(**kwargs) self.value = value -class PerformanceTierListResult(msrest.serialization.Model): +class PerformanceTierListResult(_serialization.Model): """A list of performance tiers. :ivar value: The list of performance tiers. @@ -816,24 +741,19 @@ class PerformanceTierListResult(msrest.serialization.Model): """ _attribute_map = { - 'value': {'key': 'value', 'type': '[PerformanceTierProperties]'}, + "value": {"key": "value", "type": "[PerformanceTierProperties]"}, } - def __init__( - self, - *, - value: Optional[List["_models.PerformanceTierProperties"]] = None, - **kwargs - ): + def __init__(self, *, value: Optional[List["_models.PerformanceTierProperties"]] = None, **kwargs): """ :keyword value: The list of performance tiers. :paramtype value: list[~azure.mgmt.rdbms.mysql.models.PerformanceTierProperties] """ - super(PerformanceTierListResult, self).__init__(**kwargs) + super().__init__(**kwargs) self.value = value -class PerformanceTierProperties(msrest.serialization.Model): +class PerformanceTierProperties(_serialization.Model): """Performance tier properties. :ivar id: ID of the performance tier. @@ -858,20 +778,23 @@ class PerformanceTierProperties(msrest.serialization.Model): """ _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'max_backup_retention_days': {'key': 'maxBackupRetentionDays', 'type': 'int'}, - 'min_backup_retention_days': {'key': 'minBackupRetentionDays', 'type': 'int'}, - 'max_storage_mb': {'key': 'maxStorageMB', 'type': 'int'}, - 'min_large_storage_mb': {'key': 'minLargeStorageMB', 'type': 'int'}, - 'max_large_storage_mb': {'key': 'maxLargeStorageMB', 'type': 'int'}, - 'min_storage_mb': {'key': 'minStorageMB', 'type': 'int'}, - 'service_level_objectives': {'key': 'serviceLevelObjectives', 'type': '[PerformanceTierServiceLevelObjectives]'}, + "id": {"key": "id", "type": "str"}, + "max_backup_retention_days": {"key": "maxBackupRetentionDays", "type": "int"}, + "min_backup_retention_days": {"key": "minBackupRetentionDays", "type": "int"}, + "max_storage_mb": {"key": "maxStorageMB", "type": "int"}, + "min_large_storage_mb": {"key": "minLargeStorageMB", "type": "int"}, + "max_large_storage_mb": {"key": "maxLargeStorageMB", "type": "int"}, + "min_storage_mb": {"key": "minStorageMB", "type": "int"}, + "service_level_objectives": { + "key": "serviceLevelObjectives", + "type": "[PerformanceTierServiceLevelObjectives]", + }, } def __init__( self, *, - id: Optional[str] = None, + id: Optional[str] = None, # pylint: disable=redefined-builtin max_backup_retention_days: Optional[int] = None, min_backup_retention_days: Optional[int] = None, max_storage_mb: Optional[int] = None, @@ -903,7 +826,7 @@ def __init__( :paramtype service_level_objectives: list[~azure.mgmt.rdbms.mysql.models.PerformanceTierServiceLevelObjectives] """ - super(PerformanceTierProperties, self).__init__(**kwargs) + super().__init__(**kwargs) self.id = id self.max_backup_retention_days = max_backup_retention_days self.min_backup_retention_days = min_backup_retention_days @@ -914,7 +837,7 @@ def __init__( self.service_level_objectives = service_level_objectives -class PerformanceTierServiceLevelObjectives(msrest.serialization.Model): +class PerformanceTierServiceLevelObjectives(_serialization.Model): """Service level objectives for performance tier. :ivar id: ID for the service level objective. @@ -938,20 +861,20 @@ class PerformanceTierServiceLevelObjectives(msrest.serialization.Model): """ _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'edition': {'key': 'edition', 'type': 'str'}, - 'v_core': {'key': 'vCore', 'type': 'int'}, - 'hardware_generation': {'key': 'hardwareGeneration', 'type': 'str'}, - 'max_backup_retention_days': {'key': 'maxBackupRetentionDays', 'type': 'int'}, - 'min_backup_retention_days': {'key': 'minBackupRetentionDays', 'type': 'int'}, - 'max_storage_mb': {'key': 'maxStorageMB', 'type': 'int'}, - 'min_storage_mb': {'key': 'minStorageMB', 'type': 'int'}, + "id": {"key": "id", "type": "str"}, + "edition": {"key": "edition", "type": "str"}, + "v_core": {"key": "vCore", "type": "int"}, + "hardware_generation": {"key": "hardwareGeneration", "type": "str"}, + "max_backup_retention_days": {"key": "maxBackupRetentionDays", "type": "int"}, + "min_backup_retention_days": {"key": "minBackupRetentionDays", "type": "int"}, + "max_storage_mb": {"key": "maxStorageMB", "type": "int"}, + "min_storage_mb": {"key": "minStorageMB", "type": "int"}, } def __init__( self, *, - id: Optional[str] = None, + id: Optional[str] = None, # pylint: disable=redefined-builtin edition: Optional[str] = None, v_core: Optional[int] = None, hardware_generation: Optional[str] = None, @@ -981,7 +904,7 @@ def __init__( :keyword min_storage_mb: Max storage allowed for a server. :paramtype min_storage_mb: int """ - super(PerformanceTierServiceLevelObjectives, self).__init__(**kwargs) + super().__init__(**kwargs) self.id = id self.edition = edition self.v_core = v_core @@ -1016,19 +939,22 @@ class PrivateEndpointConnection(ProxyResource): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'provisioning_state': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "provisioning_state": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'private_endpoint': {'key': 'properties.privateEndpoint', 'type': 'PrivateEndpointProperty'}, - 'private_link_service_connection_state': {'key': 'properties.privateLinkServiceConnectionState', 'type': 'PrivateLinkServiceConnectionStateProperty'}, - 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "private_endpoint": {"key": "properties.privateEndpoint", "type": "PrivateEndpointProperty"}, + "private_link_service_connection_state": { + "key": "properties.privateLinkServiceConnectionState", + "type": "PrivateLinkServiceConnectionStateProperty", + }, + "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, } def __init__( @@ -1046,13 +972,13 @@ def __init__( :paramtype private_link_service_connection_state: ~azure.mgmt.rdbms.mysql.models.PrivateLinkServiceConnectionStateProperty """ - super(PrivateEndpointConnection, self).__init__(**kwargs) + super().__init__(**kwargs) self.private_endpoint = private_endpoint self.private_link_service_connection_state = private_link_service_connection_state self.provisioning_state = None -class PrivateEndpointConnectionListResult(msrest.serialization.Model): +class PrivateEndpointConnectionListResult(_serialization.Model): """A list of private endpoint connections. Variables are only populated by the server, and will be ignored when sending a request. @@ -1064,27 +990,23 @@ class PrivateEndpointConnectionListResult(msrest.serialization.Model): """ _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, + "value": {"readonly": True}, + "next_link": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[PrivateEndpointConnection]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[PrivateEndpointConnection]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(PrivateEndpointConnectionListResult, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.value = None self.next_link = None -class PrivateEndpointProperty(msrest.serialization.Model): +class PrivateEndpointProperty(_serialization.Model): """PrivateEndpointProperty. :ivar id: Resource id of the private endpoint. @@ -1092,20 +1014,15 @@ class PrivateEndpointProperty(msrest.serialization.Model): """ _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, } - def __init__( - self, - *, - id: Optional[str] = None, - **kwargs - ): + def __init__(self, *, id: Optional[str] = None, **kwargs): # pylint: disable=redefined-builtin """ :keyword id: Resource id of the private endpoint. :paramtype id: str """ - super(PrivateEndpointProperty, self).__init__(**kwargs) + super().__init__(**kwargs) self.id = id @@ -1127,30 +1044,26 @@ class PrivateLinkResource(ProxyResource): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'properties': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "properties": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'properties': {'key': 'properties', 'type': 'PrivateLinkResourceProperties'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "properties": {"key": "properties", "type": "PrivateLinkResourceProperties"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(PrivateLinkResource, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.properties = None -class PrivateLinkResourceListResult(msrest.serialization.Model): +class PrivateLinkResourceListResult(_serialization.Model): """A list of private link resources. Variables are only populated by the server, and will be ignored when sending a request. @@ -1162,27 +1075,23 @@ class PrivateLinkResourceListResult(msrest.serialization.Model): """ _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, + "value": {"readonly": True}, + "next_link": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[PrivateLinkResource]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[PrivateLinkResource]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(PrivateLinkResourceListResult, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.value = None self.next_link = None -class PrivateLinkResourceProperties(msrest.serialization.Model): +class PrivateLinkResourceProperties(_serialization.Model): """Properties of a private link resource. Variables are only populated by the server, and will be ignored when sending a request. @@ -1194,76 +1103,66 @@ class PrivateLinkResourceProperties(msrest.serialization.Model): """ _validation = { - 'group_id': {'readonly': True}, - 'required_members': {'readonly': True}, + "group_id": {"readonly": True}, + "required_members": {"readonly": True}, } _attribute_map = { - 'group_id': {'key': 'groupId', 'type': 'str'}, - 'required_members': {'key': 'requiredMembers', 'type': '[str]'}, + "group_id": {"key": "groupId", "type": "str"}, + "required_members": {"key": "requiredMembers", "type": "[str]"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(PrivateLinkResourceProperties, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.group_id = None self.required_members = None -class PrivateLinkServiceConnectionStateProperty(msrest.serialization.Model): +class PrivateLinkServiceConnectionStateProperty(_serialization.Model): """PrivateLinkServiceConnectionStateProperty. 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 status: Required. The private link service connection status. + :ivar status: The private link service connection status. Required. :vartype status: str - :ivar description: Required. The private link service connection description. + :ivar description: The private link service connection description. Required. :vartype description: str :ivar actions_required: The actions required for private link service connection. :vartype actions_required: str """ _validation = { - 'status': {'required': True}, - 'description': {'required': True}, - 'actions_required': {'readonly': True}, + "status": {"required": True}, + "description": {"required": True}, + "actions_required": {"readonly": True}, } _attribute_map = { - 'status': {'key': 'status', 'type': 'str'}, - 'description': {'key': 'description', 'type': 'str'}, - 'actions_required': {'key': 'actionsRequired', 'type': 'str'}, + "status": {"key": "status", "type": "str"}, + "description": {"key": "description", "type": "str"}, + "actions_required": {"key": "actionsRequired", "type": "str"}, } - def __init__( - self, - *, - status: str, - description: str, - **kwargs - ): + def __init__(self, *, status: str, description: str, **kwargs): """ - :keyword status: Required. The private link service connection status. + :keyword status: The private link service connection status. Required. :paramtype status: str - :keyword description: Required. The private link service connection description. + :keyword description: The private link service connection description. Required. :paramtype description: str """ - super(PrivateLinkServiceConnectionStateProperty, self).__init__(**kwargs) + super().__init__(**kwargs) self.status = status self.description = description self.actions_required = None -class QueryPerformanceInsightResetDataResult(msrest.serialization.Model): +class QueryPerformanceInsightResetDataResult(_serialization.Model): """Result of Query Performance Insight data reset. - :ivar status: Indicates result of the operation. Known values are: "Succeeded", "Failed". + :ivar status: Indicates result of the operation. Known values are: "Succeeded" and "Failed". :vartype status: str or ~azure.mgmt.rdbms.mysql.models.QueryPerformanceInsightResetDataResultState :ivar message: operation message. @@ -1271,8 +1170,8 @@ class QueryPerformanceInsightResetDataResult(msrest.serialization.Model): """ _attribute_map = { - 'status': {'key': 'status', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, + "status": {"key": "status", "type": "str"}, + "message": {"key": "message", "type": "str"}, } def __init__( @@ -1283,18 +1182,18 @@ def __init__( **kwargs ): """ - :keyword status: Indicates result of the operation. Known values are: "Succeeded", "Failed". + :keyword status: Indicates result of the operation. Known values are: "Succeeded" and "Failed". :paramtype status: str or ~azure.mgmt.rdbms.mysql.models.QueryPerformanceInsightResetDataResultState :keyword message: operation message. :paramtype message: str """ - super(QueryPerformanceInsightResetDataResult, self).__init__(**kwargs) + super().__init__(**kwargs) self.status = status self.message = message -class QueryStatistic(ProxyResource): +class QueryStatistic(ProxyResource): # pylint: disable=too-many-instance-attributes """Represents a Query Statistic. Variables are only populated by the server, and will be ignored when sending a request. @@ -1318,7 +1217,7 @@ class QueryStatistic(ProxyResource): :ivar database_names: The list of database names. :vartype database_names: list[str] :ivar query_execution_count: Number of query executions in this time interval. - :vartype query_execution_count: long + :vartype query_execution_count: int :ivar metric_name: Metric name. :vartype metric_name: str :ivar metric_display_name: Metric display name. @@ -1330,25 +1229,25 @@ class QueryStatistic(ProxyResource): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'query_id': {'key': 'properties.queryId', 'type': 'str'}, - 'start_time': {'key': 'properties.startTime', 'type': 'iso-8601'}, - 'end_time': {'key': 'properties.endTime', 'type': 'iso-8601'}, - 'aggregation_function': {'key': 'properties.aggregationFunction', 'type': 'str'}, - 'database_names': {'key': 'properties.databaseNames', 'type': '[str]'}, - 'query_execution_count': {'key': 'properties.queryExecutionCount', 'type': 'long'}, - 'metric_name': {'key': 'properties.metricName', 'type': 'str'}, - 'metric_display_name': {'key': 'properties.metricDisplayName', 'type': 'str'}, - 'metric_value': {'key': 'properties.metricValue', 'type': 'float'}, - 'metric_value_unit': {'key': 'properties.metricValueUnit', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "query_id": {"key": "properties.queryId", "type": "str"}, + "start_time": {"key": "properties.startTime", "type": "iso-8601"}, + "end_time": {"key": "properties.endTime", "type": "iso-8601"}, + "aggregation_function": {"key": "properties.aggregationFunction", "type": "str"}, + "database_names": {"key": "properties.databaseNames", "type": "[str]"}, + "query_execution_count": {"key": "properties.queryExecutionCount", "type": "int"}, + "metric_name": {"key": "properties.metricName", "type": "str"}, + "metric_display_name": {"key": "properties.metricDisplayName", "type": "str"}, + "metric_value": {"key": "properties.metricValue", "type": "float"}, + "metric_value_unit": {"key": "properties.metricValueUnit", "type": "str"}, } def __init__( @@ -1378,7 +1277,7 @@ def __init__( :keyword database_names: The list of database names. :paramtype database_names: list[str] :keyword query_execution_count: Number of query executions in this time interval. - :paramtype query_execution_count: long + :paramtype query_execution_count: int :keyword metric_name: Metric name. :paramtype metric_name: str :keyword metric_display_name: Metric display name. @@ -1388,7 +1287,7 @@ def __init__( :keyword metric_value_unit: Metric value unit. :paramtype metric_value_unit: str """ - super(QueryStatistic, self).__init__(**kwargs) + super().__init__(**kwargs) self.query_id = query_id self.start_time = start_time self.end_time = end_time @@ -1421,38 +1320,32 @@ class QueryText(ProxyResource): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'query_id': {'key': 'properties.queryId', 'type': 'str'}, - 'query_text': {'key': 'properties.queryText', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "query_id": {"key": "properties.queryId", "type": "str"}, + "query_text": {"key": "properties.queryText", "type": "str"}, } - def __init__( - self, - *, - query_id: Optional[str] = None, - query_text: Optional[str] = None, - **kwargs - ): + def __init__(self, *, query_id: Optional[str] = None, query_text: Optional[str] = None, **kwargs): """ :keyword query_id: Query identifier unique to the server. :paramtype query_id: str :keyword query_text: Query text. :paramtype query_text: str """ - super(QueryText, self).__init__(**kwargs) + super().__init__(**kwargs) self.query_id = query_id self.query_text = query_text -class QueryTextsResultList(msrest.serialization.Model): +class QueryTextsResultList(_serialization.Model): """A list of query texts. Variables are only populated by the server, and will be ignored when sending a request. @@ -1464,27 +1357,23 @@ class QueryTextsResultList(msrest.serialization.Model): """ _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, + "value": {"readonly": True}, + "next_link": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[QueryText]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[QueryText]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(QueryTextsResultList, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.value = None self.next_link = None -class RecommendationAction(ProxyResource): +class RecommendationAction(ProxyResource): # pylint: disable=too-many-instance-attributes """Represents a Recommendation Action. Variables are only populated by the server, and will be ignored when sending a request. @@ -1516,23 +1405,23 @@ class RecommendationAction(ProxyResource): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'advisor_name': {'key': 'properties.advisorName', 'type': 'str'}, - 'session_id': {'key': 'properties.sessionId', 'type': 'str'}, - 'action_id': {'key': 'properties.actionId', 'type': 'int'}, - 'created_time': {'key': 'properties.createdTime', 'type': 'iso-8601'}, - 'expiration_time': {'key': 'properties.expirationTime', 'type': 'iso-8601'}, - 'reason': {'key': 'properties.reason', 'type': 'str'}, - 'recommendation_type': {'key': 'properties.recommendationType', 'type': 'str'}, - 'details': {'key': 'properties.details', 'type': '{str}'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "advisor_name": {"key": "properties.advisorName", "type": "str"}, + "session_id": {"key": "properties.sessionId", "type": "str"}, + "action_id": {"key": "properties.actionId", "type": "int"}, + "created_time": {"key": "properties.createdTime", "type": "iso-8601"}, + "expiration_time": {"key": "properties.expirationTime", "type": "iso-8601"}, + "reason": {"key": "properties.reason", "type": "str"}, + "recommendation_type": {"key": "properties.recommendationType", "type": "str"}, + "details": {"key": "properties.details", "type": "{str}"}, } def __init__( @@ -1566,7 +1455,7 @@ def __init__( :keyword details: Recommendation action details. :paramtype details: dict[str, str] """ - super(RecommendationAction, self).__init__(**kwargs) + super().__init__(**kwargs) self.advisor_name = advisor_name self.session_id = session_id self.action_id = action_id @@ -1577,7 +1466,7 @@ def __init__( self.details = details -class RecommendationActionsResultList(msrest.serialization.Model): +class RecommendationActionsResultList(_serialization.Model): """A list of recommendation actions. Variables are only populated by the server, and will be ignored when sending a request. @@ -1589,27 +1478,23 @@ class RecommendationActionsResultList(msrest.serialization.Model): """ _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, + "value": {"readonly": True}, + "next_link": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[RecommendationAction]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[RecommendationAction]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(RecommendationActionsResultList, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.value = None self.next_link = None -class RecommendedActionSessionsOperationStatus(msrest.serialization.Model): +class RecommendedActionSessionsOperationStatus(_serialization.Model): """Recommendation action session operation status. :ivar name: Operation identifier. @@ -1621,9 +1506,9 @@ class RecommendedActionSessionsOperationStatus(msrest.serialization.Model): """ _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'start_time': {'key': 'startTime', 'type': 'iso-8601'}, - 'status': {'key': 'status', 'type': 'str'}, + "name": {"key": "name", "type": "str"}, + "start_time": {"key": "startTime", "type": "iso-8601"}, + "status": {"key": "status", "type": "str"}, } def __init__( @@ -1642,7 +1527,7 @@ def __init__( :keyword status: Operation status. :paramtype status: str """ - super(RecommendedActionSessionsOperationStatus, self).__init__(**kwargs) + super().__init__(**kwargs) self.name = name self.start_time = start_time self.status = status @@ -1676,36 +1561,32 @@ class RecoverableServerResource(ProxyResource): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'last_available_backup_date_time': {'readonly': True}, - 'service_level_objective': {'readonly': True}, - 'edition': {'readonly': True}, - 'v_core': {'readonly': True}, - 'hardware_generation': {'readonly': True}, - 'version': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'last_available_backup_date_time': {'key': 'properties.lastAvailableBackupDateTime', 'type': 'str'}, - 'service_level_objective': {'key': 'properties.serviceLevelObjective', 'type': 'str'}, - 'edition': {'key': 'properties.edition', 'type': 'str'}, - 'v_core': {'key': 'properties.vCore', 'type': 'int'}, - 'hardware_generation': {'key': 'properties.hardwareGeneration', 'type': 'str'}, - 'version': {'key': 'properties.version', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - """ - """ - super(RecoverableServerResource, self).__init__(**kwargs) + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "last_available_backup_date_time": {"readonly": True}, + "service_level_objective": {"readonly": True}, + "edition": {"readonly": True}, + "v_core": {"readonly": True}, + "hardware_generation": {"readonly": True}, + "version": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "last_available_backup_date_time": {"key": "properties.lastAvailableBackupDateTime", "type": "str"}, + "service_level_objective": {"key": "properties.serviceLevelObjective", "type": "str"}, + "edition": {"key": "properties.edition", "type": "str"}, + "v_core": {"key": "properties.vCore", "type": "int"}, + "hardware_generation": {"key": "properties.hardwareGeneration", "type": "str"}, + "version": {"key": "properties.version", "type": "str"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.last_available_backup_date_time = None self.service_level_objective = None self.edition = None @@ -1714,7 +1595,7 @@ def __init__( self.version = None -class ResourceIdentity(msrest.serialization.Model): +class ResourceIdentity(_serialization.Model): """Azure Active Directory identity configuration for a resource. Variables are only populated by the server, and will be ignored when sending a request. @@ -1722,37 +1603,30 @@ class ResourceIdentity(msrest.serialization.Model): :ivar principal_id: The Azure Active Directory principal id. :vartype principal_id: str :ivar type: The identity type. Set this to 'SystemAssigned' in order to automatically create - and assign an Azure Active Directory principal for the resource. Known values are: - "SystemAssigned". + and assign an Azure Active Directory principal for the resource. "SystemAssigned" :vartype type: str or ~azure.mgmt.rdbms.mysql.models.IdentityType :ivar tenant_id: The Azure Active Directory tenant id. :vartype tenant_id: str """ _validation = { - 'principal_id': {'readonly': True}, - 'tenant_id': {'readonly': True}, + "principal_id": {"readonly": True}, + "tenant_id": {"readonly": True}, } _attribute_map = { - 'principal_id': {'key': 'principalId', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'tenant_id': {'key': 'tenantId', 'type': 'str'}, + "principal_id": {"key": "principalId", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "tenant_id": {"key": "tenantId", "type": "str"}, } - def __init__( - self, - *, - type: Optional[Union[str, "_models.IdentityType"]] = None, - **kwargs - ): + def __init__(self, *, type: Optional[Union[str, "_models.IdentityType"]] = None, **kwargs): """ :keyword type: The identity type. Set this to 'SystemAssigned' in order to automatically create - and assign an Azure Active Directory principal for the resource. Known values are: - "SystemAssigned". + and assign an Azure Active Directory principal for the resource. "SystemAssigned" :paramtype type: str or ~azure.mgmt.rdbms.mysql.models.IdentityType """ - super(ResourceIdentity, self).__init__(**kwargs) + super().__init__(**kwargs) self.principal_id = None self.type = type self.tenant_id = None @@ -1773,46 +1647,40 @@ class TrackedResource(Resource): :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts". :vartype type: str - :ivar tags: A set of tags. Resource tags. + :ivar tags: Resource tags. :vartype tags: dict[str, str] - :ivar location: Required. The geo-location where the resource lives. + :ivar location: The geo-location where the resource lives. Required. :vartype location: str """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'location': {'required': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "location": {"required": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - 'location': {'key': 'location', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "location": {"key": "location", "type": "str"}, } - def __init__( - self, - *, - location: str, - tags: Optional[Dict[str, str]] = None, - **kwargs - ): + def __init__(self, *, location: str, tags: Optional[Dict[str, str]] = None, **kwargs): """ - :keyword tags: A set of tags. Resource tags. + :keyword tags: Resource tags. :paramtype tags: dict[str, str] - :keyword location: Required. The geo-location where the resource lives. + :keyword location: The geo-location where the resource lives. Required. :paramtype location: str """ - super(TrackedResource, self).__init__(**kwargs) + super().__init__(**kwargs) self.tags = tags self.location = location -class Server(TrackedResource): +class Server(TrackedResource): # pylint: disable=too-many-instance-attributes """Represents a server. Variables are only populated by the server, and will be ignored when sending a request. @@ -1827,9 +1695,9 @@ class Server(TrackedResource): :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts". :vartype type: str - :ivar tags: A set of tags. Resource tags. + :ivar tags: Resource tags. :vartype tags: dict[str, str] - :ivar location: Required. The geo-location where the resource lives. + :ivar location: The geo-location where the resource lives. Required. :vartype location: str :ivar identity: The Azure Active Directory identity of the server. :vartype identity: ~azure.mgmt.rdbms.mysql.models.ResourceIdentity @@ -1838,23 +1706,23 @@ class Server(TrackedResource): :ivar administrator_login: The administrator's login name of a server. Can only be specified when the server is being created (and is required for creation). :vartype administrator_login: str - :ivar version: Server version. Known values are: "5.6", "5.7", "8.0". + :ivar version: Server version. Known values are: "5.6", "5.7", and "8.0". :vartype version: str or ~azure.mgmt.rdbms.mysql.models.ServerVersion :ivar ssl_enforcement: Enable ssl enforcement or not when connect to server. Known values are: - "Enabled", "Disabled". + "Enabled" and "Disabled". :vartype ssl_enforcement: str or ~azure.mgmt.rdbms.mysql.models.SslEnforcementEnum :ivar minimal_tls_version: Enforce a minimal Tls version for the server. Known values are: - "TLS1_0", "TLS1_1", "TLS1_2", "TLSEnforcementDisabled". + "TLS1_0", "TLS1_1", "TLS1_2", and "TLSEnforcementDisabled". :vartype minimal_tls_version: str or ~azure.mgmt.rdbms.mysql.models.MinimalTlsVersionEnum :ivar byok_enforcement: Status showing whether the server data encryption is enabled with customer-managed keys. :vartype byok_enforcement: str :ivar infrastructure_encryption: Status showing whether the server enabled infrastructure - encryption. Known values are: "Enabled", "Disabled". + encryption. Known values are: "Enabled" and "Disabled". :vartype infrastructure_encryption: str or ~azure.mgmt.rdbms.mysql.models.InfrastructureEncryption :ivar user_visible_state: A state of a server that is visible to user. Known values are: - "Ready", "Dropping", "Disabled", "Inaccessible". + "Ready", "Dropping", "Disabled", and "Inaccessible". :vartype user_visible_state: str or ~azure.mgmt.rdbms.mysql.models.ServerState :ivar fully_qualified_domain_name: The fully qualified domain name of a server. :vartype fully_qualified_domain_name: str @@ -1870,7 +1738,7 @@ class Server(TrackedResource): :vartype replica_capacity: int :ivar public_network_access: Whether or not public network access is allowed for this server. Value is optional but if passed in, must be 'Enabled' or 'Disabled'. Known values are: - "Enabled", "Disabled". + "Enabled" and "Disabled". :vartype public_network_access: str or ~azure.mgmt.rdbms.mysql.models.PublicNetworkAccessEnum :ivar private_endpoint_connections: List of private endpoint connections on a server. :vartype private_endpoint_connections: @@ -1878,38 +1746,41 @@ class Server(TrackedResource): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'location': {'required': True}, - 'byok_enforcement': {'readonly': True}, - 'replica_capacity': {'minimum': 0}, - 'private_endpoint_connections': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - 'location': {'key': 'location', 'type': 'str'}, - 'identity': {'key': 'identity', 'type': 'ResourceIdentity'}, - 'sku': {'key': 'sku', 'type': 'Sku'}, - 'administrator_login': {'key': 'properties.administratorLogin', 'type': 'str'}, - 'version': {'key': 'properties.version', 'type': 'str'}, - 'ssl_enforcement': {'key': 'properties.sslEnforcement', 'type': 'str'}, - 'minimal_tls_version': {'key': 'properties.minimalTlsVersion', 'type': 'str'}, - 'byok_enforcement': {'key': 'properties.byokEnforcement', 'type': 'str'}, - 'infrastructure_encryption': {'key': 'properties.infrastructureEncryption', 'type': 'str'}, - 'user_visible_state': {'key': 'properties.userVisibleState', 'type': 'str'}, - 'fully_qualified_domain_name': {'key': 'properties.fullyQualifiedDomainName', 'type': 'str'}, - 'earliest_restore_date': {'key': 'properties.earliestRestoreDate', 'type': 'iso-8601'}, - 'storage_profile': {'key': 'properties.storageProfile', 'type': 'StorageProfile'}, - 'replication_role': {'key': 'properties.replicationRole', 'type': 'str'}, - 'master_server_id': {'key': 'properties.masterServerId', 'type': 'str'}, - 'replica_capacity': {'key': 'properties.replicaCapacity', 'type': 'int'}, - 'public_network_access': {'key': 'properties.publicNetworkAccess', 'type': 'str'}, - 'private_endpoint_connections': {'key': 'properties.privateEndpointConnections', 'type': '[ServerPrivateEndpointConnection]'}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "location": {"required": True}, + "byok_enforcement": {"readonly": True}, + "replica_capacity": {"minimum": 0}, + "private_endpoint_connections": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "location": {"key": "location", "type": "str"}, + "identity": {"key": "identity", "type": "ResourceIdentity"}, + "sku": {"key": "sku", "type": "Sku"}, + "administrator_login": {"key": "properties.administratorLogin", "type": "str"}, + "version": {"key": "properties.version", "type": "str"}, + "ssl_enforcement": {"key": "properties.sslEnforcement", "type": "str"}, + "minimal_tls_version": {"key": "properties.minimalTlsVersion", "type": "str"}, + "byok_enforcement": {"key": "properties.byokEnforcement", "type": "str"}, + "infrastructure_encryption": {"key": "properties.infrastructureEncryption", "type": "str"}, + "user_visible_state": {"key": "properties.userVisibleState", "type": "str"}, + "fully_qualified_domain_name": {"key": "properties.fullyQualifiedDomainName", "type": "str"}, + "earliest_restore_date": {"key": "properties.earliestRestoreDate", "type": "iso-8601"}, + "storage_profile": {"key": "properties.storageProfile", "type": "StorageProfile"}, + "replication_role": {"key": "properties.replicationRole", "type": "str"}, + "master_server_id": {"key": "properties.masterServerId", "type": "str"}, + "replica_capacity": {"key": "properties.replicaCapacity", "type": "int"}, + "public_network_access": {"key": "properties.publicNetworkAccess", "type": "str"}, + "private_endpoint_connections": { + "key": "properties.privateEndpointConnections", + "type": "[ServerPrivateEndpointConnection]", + }, } def __init__( @@ -1935,9 +1806,9 @@ def __init__( **kwargs ): """ - :keyword tags: A set of tags. Resource tags. + :keyword tags: Resource tags. :paramtype tags: dict[str, str] - :keyword location: Required. The geo-location where the resource lives. + :keyword location: The geo-location where the resource lives. Required. :paramtype location: str :keyword identity: The Azure Active Directory identity of the server. :paramtype identity: ~azure.mgmt.rdbms.mysql.models.ResourceIdentity @@ -1946,20 +1817,20 @@ def __init__( :keyword administrator_login: The administrator's login name of a server. Can only be specified when the server is being created (and is required for creation). :paramtype administrator_login: str - :keyword version: Server version. Known values are: "5.6", "5.7", "8.0". + :keyword version: Server version. Known values are: "5.6", "5.7", and "8.0". :paramtype version: str or ~azure.mgmt.rdbms.mysql.models.ServerVersion :keyword ssl_enforcement: Enable ssl enforcement or not when connect to server. Known values - are: "Enabled", "Disabled". + are: "Enabled" and "Disabled". :paramtype ssl_enforcement: str or ~azure.mgmt.rdbms.mysql.models.SslEnforcementEnum :keyword minimal_tls_version: Enforce a minimal Tls version for the server. Known values are: - "TLS1_0", "TLS1_1", "TLS1_2", "TLSEnforcementDisabled". + "TLS1_0", "TLS1_1", "TLS1_2", and "TLSEnforcementDisabled". :paramtype minimal_tls_version: str or ~azure.mgmt.rdbms.mysql.models.MinimalTlsVersionEnum :keyword infrastructure_encryption: Status showing whether the server enabled infrastructure - encryption. Known values are: "Enabled", "Disabled". + encryption. Known values are: "Enabled" and "Disabled". :paramtype infrastructure_encryption: str or ~azure.mgmt.rdbms.mysql.models.InfrastructureEncryption :keyword user_visible_state: A state of a server that is visible to user. Known values are: - "Ready", "Dropping", "Disabled", "Inaccessible". + "Ready", "Dropping", "Disabled", and "Inaccessible". :paramtype user_visible_state: str or ~azure.mgmt.rdbms.mysql.models.ServerState :keyword fully_qualified_domain_name: The fully qualified domain name of a server. :paramtype fully_qualified_domain_name: str @@ -1975,10 +1846,10 @@ def __init__( :paramtype replica_capacity: int :keyword public_network_access: Whether or not public network access is allowed for this server. Value is optional but if passed in, must be 'Enabled' or 'Disabled'. Known values are: - "Enabled", "Disabled". + "Enabled" and "Disabled". :paramtype public_network_access: str or ~azure.mgmt.rdbms.mysql.models.PublicNetworkAccessEnum """ - super(Server, self).__init__(tags=tags, location=location, **kwargs) + super().__init__(tags=tags, location=location, **kwargs) self.identity = identity self.sku = sku self.administrator_login = administrator_login @@ -2011,8 +1882,7 @@ class ServerAdministratorResource(ProxyResource): :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts". :vartype type: str - :ivar administrator_type: The type of administrator. The only acceptable values to pass in are - None and "ActiveDirectory". The default value is None. + :ivar administrator_type: The type of administrator. Default value is "ActiveDirectory". :vartype administrator_type: str :ivar login: The server administrator login account name. :vartype login: str @@ -2023,19 +1893,19 @@ class ServerAdministratorResource(ProxyResource): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'administrator_type': {'key': 'properties.administratorType', 'type': 'str'}, - 'login': {'key': 'properties.login', 'type': 'str'}, - 'sid': {'key': 'properties.sid', 'type': 'str'}, - 'tenant_id': {'key': 'properties.tenantId', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "administrator_type": {"key": "properties.administratorType", "type": "str"}, + "login": {"key": "properties.login", "type": "str"}, + "sid": {"key": "properties.sid", "type": "str"}, + "tenant_id": {"key": "properties.tenantId", "type": "str"}, } def __init__( @@ -2048,8 +1918,7 @@ def __init__( **kwargs ): """ - :keyword administrator_type: The type of administrator. The only acceptable values to pass in - are None and "ActiveDirectory". The default value is None. + :keyword administrator_type: The type of administrator. Default value is "ActiveDirectory". :paramtype administrator_type: str :keyword login: The server administrator login account name. :paramtype login: str @@ -2058,14 +1927,14 @@ def __init__( :keyword tenant_id: The server Active Directory Administrator tenant id. :paramtype tenant_id: str """ - super(ServerAdministratorResource, self).__init__(**kwargs) + super().__init__(**kwargs) self.administrator_type = administrator_type self.login = login self.sid = sid self.tenant_id = tenant_id -class ServerAdministratorResourceListResult(msrest.serialization.Model): +class ServerAdministratorResourceListResult(_serialization.Model): """The response to a list Active Directory Administrators request. :ivar value: The list of server Active Directory Administrators for the server. @@ -2073,24 +1942,19 @@ class ServerAdministratorResourceListResult(msrest.serialization.Model): """ _attribute_map = { - 'value': {'key': 'value', 'type': '[ServerAdministratorResource]'}, + "value": {"key": "value", "type": "[ServerAdministratorResource]"}, } - def __init__( - self, - *, - value: Optional[List["_models.ServerAdministratorResource"]] = None, - **kwargs - ): + def __init__(self, *, value: Optional[List["_models.ServerAdministratorResource"]] = None, **kwargs): """ :keyword value: The list of server Active Directory Administrators for the server. :paramtype value: list[~azure.mgmt.rdbms.mysql.models.ServerAdministratorResource] """ - super(ServerAdministratorResourceListResult, self).__init__(**kwargs) + super().__init__(**kwargs) self.value = value -class ServerForCreate(msrest.serialization.Model): +class ServerForCreate(_serialization.Model): """Represents a server to be created. All required parameters must be populated in order to send to Azure. @@ -2099,25 +1963,25 @@ class ServerForCreate(msrest.serialization.Model): :vartype identity: ~azure.mgmt.rdbms.mysql.models.ResourceIdentity :ivar sku: The SKU (pricing tier) of the server. :vartype sku: ~azure.mgmt.rdbms.mysql.models.Sku - :ivar properties: Required. Properties of the server. + :ivar properties: Properties of the server. Required. :vartype properties: ~azure.mgmt.rdbms.mysql.models.ServerPropertiesForCreate - :ivar location: Required. The location the resource resides in. + :ivar location: The location the resource resides in. Required. :vartype location: str - :ivar tags: A set of tags. Application-specific metadata in the form of key-value pairs. + :ivar tags: Application-specific metadata in the form of key-value pairs. :vartype tags: dict[str, str] """ _validation = { - 'properties': {'required': True}, - 'location': {'required': True}, + "properties": {"required": True}, + "location": {"required": True}, } _attribute_map = { - 'identity': {'key': 'identity', 'type': 'ResourceIdentity'}, - 'sku': {'key': 'sku', 'type': 'Sku'}, - 'properties': {'key': 'properties', 'type': 'ServerPropertiesForCreate'}, - 'location': {'key': 'location', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '{str}'}, + "identity": {"key": "identity", "type": "ResourceIdentity"}, + "sku": {"key": "sku", "type": "Sku"}, + "properties": {"key": "properties", "type": "ServerPropertiesForCreate"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, } def __init__( @@ -2135,14 +1999,14 @@ def __init__( :paramtype identity: ~azure.mgmt.rdbms.mysql.models.ResourceIdentity :keyword sku: The SKU (pricing tier) of the server. :paramtype sku: ~azure.mgmt.rdbms.mysql.models.Sku - :keyword properties: Required. Properties of the server. + :keyword properties: Properties of the server. Required. :paramtype properties: ~azure.mgmt.rdbms.mysql.models.ServerPropertiesForCreate - :keyword location: Required. The location the resource resides in. + :keyword location: The location the resource resides in. Required. :paramtype location: str - :keyword tags: A set of tags. Application-specific metadata in the form of key-value pairs. + :keyword tags: Application-specific metadata in the form of key-value pairs. :paramtype tags: dict[str, str] """ - super(ServerForCreate, self).__init__(**kwargs) + super().__init__(**kwargs) self.identity = identity self.sku = sku self.properties = properties @@ -2165,7 +2029,7 @@ class ServerKey(ProxyResource): :vartype type: str :ivar kind: Kind of encryption protector used to protect the key. :vartype kind: str - :ivar server_key_type: The key type like 'AzureKeyVault'. Known values are: "AzureKeyVault". + :ivar server_key_type: The key type like 'AzureKeyVault'. "AzureKeyVault" :vartype server_key_type: str or ~azure.mgmt.rdbms.mysql.models.ServerKeyType :ivar uri: The URI of the key. :vartype uri: str @@ -2174,21 +2038,21 @@ class ServerKey(ProxyResource): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'kind': {'readonly': True}, - 'creation_date': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "kind": {"readonly": True}, + "creation_date": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'kind': {'key': 'kind', 'type': 'str'}, - 'server_key_type': {'key': 'properties.serverKeyType', 'type': 'str'}, - 'uri': {'key': 'properties.uri', 'type': 'str'}, - 'creation_date': {'key': 'properties.creationDate', 'type': 'iso-8601'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "kind": {"key": "kind", "type": "str"}, + "server_key_type": {"key": "properties.serverKeyType", "type": "str"}, + "uri": {"key": "properties.uri", "type": "str"}, + "creation_date": {"key": "properties.creationDate", "type": "iso-8601"}, } def __init__( @@ -2199,19 +2063,19 @@ def __init__( **kwargs ): """ - :keyword server_key_type: The key type like 'AzureKeyVault'. Known values are: "AzureKeyVault". + :keyword server_key_type: The key type like 'AzureKeyVault'. "AzureKeyVault" :paramtype server_key_type: str or ~azure.mgmt.rdbms.mysql.models.ServerKeyType :keyword uri: The URI of the key. :paramtype uri: str """ - super(ServerKey, self).__init__(**kwargs) + super().__init__(**kwargs) self.kind = None self.server_key_type = server_key_type self.uri = uri self.creation_date = None -class ServerKeyListResult(msrest.serialization.Model): +class ServerKeyListResult(_serialization.Model): """A list of MySQL Server keys. Variables are only populated by the server, and will be ignored when sending a request. @@ -2223,27 +2087,23 @@ class ServerKeyListResult(msrest.serialization.Model): """ _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, + "value": {"readonly": True}, + "next_link": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[ServerKey]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[ServerKey]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(ServerKeyListResult, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.value = None self.next_link = None -class ServerListResult(msrest.serialization.Model): +class ServerListResult(_serialization.Model): """A list of servers. :ivar value: The list of servers. @@ -2251,24 +2111,19 @@ class ServerListResult(msrest.serialization.Model): """ _attribute_map = { - 'value': {'key': 'value', 'type': '[Server]'}, + "value": {"key": "value", "type": "[Server]"}, } - def __init__( - self, - *, - value: Optional[List["_models.Server"]] = None, - **kwargs - ): + def __init__(self, *, value: Optional[List["_models.Server"]] = None, **kwargs): """ :keyword value: The list of servers. :paramtype value: list[~azure.mgmt.rdbms.mysql.models.Server] """ - super(ServerListResult, self).__init__(**kwargs) + super().__init__(**kwargs) self.value = value -class ServerPrivateEndpointConnection(msrest.serialization.Model): +class ServerPrivateEndpointConnection(_serialization.Model): """A private endpoint connection under a server. Variables are only populated by the server, and will be ignored when sending a request. @@ -2280,27 +2135,23 @@ class ServerPrivateEndpointConnection(msrest.serialization.Model): """ _validation = { - 'id': {'readonly': True}, - 'properties': {'readonly': True}, + "id": {"readonly": True}, + "properties": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'properties': {'key': 'properties', 'type': 'ServerPrivateEndpointConnectionProperties'}, + "id": {"key": "id", "type": "str"}, + "properties": {"key": "properties", "type": "ServerPrivateEndpointConnectionProperties"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(ServerPrivateEndpointConnection, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.id = None self.properties = None -class ServerPrivateEndpointConnectionProperties(msrest.serialization.Model): +class ServerPrivateEndpointConnectionProperties(_serialization.Model): """Properties of a private endpoint connection. Variables are only populated by the server, and will be ignored when sending a request. @@ -2312,26 +2163,31 @@ class ServerPrivateEndpointConnectionProperties(msrest.serialization.Model): :vartype private_link_service_connection_state: ~azure.mgmt.rdbms.mysql.models.ServerPrivateLinkServiceConnectionStateProperty :ivar provisioning_state: State of the private endpoint connection. Known values are: - "Approving", "Ready", "Dropping", "Failed", "Rejecting". + "Approving", "Ready", "Dropping", "Failed", and "Rejecting". :vartype provisioning_state: str or ~azure.mgmt.rdbms.mysql.models.PrivateEndpointProvisioningState """ _validation = { - 'provisioning_state': {'readonly': True}, + "provisioning_state": {"readonly": True}, } _attribute_map = { - 'private_endpoint': {'key': 'privateEndpoint', 'type': 'PrivateEndpointProperty'}, - 'private_link_service_connection_state': {'key': 'privateLinkServiceConnectionState', 'type': 'ServerPrivateLinkServiceConnectionStateProperty'}, - 'provisioning_state': {'key': 'provisioningState', 'type': 'str'}, + "private_endpoint": {"key": "privateEndpoint", "type": "PrivateEndpointProperty"}, + "private_link_service_connection_state": { + "key": "privateLinkServiceConnectionState", + "type": "ServerPrivateLinkServiceConnectionStateProperty", + }, + "provisioning_state": {"key": "provisioningState", "type": "str"}, } def __init__( self, *, private_endpoint: Optional["_models.PrivateEndpointProperty"] = None, - private_link_service_connection_state: Optional["_models.ServerPrivateLinkServiceConnectionStateProperty"] = None, + private_link_service_connection_state: Optional[ + "_models.ServerPrivateLinkServiceConnectionStateProperty" + ] = None, **kwargs ): """ @@ -2342,110 +2198,111 @@ def __init__( :paramtype private_link_service_connection_state: ~azure.mgmt.rdbms.mysql.models.ServerPrivateLinkServiceConnectionStateProperty """ - super(ServerPrivateEndpointConnectionProperties, self).__init__(**kwargs) + super().__init__(**kwargs) self.private_endpoint = private_endpoint self.private_link_service_connection_state = private_link_service_connection_state self.provisioning_state = None -class ServerPrivateLinkServiceConnectionStateProperty(msrest.serialization.Model): +class ServerPrivateLinkServiceConnectionStateProperty(_serialization.Model): """ServerPrivateLinkServiceConnectionStateProperty. 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 status: Required. The private link service connection status. Known values are: - "Approved", "Pending", "Rejected", "Disconnected". + :ivar status: The private link service connection status. Required. Known values are: + "Approved", "Pending", "Rejected", and "Disconnected". :vartype status: str or ~azure.mgmt.rdbms.mysql.models.PrivateLinkServiceConnectionStateStatus - :ivar description: Required. The private link service connection description. + :ivar description: The private link service connection description. Required. :vartype description: str - :ivar actions_required: The actions required for private link service connection. Known values - are: "None". + :ivar actions_required: The actions required for private link service connection. "None" :vartype actions_required: str or ~azure.mgmt.rdbms.mysql.models.PrivateLinkServiceConnectionStateActionsRequire """ _validation = { - 'status': {'required': True}, - 'description': {'required': True}, - 'actions_required': {'readonly': True}, + "status": {"required": True}, + "description": {"required": True}, + "actions_required": {"readonly": True}, } _attribute_map = { - 'status': {'key': 'status', 'type': 'str'}, - 'description': {'key': 'description', 'type': 'str'}, - 'actions_required': {'key': 'actionsRequired', 'type': 'str'}, + "status": {"key": "status", "type": "str"}, + "description": {"key": "description", "type": "str"}, + "actions_required": {"key": "actionsRequired", "type": "str"}, } def __init__( - self, - *, - status: Union[str, "_models.PrivateLinkServiceConnectionStateStatus"], - description: str, - **kwargs + self, *, status: Union[str, "_models.PrivateLinkServiceConnectionStateStatus"], description: str, **kwargs ): """ - :keyword status: Required. The private link service connection status. Known values are: - "Approved", "Pending", "Rejected", "Disconnected". + :keyword status: The private link service connection status. Required. Known values are: + "Approved", "Pending", "Rejected", and "Disconnected". :paramtype status: str or ~azure.mgmt.rdbms.mysql.models.PrivateLinkServiceConnectionStateStatus - :keyword description: Required. The private link service connection description. + :keyword description: The private link service connection description. Required. :paramtype description: str """ - super(ServerPrivateLinkServiceConnectionStateProperty, self).__init__(**kwargs) + super().__init__(**kwargs) self.status = status self.description = description self.actions_required = None -class ServerPropertiesForCreate(msrest.serialization.Model): +class ServerPropertiesForCreate(_serialization.Model): """The properties used to create a new server. - You probably want to use the sub-classes and not this class directly. Known - sub-classes are: ServerPropertiesForDefaultCreate, ServerPropertiesForGeoRestore, ServerPropertiesForRestore, ServerPropertiesForReplica. + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + ServerPropertiesForDefaultCreate, ServerPropertiesForGeoRestore, ServerPropertiesForRestore, + ServerPropertiesForReplica All required parameters must be populated in order to send to Azure. - :ivar version: Server version. Known values are: "5.6", "5.7", "8.0". + :ivar version: Server version. Known values are: "5.6", "5.7", and "8.0". :vartype version: str or ~azure.mgmt.rdbms.mysql.models.ServerVersion :ivar ssl_enforcement: Enable ssl enforcement or not when connect to server. Known values are: - "Enabled", "Disabled". + "Enabled" and "Disabled". :vartype ssl_enforcement: str or ~azure.mgmt.rdbms.mysql.models.SslEnforcementEnum :ivar minimal_tls_version: Enforce a minimal Tls version for the server. Known values are: - "TLS1_0", "TLS1_1", "TLS1_2", "TLSEnforcementDisabled". + "TLS1_0", "TLS1_1", "TLS1_2", and "TLSEnforcementDisabled". :vartype minimal_tls_version: str or ~azure.mgmt.rdbms.mysql.models.MinimalTlsVersionEnum :ivar infrastructure_encryption: Status showing whether the server enabled infrastructure - encryption. Known values are: "Enabled", "Disabled". + encryption. Known values are: "Enabled" and "Disabled". :vartype infrastructure_encryption: str or ~azure.mgmt.rdbms.mysql.models.InfrastructureEncryption :ivar public_network_access: Whether or not public network access is allowed for this server. Value is optional but if passed in, must be 'Enabled' or 'Disabled'. Known values are: - "Enabled", "Disabled". + "Enabled" and "Disabled". :vartype public_network_access: str or ~azure.mgmt.rdbms.mysql.models.PublicNetworkAccessEnum :ivar storage_profile: Storage profile of a server. :vartype storage_profile: ~azure.mgmt.rdbms.mysql.models.StorageProfile - :ivar create_mode: Required. The mode to create a new server.Constant filled by server. Known - values are: "Default", "PointInTimeRestore", "GeoRestore", "Replica". + :ivar create_mode: The mode to create a new server. Required. Known values are: "Default", + "PointInTimeRestore", "GeoRestore", and "Replica". :vartype create_mode: str or ~azure.mgmt.rdbms.mysql.models.CreateMode """ _validation = { - 'create_mode': {'required': True}, + "create_mode": {"required": True}, } _attribute_map = { - 'version': {'key': 'version', 'type': 'str'}, - 'ssl_enforcement': {'key': 'sslEnforcement', 'type': 'str'}, - 'minimal_tls_version': {'key': 'minimalTlsVersion', 'type': 'str'}, - 'infrastructure_encryption': {'key': 'infrastructureEncryption', 'type': 'str'}, - 'public_network_access': {'key': 'publicNetworkAccess', 'type': 'str'}, - 'storage_profile': {'key': 'storageProfile', 'type': 'StorageProfile'}, - 'create_mode': {'key': 'createMode', 'type': 'str'}, + "version": {"key": "version", "type": "str"}, + "ssl_enforcement": {"key": "sslEnforcement", "type": "str"}, + "minimal_tls_version": {"key": "minimalTlsVersion", "type": "str"}, + "infrastructure_encryption": {"key": "infrastructureEncryption", "type": "str"}, + "public_network_access": {"key": "publicNetworkAccess", "type": "str"}, + "storage_profile": {"key": "storageProfile", "type": "StorageProfile"}, + "create_mode": {"key": "createMode", "type": "str"}, } _subtype_map = { - 'create_mode': {'Default': 'ServerPropertiesForDefaultCreate', 'GeoRestore': 'ServerPropertiesForGeoRestore', 'PointInTimeRestore': 'ServerPropertiesForRestore', 'Replica': 'ServerPropertiesForReplica'} + "create_mode": { + "Default": "ServerPropertiesForDefaultCreate", + "GeoRestore": "ServerPropertiesForGeoRestore", + "PointInTimeRestore": "ServerPropertiesForRestore", + "Replica": "ServerPropertiesForReplica", + } } def __init__( @@ -2460,26 +2317,26 @@ def __init__( **kwargs ): """ - :keyword version: Server version. Known values are: "5.6", "5.7", "8.0". + :keyword version: Server version. Known values are: "5.6", "5.7", and "8.0". :paramtype version: str or ~azure.mgmt.rdbms.mysql.models.ServerVersion :keyword ssl_enforcement: Enable ssl enforcement or not when connect to server. Known values - are: "Enabled", "Disabled". + are: "Enabled" and "Disabled". :paramtype ssl_enforcement: str or ~azure.mgmt.rdbms.mysql.models.SslEnforcementEnum :keyword minimal_tls_version: Enforce a minimal Tls version for the server. Known values are: - "TLS1_0", "TLS1_1", "TLS1_2", "TLSEnforcementDisabled". + "TLS1_0", "TLS1_1", "TLS1_2", and "TLSEnforcementDisabled". :paramtype minimal_tls_version: str or ~azure.mgmt.rdbms.mysql.models.MinimalTlsVersionEnum :keyword infrastructure_encryption: Status showing whether the server enabled infrastructure - encryption. Known values are: "Enabled", "Disabled". + encryption. Known values are: "Enabled" and "Disabled". :paramtype infrastructure_encryption: str or ~azure.mgmt.rdbms.mysql.models.InfrastructureEncryption :keyword public_network_access: Whether or not public network access is allowed for this server. Value is optional but if passed in, must be 'Enabled' or 'Disabled'. Known values are: - "Enabled", "Disabled". + "Enabled" and "Disabled". :paramtype public_network_access: str or ~azure.mgmt.rdbms.mysql.models.PublicNetworkAccessEnum :keyword storage_profile: Storage profile of a server. :paramtype storage_profile: ~azure.mgmt.rdbms.mysql.models.StorageProfile """ - super(ServerPropertiesForCreate, self).__init__(**kwargs) + super().__init__(**kwargs) self.version = version self.ssl_enforcement = ssl_enforcement self.minimal_tls_version = minimal_tls_version @@ -2494,51 +2351,51 @@ class ServerPropertiesForDefaultCreate(ServerPropertiesForCreate): All required parameters must be populated in order to send to Azure. - :ivar version: Server version. Known values are: "5.6", "5.7", "8.0". + :ivar version: Server version. Known values are: "5.6", "5.7", and "8.0". :vartype version: str or ~azure.mgmt.rdbms.mysql.models.ServerVersion :ivar ssl_enforcement: Enable ssl enforcement or not when connect to server. Known values are: - "Enabled", "Disabled". + "Enabled" and "Disabled". :vartype ssl_enforcement: str or ~azure.mgmt.rdbms.mysql.models.SslEnforcementEnum :ivar minimal_tls_version: Enforce a minimal Tls version for the server. Known values are: - "TLS1_0", "TLS1_1", "TLS1_2", "TLSEnforcementDisabled". + "TLS1_0", "TLS1_1", "TLS1_2", and "TLSEnforcementDisabled". :vartype minimal_tls_version: str or ~azure.mgmt.rdbms.mysql.models.MinimalTlsVersionEnum :ivar infrastructure_encryption: Status showing whether the server enabled infrastructure - encryption. Known values are: "Enabled", "Disabled". + encryption. Known values are: "Enabled" and "Disabled". :vartype infrastructure_encryption: str or ~azure.mgmt.rdbms.mysql.models.InfrastructureEncryption :ivar public_network_access: Whether or not public network access is allowed for this server. Value is optional but if passed in, must be 'Enabled' or 'Disabled'. Known values are: - "Enabled", "Disabled". + "Enabled" and "Disabled". :vartype public_network_access: str or ~azure.mgmt.rdbms.mysql.models.PublicNetworkAccessEnum :ivar storage_profile: Storage profile of a server. :vartype storage_profile: ~azure.mgmt.rdbms.mysql.models.StorageProfile - :ivar create_mode: Required. The mode to create a new server.Constant filled by server. Known - values are: "Default", "PointInTimeRestore", "GeoRestore", "Replica". + :ivar create_mode: The mode to create a new server. Required. Known values are: "Default", + "PointInTimeRestore", "GeoRestore", and "Replica". :vartype create_mode: str or ~azure.mgmt.rdbms.mysql.models.CreateMode - :ivar administrator_login: Required. The administrator's login name of a server. Can only be - specified when the server is being created (and is required for creation). The login name is - required when updating password. + :ivar administrator_login: The administrator's login name of a server. Can only be specified + when the server is being created (and is required for creation). The login name is required + when updating password. Required. :vartype administrator_login: str - :ivar administrator_login_password: Required. The password of the administrator login. + :ivar administrator_login_password: The password of the administrator login. Required. :vartype administrator_login_password: str """ _validation = { - 'create_mode': {'required': True}, - 'administrator_login': {'required': True}, - 'administrator_login_password': {'required': True}, + "create_mode": {"required": True}, + "administrator_login": {"required": True}, + "administrator_login_password": {"required": True}, } _attribute_map = { - 'version': {'key': 'version', 'type': 'str'}, - 'ssl_enforcement': {'key': 'sslEnforcement', 'type': 'str'}, - 'minimal_tls_version': {'key': 'minimalTlsVersion', 'type': 'str'}, - 'infrastructure_encryption': {'key': 'infrastructureEncryption', 'type': 'str'}, - 'public_network_access': {'key': 'publicNetworkAccess', 'type': 'str'}, - 'storage_profile': {'key': 'storageProfile', 'type': 'StorageProfile'}, - 'create_mode': {'key': 'createMode', 'type': 'str'}, - 'administrator_login': {'key': 'administratorLogin', 'type': 'str'}, - 'administrator_login_password': {'key': 'administratorLoginPassword', 'type': 'str'}, + "version": {"key": "version", "type": "str"}, + "ssl_enforcement": {"key": "sslEnforcement", "type": "str"}, + "minimal_tls_version": {"key": "minimalTlsVersion", "type": "str"}, + "infrastructure_encryption": {"key": "infrastructureEncryption", "type": "str"}, + "public_network_access": {"key": "publicNetworkAccess", "type": "str"}, + "storage_profile": {"key": "storageProfile", "type": "StorageProfile"}, + "create_mode": {"key": "createMode", "type": "str"}, + "administrator_login": {"key": "administratorLogin", "type": "str"}, + "administrator_login_password": {"key": "administratorLoginPassword", "type": "str"}, } def __init__( @@ -2555,33 +2412,41 @@ def __init__( **kwargs ): """ - :keyword version: Server version. Known values are: "5.6", "5.7", "8.0". + :keyword version: Server version. Known values are: "5.6", "5.7", and "8.0". :paramtype version: str or ~azure.mgmt.rdbms.mysql.models.ServerVersion :keyword ssl_enforcement: Enable ssl enforcement or not when connect to server. Known values - are: "Enabled", "Disabled". + are: "Enabled" and "Disabled". :paramtype ssl_enforcement: str or ~azure.mgmt.rdbms.mysql.models.SslEnforcementEnum :keyword minimal_tls_version: Enforce a minimal Tls version for the server. Known values are: - "TLS1_0", "TLS1_1", "TLS1_2", "TLSEnforcementDisabled". + "TLS1_0", "TLS1_1", "TLS1_2", and "TLSEnforcementDisabled". :paramtype minimal_tls_version: str or ~azure.mgmt.rdbms.mysql.models.MinimalTlsVersionEnum :keyword infrastructure_encryption: Status showing whether the server enabled infrastructure - encryption. Known values are: "Enabled", "Disabled". + encryption. Known values are: "Enabled" and "Disabled". :paramtype infrastructure_encryption: str or ~azure.mgmt.rdbms.mysql.models.InfrastructureEncryption :keyword public_network_access: Whether or not public network access is allowed for this server. Value is optional but if passed in, must be 'Enabled' or 'Disabled'. Known values are: - "Enabled", "Disabled". + "Enabled" and "Disabled". :paramtype public_network_access: str or ~azure.mgmt.rdbms.mysql.models.PublicNetworkAccessEnum :keyword storage_profile: Storage profile of a server. :paramtype storage_profile: ~azure.mgmt.rdbms.mysql.models.StorageProfile - :keyword administrator_login: Required. The administrator's login name of a server. Can only be - specified when the server is being created (and is required for creation). The login name is - required when updating password. + :keyword administrator_login: The administrator's login name of a server. Can only be specified + when the server is being created (and is required for creation). The login name is required + when updating password. Required. :paramtype administrator_login: str - :keyword administrator_login_password: Required. The password of the administrator login. + :keyword administrator_login_password: The password of the administrator login. Required. :paramtype administrator_login_password: str """ - super(ServerPropertiesForDefaultCreate, self).__init__(version=version, ssl_enforcement=ssl_enforcement, minimal_tls_version=minimal_tls_version, infrastructure_encryption=infrastructure_encryption, public_network_access=public_network_access, storage_profile=storage_profile, **kwargs) - self.create_mode = 'Default' # type: str + super().__init__( + version=version, + ssl_enforcement=ssl_enforcement, + minimal_tls_version=minimal_tls_version, + infrastructure_encryption=infrastructure_encryption, + public_network_access=public_network_access, + storage_profile=storage_profile, + **kwargs + ) + self.create_mode = "Default" # type: str self.administrator_login = administrator_login self.administrator_login_password = administrator_login_password @@ -2591,45 +2456,45 @@ class ServerPropertiesForGeoRestore(ServerPropertiesForCreate): All required parameters must be populated in order to send to Azure. - :ivar version: Server version. Known values are: "5.6", "5.7", "8.0". + :ivar version: Server version. Known values are: "5.6", "5.7", and "8.0". :vartype version: str or ~azure.mgmt.rdbms.mysql.models.ServerVersion :ivar ssl_enforcement: Enable ssl enforcement or not when connect to server. Known values are: - "Enabled", "Disabled". + "Enabled" and "Disabled". :vartype ssl_enforcement: str or ~azure.mgmt.rdbms.mysql.models.SslEnforcementEnum :ivar minimal_tls_version: Enforce a minimal Tls version for the server. Known values are: - "TLS1_0", "TLS1_1", "TLS1_2", "TLSEnforcementDisabled". + "TLS1_0", "TLS1_1", "TLS1_2", and "TLSEnforcementDisabled". :vartype minimal_tls_version: str or ~azure.mgmt.rdbms.mysql.models.MinimalTlsVersionEnum :ivar infrastructure_encryption: Status showing whether the server enabled infrastructure - encryption. Known values are: "Enabled", "Disabled". + encryption. Known values are: "Enabled" and "Disabled". :vartype infrastructure_encryption: str or ~azure.mgmt.rdbms.mysql.models.InfrastructureEncryption :ivar public_network_access: Whether or not public network access is allowed for this server. Value is optional but if passed in, must be 'Enabled' or 'Disabled'. Known values are: - "Enabled", "Disabled". + "Enabled" and "Disabled". :vartype public_network_access: str or ~azure.mgmt.rdbms.mysql.models.PublicNetworkAccessEnum :ivar storage_profile: Storage profile of a server. :vartype storage_profile: ~azure.mgmt.rdbms.mysql.models.StorageProfile - :ivar create_mode: Required. The mode to create a new server.Constant filled by server. Known - values are: "Default", "PointInTimeRestore", "GeoRestore", "Replica". + :ivar create_mode: The mode to create a new server. Required. Known values are: "Default", + "PointInTimeRestore", "GeoRestore", and "Replica". :vartype create_mode: str or ~azure.mgmt.rdbms.mysql.models.CreateMode - :ivar source_server_id: Required. The source server id to restore from. + :ivar source_server_id: The source server id to restore from. Required. :vartype source_server_id: str """ _validation = { - 'create_mode': {'required': True}, - 'source_server_id': {'required': True}, + "create_mode": {"required": True}, + "source_server_id": {"required": True}, } _attribute_map = { - 'version': {'key': 'version', 'type': 'str'}, - 'ssl_enforcement': {'key': 'sslEnforcement', 'type': 'str'}, - 'minimal_tls_version': {'key': 'minimalTlsVersion', 'type': 'str'}, - 'infrastructure_encryption': {'key': 'infrastructureEncryption', 'type': 'str'}, - 'public_network_access': {'key': 'publicNetworkAccess', 'type': 'str'}, - 'storage_profile': {'key': 'storageProfile', 'type': 'StorageProfile'}, - 'create_mode': {'key': 'createMode', 'type': 'str'}, - 'source_server_id': {'key': 'sourceServerId', 'type': 'str'}, + "version": {"key": "version", "type": "str"}, + "ssl_enforcement": {"key": "sslEnforcement", "type": "str"}, + "minimal_tls_version": {"key": "minimalTlsVersion", "type": "str"}, + "infrastructure_encryption": {"key": "infrastructureEncryption", "type": "str"}, + "public_network_access": {"key": "publicNetworkAccess", "type": "str"}, + "storage_profile": {"key": "storageProfile", "type": "StorageProfile"}, + "create_mode": {"key": "createMode", "type": "str"}, + "source_server_id": {"key": "sourceServerId", "type": "str"}, } def __init__( @@ -2645,29 +2510,37 @@ def __init__( **kwargs ): """ - :keyword version: Server version. Known values are: "5.6", "5.7", "8.0". + :keyword version: Server version. Known values are: "5.6", "5.7", and "8.0". :paramtype version: str or ~azure.mgmt.rdbms.mysql.models.ServerVersion :keyword ssl_enforcement: Enable ssl enforcement or not when connect to server. Known values - are: "Enabled", "Disabled". + are: "Enabled" and "Disabled". :paramtype ssl_enforcement: str or ~azure.mgmt.rdbms.mysql.models.SslEnforcementEnum :keyword minimal_tls_version: Enforce a minimal Tls version for the server. Known values are: - "TLS1_0", "TLS1_1", "TLS1_2", "TLSEnforcementDisabled". + "TLS1_0", "TLS1_1", "TLS1_2", and "TLSEnforcementDisabled". :paramtype minimal_tls_version: str or ~azure.mgmt.rdbms.mysql.models.MinimalTlsVersionEnum :keyword infrastructure_encryption: Status showing whether the server enabled infrastructure - encryption. Known values are: "Enabled", "Disabled". + encryption. Known values are: "Enabled" and "Disabled". :paramtype infrastructure_encryption: str or ~azure.mgmt.rdbms.mysql.models.InfrastructureEncryption :keyword public_network_access: Whether or not public network access is allowed for this server. Value is optional but if passed in, must be 'Enabled' or 'Disabled'. Known values are: - "Enabled", "Disabled". + "Enabled" and "Disabled". :paramtype public_network_access: str or ~azure.mgmt.rdbms.mysql.models.PublicNetworkAccessEnum :keyword storage_profile: Storage profile of a server. :paramtype storage_profile: ~azure.mgmt.rdbms.mysql.models.StorageProfile - :keyword source_server_id: Required. The source server id to restore from. + :keyword source_server_id: The source server id to restore from. Required. :paramtype source_server_id: str """ - super(ServerPropertiesForGeoRestore, self).__init__(version=version, ssl_enforcement=ssl_enforcement, minimal_tls_version=minimal_tls_version, infrastructure_encryption=infrastructure_encryption, public_network_access=public_network_access, storage_profile=storage_profile, **kwargs) - self.create_mode = 'GeoRestore' # type: str + super().__init__( + version=version, + ssl_enforcement=ssl_enforcement, + minimal_tls_version=minimal_tls_version, + infrastructure_encryption=infrastructure_encryption, + public_network_access=public_network_access, + storage_profile=storage_profile, + **kwargs + ) + self.create_mode = "GeoRestore" # type: str self.source_server_id = source_server_id @@ -2676,45 +2549,45 @@ class ServerPropertiesForReplica(ServerPropertiesForCreate): All required parameters must be populated in order to send to Azure. - :ivar version: Server version. Known values are: "5.6", "5.7", "8.0". + :ivar version: Server version. Known values are: "5.6", "5.7", and "8.0". :vartype version: str or ~azure.mgmt.rdbms.mysql.models.ServerVersion :ivar ssl_enforcement: Enable ssl enforcement or not when connect to server. Known values are: - "Enabled", "Disabled". + "Enabled" and "Disabled". :vartype ssl_enforcement: str or ~azure.mgmt.rdbms.mysql.models.SslEnforcementEnum :ivar minimal_tls_version: Enforce a minimal Tls version for the server. Known values are: - "TLS1_0", "TLS1_1", "TLS1_2", "TLSEnforcementDisabled". + "TLS1_0", "TLS1_1", "TLS1_2", and "TLSEnforcementDisabled". :vartype minimal_tls_version: str or ~azure.mgmt.rdbms.mysql.models.MinimalTlsVersionEnum :ivar infrastructure_encryption: Status showing whether the server enabled infrastructure - encryption. Known values are: "Enabled", "Disabled". + encryption. Known values are: "Enabled" and "Disabled". :vartype infrastructure_encryption: str or ~azure.mgmt.rdbms.mysql.models.InfrastructureEncryption :ivar public_network_access: Whether or not public network access is allowed for this server. Value is optional but if passed in, must be 'Enabled' or 'Disabled'. Known values are: - "Enabled", "Disabled". + "Enabled" and "Disabled". :vartype public_network_access: str or ~azure.mgmt.rdbms.mysql.models.PublicNetworkAccessEnum :ivar storage_profile: Storage profile of a server. :vartype storage_profile: ~azure.mgmt.rdbms.mysql.models.StorageProfile - :ivar create_mode: Required. The mode to create a new server.Constant filled by server. Known - values are: "Default", "PointInTimeRestore", "GeoRestore", "Replica". + :ivar create_mode: The mode to create a new server. Required. Known values are: "Default", + "PointInTimeRestore", "GeoRestore", and "Replica". :vartype create_mode: str or ~azure.mgmt.rdbms.mysql.models.CreateMode - :ivar source_server_id: Required. The master server id to create replica from. + :ivar source_server_id: The master server id to create replica from. Required. :vartype source_server_id: str """ _validation = { - 'create_mode': {'required': True}, - 'source_server_id': {'required': True}, + "create_mode": {"required": True}, + "source_server_id": {"required": True}, } _attribute_map = { - 'version': {'key': 'version', 'type': 'str'}, - 'ssl_enforcement': {'key': 'sslEnforcement', 'type': 'str'}, - 'minimal_tls_version': {'key': 'minimalTlsVersion', 'type': 'str'}, - 'infrastructure_encryption': {'key': 'infrastructureEncryption', 'type': 'str'}, - 'public_network_access': {'key': 'publicNetworkAccess', 'type': 'str'}, - 'storage_profile': {'key': 'storageProfile', 'type': 'StorageProfile'}, - 'create_mode': {'key': 'createMode', 'type': 'str'}, - 'source_server_id': {'key': 'sourceServerId', 'type': 'str'}, + "version": {"key": "version", "type": "str"}, + "ssl_enforcement": {"key": "sslEnforcement", "type": "str"}, + "minimal_tls_version": {"key": "minimalTlsVersion", "type": "str"}, + "infrastructure_encryption": {"key": "infrastructureEncryption", "type": "str"}, + "public_network_access": {"key": "publicNetworkAccess", "type": "str"}, + "storage_profile": {"key": "storageProfile", "type": "StorageProfile"}, + "create_mode": {"key": "createMode", "type": "str"}, + "source_server_id": {"key": "sourceServerId", "type": "str"}, } def __init__( @@ -2730,29 +2603,37 @@ def __init__( **kwargs ): """ - :keyword version: Server version. Known values are: "5.6", "5.7", "8.0". + :keyword version: Server version. Known values are: "5.6", "5.7", and "8.0". :paramtype version: str or ~azure.mgmt.rdbms.mysql.models.ServerVersion :keyword ssl_enforcement: Enable ssl enforcement or not when connect to server. Known values - are: "Enabled", "Disabled". + are: "Enabled" and "Disabled". :paramtype ssl_enforcement: str or ~azure.mgmt.rdbms.mysql.models.SslEnforcementEnum :keyword minimal_tls_version: Enforce a minimal Tls version for the server. Known values are: - "TLS1_0", "TLS1_1", "TLS1_2", "TLSEnforcementDisabled". + "TLS1_0", "TLS1_1", "TLS1_2", and "TLSEnforcementDisabled". :paramtype minimal_tls_version: str or ~azure.mgmt.rdbms.mysql.models.MinimalTlsVersionEnum :keyword infrastructure_encryption: Status showing whether the server enabled infrastructure - encryption. Known values are: "Enabled", "Disabled". + encryption. Known values are: "Enabled" and "Disabled". :paramtype infrastructure_encryption: str or ~azure.mgmt.rdbms.mysql.models.InfrastructureEncryption :keyword public_network_access: Whether or not public network access is allowed for this server. Value is optional but if passed in, must be 'Enabled' or 'Disabled'. Known values are: - "Enabled", "Disabled". + "Enabled" and "Disabled". :paramtype public_network_access: str or ~azure.mgmt.rdbms.mysql.models.PublicNetworkAccessEnum :keyword storage_profile: Storage profile of a server. :paramtype storage_profile: ~azure.mgmt.rdbms.mysql.models.StorageProfile - :keyword source_server_id: Required. The master server id to create replica from. + :keyword source_server_id: The master server id to create replica from. Required. :paramtype source_server_id: str """ - super(ServerPropertiesForReplica, self).__init__(version=version, ssl_enforcement=ssl_enforcement, minimal_tls_version=minimal_tls_version, infrastructure_encryption=infrastructure_encryption, public_network_access=public_network_access, storage_profile=storage_profile, **kwargs) - self.create_mode = 'Replica' # type: str + super().__init__( + version=version, + ssl_enforcement=ssl_enforcement, + minimal_tls_version=minimal_tls_version, + infrastructure_encryption=infrastructure_encryption, + public_network_access=public_network_access, + storage_profile=storage_profile, + **kwargs + ) + self.create_mode = "Replica" # type: str self.source_server_id = source_server_id @@ -2761,50 +2642,50 @@ class ServerPropertiesForRestore(ServerPropertiesForCreate): All required parameters must be populated in order to send to Azure. - :ivar version: Server version. Known values are: "5.6", "5.7", "8.0". + :ivar version: Server version. Known values are: "5.6", "5.7", and "8.0". :vartype version: str or ~azure.mgmt.rdbms.mysql.models.ServerVersion :ivar ssl_enforcement: Enable ssl enforcement or not when connect to server. Known values are: - "Enabled", "Disabled". + "Enabled" and "Disabled". :vartype ssl_enforcement: str or ~azure.mgmt.rdbms.mysql.models.SslEnforcementEnum :ivar minimal_tls_version: Enforce a minimal Tls version for the server. Known values are: - "TLS1_0", "TLS1_1", "TLS1_2", "TLSEnforcementDisabled". + "TLS1_0", "TLS1_1", "TLS1_2", and "TLSEnforcementDisabled". :vartype minimal_tls_version: str or ~azure.mgmt.rdbms.mysql.models.MinimalTlsVersionEnum :ivar infrastructure_encryption: Status showing whether the server enabled infrastructure - encryption. Known values are: "Enabled", "Disabled". + encryption. Known values are: "Enabled" and "Disabled". :vartype infrastructure_encryption: str or ~azure.mgmt.rdbms.mysql.models.InfrastructureEncryption :ivar public_network_access: Whether or not public network access is allowed for this server. Value is optional but if passed in, must be 'Enabled' or 'Disabled'. Known values are: - "Enabled", "Disabled". + "Enabled" and "Disabled". :vartype public_network_access: str or ~azure.mgmt.rdbms.mysql.models.PublicNetworkAccessEnum :ivar storage_profile: Storage profile of a server. :vartype storage_profile: ~azure.mgmt.rdbms.mysql.models.StorageProfile - :ivar create_mode: Required. The mode to create a new server.Constant filled by server. Known - values are: "Default", "PointInTimeRestore", "GeoRestore", "Replica". + :ivar create_mode: The mode to create a new server. Required. Known values are: "Default", + "PointInTimeRestore", "GeoRestore", and "Replica". :vartype create_mode: str or ~azure.mgmt.rdbms.mysql.models.CreateMode - :ivar source_server_id: Required. The source server id to restore from. + :ivar source_server_id: The source server id to restore from. Required. :vartype source_server_id: str - :ivar restore_point_in_time: Required. Restore point creation time (ISO8601 format), specifying - the time to restore from. + :ivar restore_point_in_time: Restore point creation time (ISO8601 format), specifying the time + to restore from. Required. :vartype restore_point_in_time: ~datetime.datetime """ _validation = { - 'create_mode': {'required': True}, - 'source_server_id': {'required': True}, - 'restore_point_in_time': {'required': True}, + "create_mode": {"required": True}, + "source_server_id": {"required": True}, + "restore_point_in_time": {"required": True}, } _attribute_map = { - 'version': {'key': 'version', 'type': 'str'}, - 'ssl_enforcement': {'key': 'sslEnforcement', 'type': 'str'}, - 'minimal_tls_version': {'key': 'minimalTlsVersion', 'type': 'str'}, - 'infrastructure_encryption': {'key': 'infrastructureEncryption', 'type': 'str'}, - 'public_network_access': {'key': 'publicNetworkAccess', 'type': 'str'}, - 'storage_profile': {'key': 'storageProfile', 'type': 'StorageProfile'}, - 'create_mode': {'key': 'createMode', 'type': 'str'}, - 'source_server_id': {'key': 'sourceServerId', 'type': 'str'}, - 'restore_point_in_time': {'key': 'restorePointInTime', 'type': 'iso-8601'}, + "version": {"key": "version", "type": "str"}, + "ssl_enforcement": {"key": "sslEnforcement", "type": "str"}, + "minimal_tls_version": {"key": "minimalTlsVersion", "type": "str"}, + "infrastructure_encryption": {"key": "infrastructureEncryption", "type": "str"}, + "public_network_access": {"key": "publicNetworkAccess", "type": "str"}, + "storage_profile": {"key": "storageProfile", "type": "StorageProfile"}, + "create_mode": {"key": "createMode", "type": "str"}, + "source_server_id": {"key": "sourceServerId", "type": "str"}, + "restore_point_in_time": {"key": "restorePointInTime", "type": "iso-8601"}, } def __init__( @@ -2821,32 +2702,40 @@ def __init__( **kwargs ): """ - :keyword version: Server version. Known values are: "5.6", "5.7", "8.0". + :keyword version: Server version. Known values are: "5.6", "5.7", and "8.0". :paramtype version: str or ~azure.mgmt.rdbms.mysql.models.ServerVersion :keyword ssl_enforcement: Enable ssl enforcement or not when connect to server. Known values - are: "Enabled", "Disabled". + are: "Enabled" and "Disabled". :paramtype ssl_enforcement: str or ~azure.mgmt.rdbms.mysql.models.SslEnforcementEnum :keyword minimal_tls_version: Enforce a minimal Tls version for the server. Known values are: - "TLS1_0", "TLS1_1", "TLS1_2", "TLSEnforcementDisabled". + "TLS1_0", "TLS1_1", "TLS1_2", and "TLSEnforcementDisabled". :paramtype minimal_tls_version: str or ~azure.mgmt.rdbms.mysql.models.MinimalTlsVersionEnum :keyword infrastructure_encryption: Status showing whether the server enabled infrastructure - encryption. Known values are: "Enabled", "Disabled". + encryption. Known values are: "Enabled" and "Disabled". :paramtype infrastructure_encryption: str or ~azure.mgmt.rdbms.mysql.models.InfrastructureEncryption :keyword public_network_access: Whether or not public network access is allowed for this server. Value is optional but if passed in, must be 'Enabled' or 'Disabled'. Known values are: - "Enabled", "Disabled". + "Enabled" and "Disabled". :paramtype public_network_access: str or ~azure.mgmt.rdbms.mysql.models.PublicNetworkAccessEnum :keyword storage_profile: Storage profile of a server. :paramtype storage_profile: ~azure.mgmt.rdbms.mysql.models.StorageProfile - :keyword source_server_id: Required. The source server id to restore from. + :keyword source_server_id: The source server id to restore from. Required. :paramtype source_server_id: str - :keyword restore_point_in_time: Required. Restore point creation time (ISO8601 format), - specifying the time to restore from. + :keyword restore_point_in_time: Restore point creation time (ISO8601 format), specifying the + time to restore from. Required. :paramtype restore_point_in_time: ~datetime.datetime """ - super(ServerPropertiesForRestore, self).__init__(version=version, ssl_enforcement=ssl_enforcement, minimal_tls_version=minimal_tls_version, infrastructure_encryption=infrastructure_encryption, public_network_access=public_network_access, storage_profile=storage_profile, **kwargs) - self.create_mode = 'PointInTimeRestore' # type: str + super().__init__( + version=version, + ssl_enforcement=ssl_enforcement, + minimal_tls_version=minimal_tls_version, + infrastructure_encryption=infrastructure_encryption, + public_network_access=public_network_access, + storage_profile=storage_profile, + **kwargs + ) + self.create_mode = "PointInTimeRestore" # type: str self.source_server_id = source_server_id self.restore_point_in_time = restore_point_in_time @@ -2865,7 +2754,7 @@ class ServerSecurityAlertPolicy(ProxyResource): "Microsoft.Storage/storageAccounts". :vartype type: str :ivar state: Specifies the state of the policy, whether it is enabled or disabled. Known values - are: "Enabled", "Disabled". + are: "Enabled" and "Disabled". :vartype state: str or ~azure.mgmt.rdbms.mysql.models.ServerSecurityAlertPolicyState :ivar disabled_alerts: Specifies an array of alerts that are disabled. Allowed values are: Sql_Injection, Sql_Injection_Vulnerability, Access_Anomaly. @@ -2886,22 +2775,22 @@ class ServerSecurityAlertPolicy(ProxyResource): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'state': {'key': 'properties.state', 'type': 'str'}, - 'disabled_alerts': {'key': 'properties.disabledAlerts', 'type': '[str]'}, - 'email_addresses': {'key': 'properties.emailAddresses', 'type': '[str]'}, - 'email_account_admins': {'key': 'properties.emailAccountAdmins', 'type': 'bool'}, - 'storage_endpoint': {'key': 'properties.storageEndpoint', 'type': 'str'}, - 'storage_account_access_key': {'key': 'properties.storageAccountAccessKey', 'type': 'str'}, - 'retention_days': {'key': 'properties.retentionDays', 'type': 'int'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "state": {"key": "properties.state", "type": "str"}, + "disabled_alerts": {"key": "properties.disabledAlerts", "type": "[str]"}, + "email_addresses": {"key": "properties.emailAddresses", "type": "[str]"}, + "email_account_admins": {"key": "properties.emailAccountAdmins", "type": "bool"}, + "storage_endpoint": {"key": "properties.storageEndpoint", "type": "str"}, + "storage_account_access_key": {"key": "properties.storageAccountAccessKey", "type": "str"}, + "retention_days": {"key": "properties.retentionDays", "type": "int"}, } def __init__( @@ -2918,7 +2807,7 @@ def __init__( ): """ :keyword state: Specifies the state of the policy, whether it is enabled or disabled. Known - values are: "Enabled", "Disabled". + values are: "Enabled" and "Disabled". :paramtype state: str or ~azure.mgmt.rdbms.mysql.models.ServerSecurityAlertPolicyState :keyword disabled_alerts: Specifies an array of alerts that are disabled. Allowed values are: Sql_Injection, Sql_Injection_Vulnerability, Access_Anomaly. @@ -2938,7 +2827,7 @@ def __init__( logs. :paramtype retention_days: int """ - super(ServerSecurityAlertPolicy, self).__init__(**kwargs) + super().__init__(**kwargs) self.state = state self.disabled_alerts = disabled_alerts self.email_addresses = email_addresses @@ -2948,7 +2837,7 @@ def __init__( self.retention_days = retention_days -class ServerSecurityAlertPolicyListResult(msrest.serialization.Model): +class ServerSecurityAlertPolicyListResult(_serialization.Model): """A list of the server's security alert policies. Variables are only populated by the server, and will be ignored when sending a request. @@ -2960,66 +2849,62 @@ class ServerSecurityAlertPolicyListResult(msrest.serialization.Model): """ _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, + "value": {"readonly": True}, + "next_link": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[ServerSecurityAlertPolicy]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[ServerSecurityAlertPolicy]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(ServerSecurityAlertPolicyListResult, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.value = None self.next_link = None -class ServerUpdateParameters(msrest.serialization.Model): +class ServerUpdateParameters(_serialization.Model): """Parameters allowed to update for a server. :ivar identity: The Azure Active Directory identity of the server. :vartype identity: ~azure.mgmt.rdbms.mysql.models.ResourceIdentity :ivar sku: The SKU (pricing tier) of the server. :vartype sku: ~azure.mgmt.rdbms.mysql.models.Sku - :ivar tags: A set of tags. Application-specific metadata in the form of key-value pairs. + :ivar tags: Application-specific metadata in the form of key-value pairs. :vartype tags: dict[str, str] :ivar storage_profile: Storage profile of a server. :vartype storage_profile: ~azure.mgmt.rdbms.mysql.models.StorageProfile :ivar administrator_login_password: The password of the administrator login. :vartype administrator_login_password: str - :ivar version: The version of a server. Known values are: "5.6", "5.7", "8.0". + :ivar version: The version of a server. Known values are: "5.6", "5.7", and "8.0". :vartype version: str or ~azure.mgmt.rdbms.mysql.models.ServerVersion :ivar ssl_enforcement: Enable ssl enforcement or not when connect to server. Known values are: - "Enabled", "Disabled". + "Enabled" and "Disabled". :vartype ssl_enforcement: str or ~azure.mgmt.rdbms.mysql.models.SslEnforcementEnum :ivar minimal_tls_version: Enforce a minimal Tls version for the server. Known values are: - "TLS1_0", "TLS1_1", "TLS1_2", "TLSEnforcementDisabled". + "TLS1_0", "TLS1_1", "TLS1_2", and "TLSEnforcementDisabled". :vartype minimal_tls_version: str or ~azure.mgmt.rdbms.mysql.models.MinimalTlsVersionEnum :ivar public_network_access: Whether or not public network access is allowed for this server. Value is optional but if passed in, must be 'Enabled' or 'Disabled'. Known values are: - "Enabled", "Disabled". + "Enabled" and "Disabled". :vartype public_network_access: str or ~azure.mgmt.rdbms.mysql.models.PublicNetworkAccessEnum :ivar replication_role: The replication role of the server. :vartype replication_role: str """ _attribute_map = { - 'identity': {'key': 'identity', 'type': 'ResourceIdentity'}, - 'sku': {'key': 'sku', 'type': 'Sku'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - 'storage_profile': {'key': 'properties.storageProfile', 'type': 'StorageProfile'}, - 'administrator_login_password': {'key': 'properties.administratorLoginPassword', 'type': 'str'}, - 'version': {'key': 'properties.version', 'type': 'str'}, - 'ssl_enforcement': {'key': 'properties.sslEnforcement', 'type': 'str'}, - 'minimal_tls_version': {'key': 'properties.minimalTlsVersion', 'type': 'str'}, - 'public_network_access': {'key': 'properties.publicNetworkAccess', 'type': 'str'}, - 'replication_role': {'key': 'properties.replicationRole', 'type': 'str'}, + "identity": {"key": "identity", "type": "ResourceIdentity"}, + "sku": {"key": "sku", "type": "Sku"}, + "tags": {"key": "tags", "type": "{str}"}, + "storage_profile": {"key": "properties.storageProfile", "type": "StorageProfile"}, + "administrator_login_password": {"key": "properties.administratorLoginPassword", "type": "str"}, + "version": {"key": "properties.version", "type": "str"}, + "ssl_enforcement": {"key": "properties.sslEnforcement", "type": "str"}, + "minimal_tls_version": {"key": "properties.minimalTlsVersion", "type": "str"}, + "public_network_access": {"key": "properties.publicNetworkAccess", "type": "str"}, + "replication_role": {"key": "properties.replicationRole", "type": "str"}, } def __init__( @@ -3042,28 +2927,28 @@ def __init__( :paramtype identity: ~azure.mgmt.rdbms.mysql.models.ResourceIdentity :keyword sku: The SKU (pricing tier) of the server. :paramtype sku: ~azure.mgmt.rdbms.mysql.models.Sku - :keyword tags: A set of tags. Application-specific metadata in the form of key-value pairs. + :keyword tags: Application-specific metadata in the form of key-value pairs. :paramtype tags: dict[str, str] :keyword storage_profile: Storage profile of a server. :paramtype storage_profile: ~azure.mgmt.rdbms.mysql.models.StorageProfile :keyword administrator_login_password: The password of the administrator login. :paramtype administrator_login_password: str - :keyword version: The version of a server. Known values are: "5.6", "5.7", "8.0". + :keyword version: The version of a server. Known values are: "5.6", "5.7", and "8.0". :paramtype version: str or ~azure.mgmt.rdbms.mysql.models.ServerVersion :keyword ssl_enforcement: Enable ssl enforcement or not when connect to server. Known values - are: "Enabled", "Disabled". + are: "Enabled" and "Disabled". :paramtype ssl_enforcement: str or ~azure.mgmt.rdbms.mysql.models.SslEnforcementEnum :keyword minimal_tls_version: Enforce a minimal Tls version for the server. Known values are: - "TLS1_0", "TLS1_1", "TLS1_2", "TLSEnforcementDisabled". + "TLS1_0", "TLS1_1", "TLS1_2", and "TLSEnforcementDisabled". :paramtype minimal_tls_version: str or ~azure.mgmt.rdbms.mysql.models.MinimalTlsVersionEnum :keyword public_network_access: Whether or not public network access is allowed for this server. Value is optional but if passed in, must be 'Enabled' or 'Disabled'. Known values are: - "Enabled", "Disabled". + "Enabled" and "Disabled". :paramtype public_network_access: str or ~azure.mgmt.rdbms.mysql.models.PublicNetworkAccessEnum :keyword replication_role: The replication role of the server. :paramtype replication_role: str """ - super(ServerUpdateParameters, self).__init__(**kwargs) + super().__init__(**kwargs) self.identity = identity self.sku = sku self.tags = tags @@ -3076,7 +2961,7 @@ def __init__( self.replication_role = replication_role -class ServerUpgradeParameters(msrest.serialization.Model): +class ServerUpgradeParameters(_serialization.Model): """ServerUpgradeParameters. :ivar target_server_version: Represents an server storage profile. @@ -3084,33 +2969,28 @@ class ServerUpgradeParameters(msrest.serialization.Model): """ _attribute_map = { - 'target_server_version': {'key': 'properties.targetServerVersion', 'type': 'str'}, + "target_server_version": {"key": "properties.targetServerVersion", "type": "str"}, } - def __init__( - self, - *, - target_server_version: Optional[str] = None, - **kwargs - ): + def __init__(self, *, target_server_version: Optional[str] = None, **kwargs): """ :keyword target_server_version: Represents an server storage profile. :paramtype target_server_version: str """ - super(ServerUpgradeParameters, self).__init__(**kwargs) + super().__init__(**kwargs) self.target_server_version = target_server_version -class Sku(msrest.serialization.Model): +class Sku(_serialization.Model): """Billing information related properties of a server. All required parameters must be populated in order to send to Azure. - :ivar name: Required. The name of the sku, typically, tier + family + cores, e.g. B_Gen4_1, - GP_Gen5_8. + :ivar name: The name of the sku, typically, tier + family + cores, e.g. B_Gen4_1, GP_Gen5_8. + Required. :vartype name: str :ivar tier: The tier of the particular SKU, e.g. Basic. Known values are: "Basic", - "GeneralPurpose", "MemoryOptimized". + "GeneralPurpose", and "MemoryOptimized". :vartype tier: str or ~azure.mgmt.rdbms.mysql.models.SkuTier :ivar capacity: The scale up/out capacity, representing server's compute units. :vartype capacity: int @@ -3121,16 +3001,16 @@ class Sku(msrest.serialization.Model): """ _validation = { - 'name': {'required': True}, - 'capacity': {'minimum': 0}, + "name": {"required": True}, + "capacity": {"minimum": 0}, } _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'tier': {'key': 'tier', 'type': 'str'}, - 'capacity': {'key': 'capacity', 'type': 'int'}, - 'size': {'key': 'size', 'type': 'str'}, - 'family': {'key': 'family', 'type': 'str'}, + "name": {"key": "name", "type": "str"}, + "tier": {"key": "tier", "type": "str"}, + "capacity": {"key": "capacity", "type": "int"}, + "size": {"key": "size", "type": "str"}, + "family": {"key": "family", "type": "str"}, } def __init__( @@ -3144,11 +3024,11 @@ def __init__( **kwargs ): """ - :keyword name: Required. The name of the sku, typically, tier + family + cores, e.g. B_Gen4_1, - GP_Gen5_8. + :keyword name: The name of the sku, typically, tier + family + cores, e.g. B_Gen4_1, GP_Gen5_8. + Required. :paramtype name: str :keyword tier: The tier of the particular SKU, e.g. Basic. Known values are: "Basic", - "GeneralPurpose", "MemoryOptimized". + "GeneralPurpose", and "MemoryOptimized". :paramtype tier: str or ~azure.mgmt.rdbms.mysql.models.SkuTier :keyword capacity: The scale up/out capacity, representing server's compute units. :paramtype capacity: int @@ -3157,7 +3037,7 @@ def __init__( :keyword family: The family of hardware. :paramtype family: str """ - super(Sku, self).__init__(**kwargs) + super().__init__(**kwargs) self.name = name self.tier = tier self.capacity = capacity @@ -3165,25 +3045,25 @@ def __init__( self.family = family -class StorageProfile(msrest.serialization.Model): +class StorageProfile(_serialization.Model): """Storage Profile properties of a server. :ivar backup_retention_days: Backup retention days for the server. :vartype backup_retention_days: int :ivar geo_redundant_backup: Enable Geo-redundant or not for server backup. Known values are: - "Enabled", "Disabled". + "Enabled" and "Disabled". :vartype geo_redundant_backup: str or ~azure.mgmt.rdbms.mysql.models.GeoRedundantBackup :ivar storage_mb: Max storage allowed for a server. :vartype storage_mb: int - :ivar storage_autogrow: Enable Storage Auto Grow. Known values are: "Enabled", "Disabled". + :ivar storage_autogrow: Enable Storage Auto Grow. Known values are: "Enabled" and "Disabled". :vartype storage_autogrow: str or ~azure.mgmt.rdbms.mysql.models.StorageAutogrow """ _attribute_map = { - 'backup_retention_days': {'key': 'backupRetentionDays', 'type': 'int'}, - 'geo_redundant_backup': {'key': 'geoRedundantBackup', 'type': 'str'}, - 'storage_mb': {'key': 'storageMB', 'type': 'int'}, - 'storage_autogrow': {'key': 'storageAutogrow', 'type': 'str'}, + "backup_retention_days": {"key": "backupRetentionDays", "type": "int"}, + "geo_redundant_backup": {"key": "geoRedundantBackup", "type": "str"}, + "storage_mb": {"key": "storageMB", "type": "int"}, + "storage_autogrow": {"key": "storageAutogrow", "type": "str"}, } def __init__( @@ -3199,80 +3079,76 @@ def __init__( :keyword backup_retention_days: Backup retention days for the server. :paramtype backup_retention_days: int :keyword geo_redundant_backup: Enable Geo-redundant or not for server backup. Known values are: - "Enabled", "Disabled". + "Enabled" and "Disabled". :paramtype geo_redundant_backup: str or ~azure.mgmt.rdbms.mysql.models.GeoRedundantBackup :keyword storage_mb: Max storage allowed for a server. :paramtype storage_mb: int - :keyword storage_autogrow: Enable Storage Auto Grow. Known values are: "Enabled", "Disabled". + :keyword storage_autogrow: Enable Storage Auto Grow. Known values are: "Enabled" and + "Disabled". :paramtype storage_autogrow: str or ~azure.mgmt.rdbms.mysql.models.StorageAutogrow """ - super(StorageProfile, self).__init__(**kwargs) + super().__init__(**kwargs) self.backup_retention_days = backup_retention_days self.geo_redundant_backup = geo_redundant_backup self.storage_mb = storage_mb self.storage_autogrow = storage_autogrow -class TagsObject(msrest.serialization.Model): +class TagsObject(_serialization.Model): """Tags object for patch operations. - :ivar tags: A set of tags. Resource tags. + :ivar tags: Resource tags. :vartype tags: dict[str, str] """ _attribute_map = { - 'tags': {'key': 'tags', 'type': '{str}'}, + "tags": {"key": "tags", "type": "{str}"}, } - def __init__( - self, - *, - tags: Optional[Dict[str, str]] = None, - **kwargs - ): + def __init__(self, *, tags: Optional[Dict[str, str]] = None, **kwargs): """ - :keyword tags: A set of tags. Resource tags. + :keyword tags: Resource tags. :paramtype tags: dict[str, str] """ - super(TagsObject, self).__init__(**kwargs) + super().__init__(**kwargs) self.tags = tags -class TopQueryStatisticsInput(msrest.serialization.Model): +class TopQueryStatisticsInput(_serialization.Model): """Input to get top query statistics. All required parameters must be populated in order to send to Azure. - :ivar number_of_top_queries: Required. Max number of top queries to return. + :ivar number_of_top_queries: Max number of top queries to return. Required. :vartype number_of_top_queries: int - :ivar aggregation_function: Required. Aggregation function name. + :ivar aggregation_function: Aggregation function name. Required. :vartype aggregation_function: str - :ivar observed_metric: Required. Observed metric name. + :ivar observed_metric: Observed metric name. Required. :vartype observed_metric: str - :ivar observation_start_time: Required. Observation start time. + :ivar observation_start_time: Observation start time. Required. :vartype observation_start_time: ~datetime.datetime - :ivar observation_end_time: Required. Observation end time. + :ivar observation_end_time: Observation end time. Required. :vartype observation_end_time: ~datetime.datetime - :ivar aggregation_window: Required. Aggregation interval type in ISO 8601 format. + :ivar aggregation_window: Aggregation interval type in ISO 8601 format. Required. :vartype aggregation_window: str """ _validation = { - 'number_of_top_queries': {'required': True}, - 'aggregation_function': {'required': True}, - 'observed_metric': {'required': True}, - 'observation_start_time': {'required': True}, - 'observation_end_time': {'required': True}, - 'aggregation_window': {'required': True}, + "number_of_top_queries": {"required": True}, + "aggregation_function": {"required": True}, + "observed_metric": {"required": True}, + "observation_start_time": {"required": True}, + "observation_end_time": {"required": True}, + "aggregation_window": {"required": True}, } _attribute_map = { - 'number_of_top_queries': {'key': 'properties.numberOfTopQueries', 'type': 'int'}, - 'aggregation_function': {'key': 'properties.aggregationFunction', 'type': 'str'}, - 'observed_metric': {'key': 'properties.observedMetric', 'type': 'str'}, - 'observation_start_time': {'key': 'properties.observationStartTime', 'type': 'iso-8601'}, - 'observation_end_time': {'key': 'properties.observationEndTime', 'type': 'iso-8601'}, - 'aggregation_window': {'key': 'properties.aggregationWindow', 'type': 'str'}, + "number_of_top_queries": {"key": "properties.numberOfTopQueries", "type": "int"}, + "aggregation_function": {"key": "properties.aggregationFunction", "type": "str"}, + "observed_metric": {"key": "properties.observedMetric", "type": "str"}, + "observation_start_time": {"key": "properties.observationStartTime", "type": "iso-8601"}, + "observation_end_time": {"key": "properties.observationEndTime", "type": "iso-8601"}, + "aggregation_window": {"key": "properties.aggregationWindow", "type": "str"}, } def __init__( @@ -3287,20 +3163,20 @@ def __init__( **kwargs ): """ - :keyword number_of_top_queries: Required. Max number of top queries to return. + :keyword number_of_top_queries: Max number of top queries to return. Required. :paramtype number_of_top_queries: int - :keyword aggregation_function: Required. Aggregation function name. + :keyword aggregation_function: Aggregation function name. Required. :paramtype aggregation_function: str - :keyword observed_metric: Required. Observed metric name. + :keyword observed_metric: Observed metric name. Required. :paramtype observed_metric: str - :keyword observation_start_time: Required. Observation start time. + :keyword observation_start_time: Observation start time. Required. :paramtype observation_start_time: ~datetime.datetime - :keyword observation_end_time: Required. Observation end time. + :keyword observation_end_time: Observation end time. Required. :paramtype observation_end_time: ~datetime.datetime - :keyword aggregation_window: Required. Aggregation interval type in ISO 8601 format. + :keyword aggregation_window: Aggregation interval type in ISO 8601 format. Required. :paramtype aggregation_window: str """ - super(TopQueryStatisticsInput, self).__init__(**kwargs) + super().__init__(**kwargs) self.number_of_top_queries = number_of_top_queries self.aggregation_function = aggregation_function self.observed_metric = observed_metric @@ -3309,7 +3185,7 @@ def __init__( self.aggregation_window = aggregation_window -class TopQueryStatisticsResultList(msrest.serialization.Model): +class TopQueryStatisticsResultList(_serialization.Model): """A list of query statistics. Variables are only populated by the server, and will be ignored when sending a request. @@ -3321,22 +3197,18 @@ class TopQueryStatisticsResultList(msrest.serialization.Model): """ _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, + "value": {"readonly": True}, + "next_link": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[QueryStatistic]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[QueryStatistic]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(TopQueryStatisticsResultList, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.value = None self.next_link = None @@ -3360,24 +3232,24 @@ class VirtualNetworkRule(ProxyResource): vnet service endpoint enabled. :vartype ignore_missing_vnet_service_endpoint: bool :ivar state: Virtual Network Rule State. Known values are: "Initializing", "InProgress", - "Ready", "Deleting", "Unknown". + "Ready", "Deleting", and "Unknown". :vartype state: str or ~azure.mgmt.rdbms.mysql.models.VirtualNetworkRuleState """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'state': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "state": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'virtual_network_subnet_id': {'key': 'properties.virtualNetworkSubnetId', 'type': 'str'}, - 'ignore_missing_vnet_service_endpoint': {'key': 'properties.ignoreMissingVnetServiceEndpoint', 'type': 'bool'}, - 'state': {'key': 'properties.state', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "virtual_network_subnet_id": {"key": "properties.virtualNetworkSubnetId", "type": "str"}, + "ignore_missing_vnet_service_endpoint": {"key": "properties.ignoreMissingVnetServiceEndpoint", "type": "bool"}, + "state": {"key": "properties.state", "type": "str"}, } def __init__( @@ -3394,13 +3266,13 @@ def __init__( has vnet service endpoint enabled. :paramtype ignore_missing_vnet_service_endpoint: bool """ - super(VirtualNetworkRule, self).__init__(**kwargs) + super().__init__(**kwargs) self.virtual_network_subnet_id = virtual_network_subnet_id self.ignore_missing_vnet_service_endpoint = ignore_missing_vnet_service_endpoint self.state = None -class VirtualNetworkRuleListResult(msrest.serialization.Model): +class VirtualNetworkRuleListResult(_serialization.Model): """A list of virtual network rules. Variables are only populated by the server, and will be ignored when sending a request. @@ -3412,27 +3284,23 @@ class VirtualNetworkRuleListResult(msrest.serialization.Model): """ _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, + "value": {"readonly": True}, + "next_link": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[VirtualNetworkRule]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[VirtualNetworkRule]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(VirtualNetworkRuleListResult, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.value = None self.next_link = None -class WaitStatistic(ProxyResource): +class WaitStatistic(ProxyResource): # pylint: disable=too-many-instance-attributes """Represents a Wait Statistic. Variables are only populated by the server, and will be ignored when sending a request. @@ -3454,36 +3322,36 @@ class WaitStatistic(ProxyResource): :ivar event_type_name: Wait event type name. :vartype event_type_name: str :ivar query_id: Database query identifier. - :vartype query_id: long + :vartype query_id: int :ivar database_name: Database Name. :vartype database_name: str :ivar user_id: Database user identifier. - :vartype user_id: long + :vartype user_id: int :ivar count: Wait event count observed in this time interval. - :vartype count: long + :vartype count: int :ivar total_time_in_ms: Total time of wait in milliseconds in this time interval. :vartype total_time_in_ms: float """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'start_time': {'key': 'properties.startTime', 'type': 'iso-8601'}, - 'end_time': {'key': 'properties.endTime', 'type': 'iso-8601'}, - 'event_name': {'key': 'properties.eventName', 'type': 'str'}, - 'event_type_name': {'key': 'properties.eventTypeName', 'type': 'str'}, - 'query_id': {'key': 'properties.queryId', 'type': 'long'}, - 'database_name': {'key': 'properties.databaseName', 'type': 'str'}, - 'user_id': {'key': 'properties.userId', 'type': 'long'}, - 'count': {'key': 'properties.count', 'type': 'long'}, - 'total_time_in_ms': {'key': 'properties.totalTimeInMs', 'type': 'float'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "start_time": {"key": "properties.startTime", "type": "iso-8601"}, + "end_time": {"key": "properties.endTime", "type": "iso-8601"}, + "event_name": {"key": "properties.eventName", "type": "str"}, + "event_type_name": {"key": "properties.eventTypeName", "type": "str"}, + "query_id": {"key": "properties.queryId", "type": "int"}, + "database_name": {"key": "properties.databaseName", "type": "str"}, + "user_id": {"key": "properties.userId", "type": "int"}, + "count": {"key": "properties.count", "type": "int"}, + "total_time_in_ms": {"key": "properties.totalTimeInMs", "type": "float"}, } def __init__( @@ -3510,17 +3378,17 @@ def __init__( :keyword event_type_name: Wait event type name. :paramtype event_type_name: str :keyword query_id: Database query identifier. - :paramtype query_id: long + :paramtype query_id: int :keyword database_name: Database Name. :paramtype database_name: str :keyword user_id: Database user identifier. - :paramtype user_id: long + :paramtype user_id: int :keyword count: Wait event count observed in this time interval. - :paramtype count: long + :paramtype count: int :keyword total_time_in_ms: Total time of wait in milliseconds in this time interval. :paramtype total_time_in_ms: float """ - super(WaitStatistic, self).__init__(**kwargs) + super().__init__(**kwargs) self.start_time = start_time self.end_time = end_time self.event_name = event_name @@ -3532,29 +3400,29 @@ def __init__( self.total_time_in_ms = total_time_in_ms -class WaitStatisticsInput(msrest.serialization.Model): +class WaitStatisticsInput(_serialization.Model): """Input to get wait statistics. All required parameters must be populated in order to send to Azure. - :ivar observation_start_time: Required. Observation start time. + :ivar observation_start_time: Observation start time. Required. :vartype observation_start_time: ~datetime.datetime - :ivar observation_end_time: Required. Observation end time. + :ivar observation_end_time: Observation end time. Required. :vartype observation_end_time: ~datetime.datetime - :ivar aggregation_window: Required. Aggregation interval type in ISO 8601 format. + :ivar aggregation_window: Aggregation interval type in ISO 8601 format. Required. :vartype aggregation_window: str """ _validation = { - 'observation_start_time': {'required': True}, - 'observation_end_time': {'required': True}, - 'aggregation_window': {'required': True}, + "observation_start_time": {"required": True}, + "observation_end_time": {"required": True}, + "aggregation_window": {"required": True}, } _attribute_map = { - 'observation_start_time': {'key': 'properties.observationStartTime', 'type': 'iso-8601'}, - 'observation_end_time': {'key': 'properties.observationEndTime', 'type': 'iso-8601'}, - 'aggregation_window': {'key': 'properties.aggregationWindow', 'type': 'str'}, + "observation_start_time": {"key": "properties.observationStartTime", "type": "iso-8601"}, + "observation_end_time": {"key": "properties.observationEndTime", "type": "iso-8601"}, + "aggregation_window": {"key": "properties.aggregationWindow", "type": "str"}, } def __init__( @@ -3566,20 +3434,20 @@ def __init__( **kwargs ): """ - :keyword observation_start_time: Required. Observation start time. + :keyword observation_start_time: Observation start time. Required. :paramtype observation_start_time: ~datetime.datetime - :keyword observation_end_time: Required. Observation end time. + :keyword observation_end_time: Observation end time. Required. :paramtype observation_end_time: ~datetime.datetime - :keyword aggregation_window: Required. Aggregation interval type in ISO 8601 format. + :keyword aggregation_window: Aggregation interval type in ISO 8601 format. Required. :paramtype aggregation_window: str """ - super(WaitStatisticsInput, self).__init__(**kwargs) + super().__init__(**kwargs) self.observation_start_time = observation_start_time self.observation_end_time = observation_end_time self.aggregation_window = aggregation_window -class WaitStatisticsResultList(msrest.serialization.Model): +class WaitStatisticsResultList(_serialization.Model): """A list of wait statistics. Variables are only populated by the server, and will be ignored when sending a request. @@ -3591,21 +3459,17 @@ class WaitStatisticsResultList(msrest.serialization.Model): """ _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, + "value": {"readonly": True}, + "next_link": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[WaitStatistic]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[WaitStatistic]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(WaitStatisticsResultList, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.value = None self.next_link = None diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/models/_my_sql_management_client_enums.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/models/_my_sql_management_client_enums.py index 94a9deb6bcd1..54b079152095 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/models/_my_sql_management_client_enums.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/models/_my_sql_management_client_enums.py @@ -11,21 +11,21 @@ class CreateMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The mode to create a new server. - """ + """The mode to create a new server.""" DEFAULT = "Default" POINT_IN_TIME_RESTORE = "PointInTimeRestore" GEO_RESTORE = "GeoRestore" REPLICA = "Replica" + class GeoRedundantBackup(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Enable Geo-redundant or not for server backup. - """ + """Enable Geo-redundant or not for server backup.""" ENABLED = "Enabled" DISABLED = "Disabled" + class IdentityType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The identity type. Set this to 'SystemAssigned' in order to automatically create and assign an Azure Active Directory principal for the resource. @@ -33,6 +33,7 @@ class IdentityType(str, Enum, metaclass=CaseInsensitiveEnumMeta): SYSTEM_ASSIGNED = "SystemAssigned" + class InfrastructureEncryption(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Add a second layer of encryption for your data using new encryption algorithm which gives additional data protection. Value is optional but if passed in, must be 'Disabled' or @@ -41,29 +42,29 @@ class InfrastructureEncryption(str, Enum, metaclass=CaseInsensitiveEnumMeta): #: Default value for single layer of encryption for data at rest. ENABLED = "Enabled" - #: Additional (2nd) layer of encryption for data at rest. + #: Additional (2nd) layer of encryption for data at rest DISABLED = "Disabled" + class MinimalTlsVersionEnum(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Enforce a minimal Tls version for the server. - """ + """Enforce a minimal Tls version for the server.""" TLS1_0 = "TLS1_0" TLS1_1 = "TLS1_1" TLS1_2 = "TLS1_2" TLS_ENFORCEMENT_DISABLED = "TLSEnforcementDisabled" + class OperationOrigin(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The intended executor of the operation. - """ + """The intended executor of the operation.""" NOT_SPECIFIED = "NotSpecified" USER = "user" SYSTEM = "system" + class PrivateEndpointProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """State of the private endpoint connection. - """ + """State of the private endpoint connection.""" APPROVING = "Approving" READY = "Ready" @@ -71,95 +72,98 @@ class PrivateEndpointProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumM FAILED = "Failed" REJECTING = "Rejecting" + class PrivateLinkServiceConnectionStateActionsRequire(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The actions required for private link service connection. - """ + """The actions required for private link service connection.""" NONE = "None" + class PrivateLinkServiceConnectionStateStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The private link service connection status. - """ + """The private link service connection status.""" APPROVED = "Approved" PENDING = "Pending" REJECTED = "Rejected" DISCONNECTED = "Disconnected" + class PublicNetworkAccessEnum(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Whether or not public network access is allowed for this server. Value is optional but if - passed in, must be 'Enabled' or 'Disabled' + passed in, must be 'Enabled' or 'Disabled'. """ ENABLED = "Enabled" DISABLED = "Disabled" + class QueryPerformanceInsightResetDataResultState(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Indicates result of the operation. - """ + """Indicates result of the operation.""" SUCCEEDED = "Succeeded" FAILED = "Failed" + class SecurityAlertPolicyName(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """SecurityAlertPolicyName.""" DEFAULT = "Default" + class ServerKeyType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The key type like 'AzureKeyVault'. - """ + """The key type like 'AzureKeyVault'.""" AZURE_KEY_VAULT = "AzureKeyVault" + class ServerSecurityAlertPolicyState(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Specifies the state of the policy, whether it is enabled or disabled. - """ + """Specifies the state of the policy, whether it is enabled or disabled.""" ENABLED = "Enabled" DISABLED = "Disabled" + class ServerState(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """A state of a server that is visible to user. - """ + """A state of a server that is visible to user.""" READY = "Ready" DROPPING = "Dropping" DISABLED = "Disabled" INACCESSIBLE = "Inaccessible" + class ServerVersion(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The version of a server. - """ + """The version of a server.""" FIVE6 = "5.6" FIVE7 = "5.7" EIGHT0 = "8.0" + class SkuTier(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The tier of the particular SKU, e.g. Basic. - """ + """The tier of the particular SKU, e.g. Basic.""" BASIC = "Basic" GENERAL_PURPOSE = "GeneralPurpose" MEMORY_OPTIMIZED = "MemoryOptimized" + class SslEnforcementEnum(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Enable ssl enforcement or not when connect to server. - """ + """Enable ssl enforcement or not when connect to server.""" ENABLED = "Enabled" DISABLED = "Disabled" + class StorageAutogrow(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Enable Storage Auto Grow. - """ + """Enable Storage Auto Grow.""" ENABLED = "Enabled" DISABLED = "Disabled" + class VirtualNetworkRuleState(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Virtual Network Rule State - """ + """Virtual Network Rule State.""" INITIALIZING = "Initializing" IN_PROGRESS = "InProgress" diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/models/_patch.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/models/_patch.py index 0ad201a8c586..f7dd32510333 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/models/_patch.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/models/_patch.py @@ -10,6 +10,7 @@ __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. diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/__init__.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/__init__.py index 496637630f04..da47a12bde7b 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/__init__.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/__init__.py @@ -27,8 +27,12 @@ from ._my_sql_management_client_operations import MySQLManagementClientOperationsMixin from ._advisors_operations import AdvisorsOperations from ._recommended_actions_operations import RecommendedActionsOperations -from ._location_based_recommended_action_sessions_operation_status_operations import LocationBasedRecommendedActionSessionsOperationStatusOperations -from ._location_based_recommended_action_sessions_result_operations import LocationBasedRecommendedActionSessionsResultOperations +from ._location_based_recommended_action_sessions_operation_status_operations import ( + LocationBasedRecommendedActionSessionsOperationStatusOperations, +) +from ._location_based_recommended_action_sessions_result_operations import ( + LocationBasedRecommendedActionSessionsResultOperations, +) from ._private_endpoint_connections_operations import PrivateEndpointConnectionsOperations from ._private_link_resources_operations import PrivateLinkResourcesOperations from ._server_keys_operations import ServerKeysOperations @@ -36,33 +40,34 @@ from ._patch import __all__ as _patch_all from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import from ._patch import patch_sdk as _patch_sdk + __all__ = [ - 'ServersOperations', - 'ReplicasOperations', - 'FirewallRulesOperations', - 'VirtualNetworkRulesOperations', - 'DatabasesOperations', - 'ConfigurationsOperations', - 'ServerParametersOperations', - 'LogFilesOperations', - 'ServerAdministratorsOperations', - 'RecoverableServersOperations', - 'ServerBasedPerformanceTierOperations', - 'LocationBasedPerformanceTierOperations', - 'CheckNameAvailabilityOperations', - 'Operations', - 'ServerSecurityAlertPoliciesOperations', - 'QueryTextsOperations', - 'TopQueryStatisticsOperations', - 'WaitStatisticsOperations', - 'MySQLManagementClientOperationsMixin', - 'AdvisorsOperations', - 'RecommendedActionsOperations', - 'LocationBasedRecommendedActionSessionsOperationStatusOperations', - 'LocationBasedRecommendedActionSessionsResultOperations', - 'PrivateEndpointConnectionsOperations', - 'PrivateLinkResourcesOperations', - 'ServerKeysOperations', + "ServersOperations", + "ReplicasOperations", + "FirewallRulesOperations", + "VirtualNetworkRulesOperations", + "DatabasesOperations", + "ConfigurationsOperations", + "ServerParametersOperations", + "LogFilesOperations", + "ServerAdministratorsOperations", + "RecoverableServersOperations", + "ServerBasedPerformanceTierOperations", + "LocationBasedPerformanceTierOperations", + "CheckNameAvailabilityOperations", + "Operations", + "ServerSecurityAlertPoliciesOperations", + "QueryTextsOperations", + "TopQueryStatisticsOperations", + "WaitStatisticsOperations", + "MySQLManagementClientOperationsMixin", + "AdvisorsOperations", + "RecommendedActionsOperations", + "LocationBasedRecommendedActionSessionsOperationStatusOperations", + "LocationBasedRecommendedActionSessionsResultOperations", + "PrivateEndpointConnectionsOperations", + "PrivateLinkResourcesOperations", + "ServerKeysOperations", ] __all__.extend([p for p in _patch_all if p not in __all__]) -_patch_sdk() \ No newline at end of file +_patch_sdk() diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_advisors_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_advisors_operations.py index e446943af162..90711216cc97 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_advisors_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_advisors_operations.py @@ -8,9 +8,14 @@ # -------------------------------------------------------------------------- from typing import Any, Callable, Dict, Iterable, Optional, TypeVar -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse @@ -20,87 +25,82 @@ from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer from .._vendor import MixinABC, _convert_request, _format_url_section -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False + def build_get_request( - subscription_id: str, - resource_group_name: str, - server_name: str, - advisor_name: str, - **kwargs: Any + resource_group_name: str, server_name: str, advisor_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/advisors/{advisorName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/advisors/{advisorName}", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), - "advisorName": _SERIALIZER.url("advisor_name", advisor_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), + "advisorName": _SERIALIZER.url("advisor_name", advisor_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_list_by_server_request( - subscription_id: str, - resource_group_name: str, - server_name: str, - **kwargs: Any + resource_group_name: str, server_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/advisors") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/advisors", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) class AdvisorsOperations: """ @@ -121,50 +121,43 @@ def __init__(self, *args, **kwargs): self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace - def get( - self, - resource_group_name: str, - server_name: str, - advisor_name: str, - **kwargs: Any - ) -> _models.Advisor: + def get(self, resource_group_name: str, server_name: str, advisor_name: str, **kwargs: Any) -> _models.Advisor: """Get a recommendation action advisor. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param advisor_name: The advisor name for recommendation action. + :param advisor_name: The advisor name for recommendation action. Required. :type advisor_name: str - :keyword api_version: Api Version. Default value is "2018-06-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Advisor, or the result of cls(response) + :return: Advisor or the result of cls(response) :rtype: ~azure.mgmt.rdbms.mysql.models.Advisor - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.Advisor] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.Advisor] - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, advisor_name=advisor_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], headers=_headers, params=_params, ) @@ -172,66 +165,61 @@ def get( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('Advisor', pipeline_response) + deserialized = self._deserialize("Advisor", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/advisors/{advisorName}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/advisors/{advisorName}"} # type: ignore @distributed_trace - def list_by_server( - self, - resource_group_name: str, - server_name: str, - **kwargs: Any - ) -> Iterable[_models.AdvisorsResultList]: + def list_by_server(self, resource_group_name: str, server_name: str, **kwargs: Any) -> Iterable["_models.Advisor"]: """List recommendation action advisors. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :keyword api_version: Api Version. Default value is "2018-06-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either AdvisorsResultList or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql.models.AdvisorsResultList] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Advisor or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql.models.Advisor] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.AdvisorsResultList] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AdvisorsResultList] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_server_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_server.metadata['url'], + template_url=self.list_by_server.metadata["url"], headers=_headers, params=_params, ) @@ -239,16 +227,7 @@ def prepare_request(next_link=None): request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_by_server_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - server_name=server_name, - api_version=api_version, - template_url=next_link, - headers=_headers, - params=_params, - ) + request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" @@ -264,10 +243,8 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -277,8 +254,6 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list_by_server.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/advisors"} # type: ignore + list_by_server.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/advisors"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_check_name_availability_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_check_name_availability_operations.py index 151895e5ba0b..472a2d06253b 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_check_name_availability_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_check_name_availability_operations.py @@ -6,11 +6,16 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Optional, TypeVar - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest @@ -19,52 +24,44 @@ from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer from .._vendor import MixinABC, _convert_request, _format_url_section -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_execute_request( - subscription_id: str, - *, - json: Optional[_models.NameAvailabilityRequest] = None, - content: Any = None, - **kwargs: Any -) -> HttpRequest: + +def build_execute_request(subscription_id: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', None)) # type: Optional[str] - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/checkNameAvailability") + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/checkNameAvailability" + ) path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if content_type is not None: - _headers['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="POST", - url=_url, - params=_params, - headers=_headers, - json=json, - content=content, - **kwargs - ) + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + class CheckNameAvailabilityOperations: """ @@ -85,46 +82,93 @@ def __init__(self, *args, **kwargs): self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace + @overload def execute( self, name_availability_request: _models.NameAvailabilityRequest, + *, + content_type: str = "application/json", **kwargs: Any ) -> _models.NameAvailability: """Check the availability of name for resource. :param name_availability_request: The required parameters for checking if resource name is - available. + available. Required. :type name_availability_request: ~azure.mgmt.rdbms.mysql.models.NameAvailabilityRequest - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: NameAvailability, or the result of cls(response) + :return: NameAvailability or the result of cls(response) :rtype: ~azure.mgmt.rdbms.mysql.models.NameAvailability - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def execute( + self, name_availability_request: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.NameAvailability: + """Check the availability of name for resource. + + :param name_availability_request: The required parameters for checking if resource name is + available. Required. + :type name_availability_request: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: NameAvailability or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql.models.NameAvailability + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def execute( + self, name_availability_request: Union[_models.NameAvailabilityRequest, IO], **kwargs: Any + ) -> _models.NameAvailability: + """Check the availability of name for resource. + + :param name_availability_request: The required parameters for checking if resource name is + available. Is either a model type or a IO type. Required. + :type name_availability_request: ~azure.mgmt.rdbms.mysql.models.NameAvailabilityRequest or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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: NameAvailability or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql.models.NameAvailability + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[_models.NameAvailability] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.NameAvailability] - _json = self._serialize.body(name_availability_request, 'NameAvailabilityRequest') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(name_availability_request, (IO, bytes)): + _content = name_availability_request + else: + _json = self._serialize.body(name_availability_request, "NameAvailabilityRequest") request = build_execute_request( subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self.execute.metadata['url'], + content=_content, + template_url=self.execute.metadata["url"], headers=_headers, params=_params, ) @@ -132,22 +176,20 @@ def execute( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('NameAvailability', pipeline_response) + deserialized = self._deserialize("NameAvailability", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - execute.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/checkNameAvailability"} # type: ignore - + execute.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/checkNameAvailability"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_configurations_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_configurations_operations.py index b1eca4e5a1d0..1f889a97e08a 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_configurations_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_configurations_operations.py @@ -6,11 +6,16 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Iterable, Optional, TypeVar, Union, cast - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse @@ -22,134 +27,119 @@ from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models +from .._serialization import Serializer from .._vendor import MixinABC, _convert_request, _format_url_section -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_create_or_update_request_initial( - subscription_id: str, - resource_group_name: str, - server_name: str, - configuration_name: str, - *, - json: Optional[_models.Configuration] = None, - content: Any = None, - **kwargs: Any + +def build_create_or_update_request( + resource_group_name: str, server_name: str, configuration_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', None)) # type: Optional[str] - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/configurations/{configurationName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/configurations/{configurationName}", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), - "configurationName": _SERIALIZER.url("configuration_name", configuration_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), + "configurationName": _SERIALIZER.url("configuration_name", configuration_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _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') + _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, - json=json, - content=content, - **kwargs - ) + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) def build_get_request( - subscription_id: str, - resource_group_name: str, - server_name: str, - configuration_name: str, - **kwargs: Any + resource_group_name: str, server_name: str, configuration_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/configurations/{configurationName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/configurations/{configurationName}", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), - "configurationName": _SERIALIZER.url("configuration_name", configuration_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), + "configurationName": _SERIALIZER.url("configuration_name", configuration_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_list_by_server_request( - subscription_id: str, - resource_group_name: str, - server_name: str, - **kwargs: Any + resource_group_name: str, server_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/configurations") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/configurations", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) class ConfigurationsOperations: """ @@ -170,38 +160,47 @@ def __init__(self, *args, **kwargs): 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") - def _create_or_update_initial( self, resource_group_name: str, server_name: str, configuration_name: str, - parameters: _models.Configuration, + parameters: Union[_models.Configuration, IO], **kwargs: Any ) -> Optional[_models.Configuration]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[Optional[_models.Configuration]] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.Configuration]] - _json = self._serialize.body(parameters, 'Configuration') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Configuration") - request = build_create_or_update_request_initial( - subscription_id=self._config.subscription_id, + request = build_create_or_update_request( resource_group_name=resource_group_name, server_name=server_name, configuration_name=configuration_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._create_or_update_initial.metadata['url'], + content=_content, + template_url=self._create_or_update_initial.metadata["url"], headers=_headers, params=_params, ) @@ -209,10 +208,9 @@ def _create_or_update_initial( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202]: @@ -221,38 +219,117 @@ def _create_or_update_initial( deserialized = None if response.status_code == 200: - deserialized = self._deserialize('Configuration', pipeline_response) + deserialized = self._deserialize("Configuration", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _create_or_update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/configurations/{configurationName}"} # type: ignore - + _create_or_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/configurations/{configurationName}"} # type: ignore - @distributed_trace + @overload def begin_create_or_update( self, resource_group_name: str, server_name: str, configuration_name: str, parameters: _models.Configuration, + *, + content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.Configuration]: """Updates a configuration of a server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param configuration_name: The name of the server configuration. + :param configuration_name: The name of the server configuration. Required. :type configuration_name: str - :param parameters: The required parameters for updating a server configuration. + :param parameters: The required parameters for updating a server configuration. Required. :type parameters: ~azure.mgmt.rdbms.mysql.models.Configuration - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :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 Configuration or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql.models.Configuration] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + configuration_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.Configuration]: + """Updates a configuration of a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param configuration_name: The name of the server configuration. Required. + :type configuration_name: str + :param parameters: The required parameters for updating a server configuration. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :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 Configuration or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql.models.Configuration] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + configuration_name: str, + parameters: Union[_models.Configuration, IO], + **kwargs: Any + ) -> LROPoller[_models.Configuration]: + """Updates a configuration of a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param configuration_name: The name of the server configuration. Required. + :type configuration_name: str + :param parameters: The required parameters for updating a server configuration. Is either a + model type or a IO type. Required. + :type parameters: ~azure.mgmt.rdbms.mysql.models.Configuration or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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 @@ -264,20 +341,17 @@ def begin_create_or_update( :return: An instance of LROPoller that returns either Configuration or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql.models.Configuration] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[_models.Configuration] - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Configuration] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = self._create_or_update_initial( # type: ignore resource_group_name=resource_group_name, @@ -286,83 +360,75 @@ def begin_create_or_update( parameters=parameters, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize('Configuration', pipeline_response) + deserialized = self._deserialize("Configuration", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - if polling is True: - polling_method = cast(PollingMethod, ARMPolling( - lro_delay, - - - **kwargs - )) # type: PollingMethod - elif polling is False: polling_method = cast(PollingMethod, NoPolling()) - else: polling_method = polling + polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_create_or_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/configurations/{configurationName}"} # type: ignore + begin_create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/configurations/{configurationName}"} # type: ignore @distributed_trace def get( - self, - resource_group_name: str, - server_name: str, - configuration_name: str, - **kwargs: Any + self, resource_group_name: str, server_name: str, configuration_name: str, **kwargs: Any ) -> _models.Configuration: """Gets information about a configuration of server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param configuration_name: The name of the server configuration. + :param configuration_name: The name of the server configuration. Required. :type configuration_name: str - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Configuration, or the result of cls(response) + :return: Configuration or the result of cls(response) :rtype: ~azure.mgmt.rdbms.mysql.models.Configuration - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.Configuration] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.Configuration] - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, configuration_name=configuration_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], headers=_headers, params=_params, ) @@ -370,67 +436,63 @@ def get( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('Configuration', pipeline_response) + deserialized = self._deserialize("Configuration", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/configurations/{configurationName}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/configurations/{configurationName}"} # type: ignore @distributed_trace def list_by_server( - self, - resource_group_name: str, - server_name: str, - **kwargs: Any - ) -> Iterable[_models.ConfigurationListResult]: + self, resource_group_name: str, server_name: str, **kwargs: Any + ) -> Iterable["_models.Configuration"]: """List all the configurations in a given server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ConfigurationListResult or the result of - cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql.models.ConfigurationListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Configuration or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql.models.Configuration] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.ConfigurationListResult] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ConfigurationListResult] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_server_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_server.metadata['url'], + template_url=self.list_by_server.metadata["url"], headers=_headers, params=_params, ) @@ -438,16 +500,7 @@ def prepare_request(next_link=None): request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_by_server_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - server_name=server_name, - api_version=api_version, - template_url=next_link, - headers=_headers, - params=_params, - ) + request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" @@ -463,10 +516,8 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -476,8 +527,6 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list_by_server.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/configurations"} # type: ignore + list_by_server.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/configurations"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_databases_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_databases_operations.py index de20d6c86f5f..29ddac479c72 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_databases_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_databases_operations.py @@ -6,11 +6,16 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Iterable, Optional, TypeVar, Union, cast - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse @@ -22,173 +27,153 @@ from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models +from .._serialization import Serializer from .._vendor import MixinABC, _convert_request, _format_url_section -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_create_or_update_request_initial( - subscription_id: str, - resource_group_name: str, - server_name: str, - database_name: str, - *, - json: Optional[_models.Database] = None, - content: Any = None, - **kwargs: Any + +def build_create_or_update_request( + resource_group_name: str, server_name: str, database_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', None)) # type: Optional[str] - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/databases/{databaseName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/databases/{databaseName}", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), - "databaseName": _SERIALIZER.url("database_name", database_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _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, - json=json, - content=content, - **kwargs - ) - - -def build_delete_request_initial( - subscription_id: str, - resource_group_name: str, - server_name: str, - database_name: str, - **kwargs: Any + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_request( + resource_group_name: str, server_name: str, database_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/databases/{databaseName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/databases/{databaseName}", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), - "databaseName": _SERIALIZER.url("database_name", database_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="DELETE", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) def build_get_request( - subscription_id: str, - resource_group_name: str, - server_name: str, - database_name: str, - **kwargs: Any + resource_group_name: str, server_name: str, database_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/databases/{databaseName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/databases/{databaseName}", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), - "databaseName": _SERIALIZER.url("database_name", database_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_list_by_server_request( - subscription_id: str, - resource_group_name: str, - server_name: str, - **kwargs: Any + resource_group_name: str, server_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/databases") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/databases", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) class DatabasesOperations: """ @@ -209,38 +194,47 @@ def __init__(self, *args, **kwargs): 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") - def _create_or_update_initial( self, resource_group_name: str, server_name: str, database_name: str, - parameters: _models.Database, + parameters: Union[_models.Database, IO], **kwargs: Any ) -> Optional[_models.Database]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[Optional[_models.Database]] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.Database]] - _json = self._serialize.body(parameters, 'Database') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Database") - request = build_create_or_update_request_initial( - subscription_id=self._config.subscription_id, + request = build_create_or_update_request( resource_group_name=resource_group_name, server_name=server_name, database_name=database_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._create_or_update_initial.metadata['url'], + content=_content, + template_url=self._create_or_update_initial.metadata["url"], headers=_headers, params=_params, ) @@ -248,10 +242,9 @@ def _create_or_update_initial( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 201, 202]: @@ -260,41 +253,118 @@ def _create_or_update_initial( deserialized = None if response.status_code == 200: - deserialized = self._deserialize('Database', pipeline_response) + deserialized = self._deserialize("Database", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('Database', pipeline_response) + deserialized = self._deserialize("Database", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _create_or_update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/databases/{databaseName}"} # type: ignore - + _create_or_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/databases/{databaseName}"} # type: ignore - @distributed_trace + @overload def begin_create_or_update( self, resource_group_name: str, server_name: str, database_name: str, parameters: _models.Database, + *, + content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.Database]: """Creates a new database or updates an existing database. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param database_name: The name of the database. + :param database_name: The name of the database. Required. :type database_name: str - :param parameters: The required parameters for creating or updating a database. + :param parameters: The required parameters for creating or updating a database. Required. :type parameters: ~azure.mgmt.rdbms.mysql.models.Database - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :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 Database or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql.models.Database] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + database_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.Database]: + """Creates a new database or updates an existing database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param database_name: The name of the database. Required. + :type database_name: str + :param parameters: The required parameters for creating or updating a database. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :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 Database or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql.models.Database] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + database_name: str, + parameters: Union[_models.Database, IO], + **kwargs: Any + ) -> LROPoller[_models.Database]: + """Creates a new database or updates an existing database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param database_name: The name of the database. Required. + :type database_name: str + :param parameters: The required parameters for creating or updating a database. Is either a + model type or a IO type. Required. + :type parameters: ~azure.mgmt.rdbms.mysql.models.Database or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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 @@ -305,20 +375,17 @@ def begin_create_or_update( Retry-After header is present. :return: An instance of LROPoller that returns either Database or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql.models.Database] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[_models.Database] - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Database] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = self._create_or_update_initial( # type: ignore resource_group_name=resource_group_name, @@ -327,66 +394,60 @@ def begin_create_or_update( parameters=parameters, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize('Database', pipeline_response) + deserialized = self._deserialize("Database", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - if polling is True: - polling_method = cast(PollingMethod, ARMPolling( - lro_delay, - - - **kwargs - )) # type: PollingMethod - elif polling is False: polling_method = cast(PollingMethod, NoPolling()) - else: polling_method = polling + polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_create_or_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/databases/{databaseName}"} # type: ignore + begin_create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/databases/{databaseName}"} # type: ignore def _delete_initial( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - server_name: str, - database_name: str, - **kwargs: Any + self, resource_group_name: str, server_name: str, database_name: str, **kwargs: Any ) -> None: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] - - request = build_delete_request_initial( - subscription_id=self._config.subscription_id, + request = build_delete_request( resource_group_name=resource_group_name, server_name=server_name, database_name=database_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._delete_initial.metadata['url'], + template_url=self._delete_initial.metadata["url"], headers=_headers, params=_params, ) @@ -394,10 +455,9 @@ def _delete_initial( # pylint: disable=inconsistent-return-statements request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: @@ -407,28 +467,21 @@ def _delete_initial( # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - _delete_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/databases/{databaseName}"} # type: ignore - + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/databases/{databaseName}"} # type: ignore @distributed_trace - def begin_delete( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - server_name: str, - database_name: str, - **kwargs: Any + def begin_delete( + self, resource_group_name: str, server_name: str, database_name: str, **kwargs: Any ) -> LROPoller[None]: """Deletes a database. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param database_name: The name of the database. + :param database_name: The name of the database. Required. :type database_name: str - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function 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 @@ -439,100 +492,87 @@ def begin_delete( # pylint: disable=inconsistent-return-statements Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = self._delete_initial( # type: ignore resource_group_name=resource_group_name, server_name=server_name, database_name=database_name, api_version=api_version, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - if polling is True: - polling_method = cast(PollingMethod, ARMPolling( - lro_delay, - - - **kwargs - )) # type: PollingMethod - elif polling is False: polling_method = cast(PollingMethod, NoPolling()) - else: polling_method = polling + polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_delete.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/databases/{databaseName}"} # type: ignore + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/databases/{databaseName}"} # type: ignore @distributed_trace - def get( - self, - resource_group_name: str, - server_name: str, - database_name: str, - **kwargs: Any - ) -> _models.Database: + def get(self, resource_group_name: str, server_name: str, database_name: str, **kwargs: Any) -> _models.Database: """Gets information about a database. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param database_name: The name of the database. + :param database_name: The name of the database. Required. :type database_name: str - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Database, or the result of cls(response) + :return: Database or the result of cls(response) :rtype: ~azure.mgmt.rdbms.mysql.models.Database - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.Database] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.Database] - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, database_name=database_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], headers=_headers, params=_params, ) @@ -540,66 +580,61 @@ def get( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('Database', pipeline_response) + deserialized = self._deserialize("Database", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/databases/{databaseName}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/databases/{databaseName}"} # type: ignore @distributed_trace - def list_by_server( - self, - resource_group_name: str, - server_name: str, - **kwargs: Any - ) -> Iterable[_models.DatabaseListResult]: + def list_by_server(self, resource_group_name: str, server_name: str, **kwargs: Any) -> Iterable["_models.Database"]: """List all the databases in a given server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either DatabaseListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql.models.DatabaseListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Database or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql.models.Database] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.DatabaseListResult] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.DatabaseListResult] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_server_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_server.metadata['url'], + template_url=self.list_by_server.metadata["url"], headers=_headers, params=_params, ) @@ -607,16 +642,7 @@ def prepare_request(next_link=None): request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_by_server_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - server_name=server_name, - api_version=api_version, - template_url=next_link, - headers=_headers, - params=_params, - ) + request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" @@ -632,10 +658,8 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -645,8 +669,6 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list_by_server.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/databases"} # type: ignore + list_by_server.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/databases"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_firewall_rules_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_firewall_rules_operations.py index 4652f5aa2b1c..a4d96959bc85 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_firewall_rules_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_firewall_rules_operations.py @@ -6,11 +6,16 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Iterable, Optional, TypeVar, Union, cast - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse @@ -22,173 +27,153 @@ from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models +from .._serialization import Serializer from .._vendor import MixinABC, _convert_request, _format_url_section -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_create_or_update_request_initial( - subscription_id: str, - resource_group_name: str, - server_name: str, - firewall_rule_name: str, - *, - json: Optional[_models.FirewallRule] = None, - content: Any = None, - **kwargs: Any + +def build_create_or_update_request( + resource_group_name: str, server_name: str, firewall_rule_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', None)) # type: Optional[str] - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/firewallRules/{firewallRuleName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/firewallRules/{firewallRuleName}", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), - "firewallRuleName": _SERIALIZER.url("firewall_rule_name", firewall_rule_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), + "firewallRuleName": _SERIALIZER.url("firewall_rule_name", firewall_rule_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _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, - json=json, - content=content, - **kwargs - ) - - -def build_delete_request_initial( - subscription_id: str, - resource_group_name: str, - server_name: str, - firewall_rule_name: str, - **kwargs: Any + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_request( + resource_group_name: str, server_name: str, firewall_rule_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/firewallRules/{firewallRuleName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/firewallRules/{firewallRuleName}", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), - "firewallRuleName": _SERIALIZER.url("firewall_rule_name", firewall_rule_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), + "firewallRuleName": _SERIALIZER.url("firewall_rule_name", firewall_rule_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="DELETE", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) def build_get_request( - subscription_id: str, - resource_group_name: str, - server_name: str, - firewall_rule_name: str, - **kwargs: Any + resource_group_name: str, server_name: str, firewall_rule_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/firewallRules/{firewallRuleName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/firewallRules/{firewallRuleName}", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), - "firewallRuleName": _SERIALIZER.url("firewall_rule_name", firewall_rule_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), + "firewallRuleName": _SERIALIZER.url("firewall_rule_name", firewall_rule_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_list_by_server_request( - subscription_id: str, - resource_group_name: str, - server_name: str, - **kwargs: Any + resource_group_name: str, server_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/firewallRules") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/firewallRules", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) class FirewallRulesOperations: """ @@ -209,38 +194,47 @@ def __init__(self, *args, **kwargs): 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") - def _create_or_update_initial( self, resource_group_name: str, server_name: str, firewall_rule_name: str, - parameters: _models.FirewallRule, + parameters: Union[_models.FirewallRule, IO], **kwargs: Any ) -> Optional[_models.FirewallRule]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[Optional[_models.FirewallRule]] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.FirewallRule]] - _json = self._serialize.body(parameters, 'FirewallRule') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "FirewallRule") - request = build_create_or_update_request_initial( - subscription_id=self._config.subscription_id, + request = build_create_or_update_request( resource_group_name=resource_group_name, server_name=server_name, firewall_rule_name=firewall_rule_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._create_or_update_initial.metadata['url'], + content=_content, + template_url=self._create_or_update_initial.metadata["url"], headers=_headers, params=_params, ) @@ -248,10 +242,9 @@ def _create_or_update_initial( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 201, 202]: @@ -260,41 +253,43 @@ def _create_or_update_initial( deserialized = None if response.status_code == 200: - deserialized = self._deserialize('FirewallRule', pipeline_response) + deserialized = self._deserialize("FirewallRule", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('FirewallRule', pipeline_response) + deserialized = self._deserialize("FirewallRule", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _create_or_update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/firewallRules/{firewallRuleName}"} # type: ignore - + _create_or_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/firewallRules/{firewallRuleName}"} # type: ignore - @distributed_trace + @overload def begin_create_or_update( self, resource_group_name: str, server_name: str, firewall_rule_name: str, parameters: _models.FirewallRule, + *, + content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.FirewallRule]: """Creates a new firewall rule or updates an existing firewall rule. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param firewall_rule_name: The name of the server firewall rule. + :param firewall_rule_name: The name of the server firewall rule. Required. :type firewall_rule_name: str - :param parameters: The required parameters for creating or updating a firewall rule. + :param parameters: The required parameters for creating or updating a firewall rule. Required. :type parameters: ~azure.mgmt.rdbms.mysql.models.FirewallRule - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :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 @@ -306,20 +301,94 @@ def begin_create_or_update( :return: An instance of LROPoller that returns either FirewallRule or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql.models.FirewallRule] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + firewall_rule_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.FirewallRule]: + """Creates a new firewall rule or updates an existing firewall rule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param firewall_rule_name: The name of the server firewall rule. Required. + :type firewall_rule_name: str + :param parameters: The required parameters for creating or updating a firewall rule. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :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 FirewallRule or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql.models.FirewallRule] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + firewall_rule_name: str, + parameters: Union[_models.FirewallRule, IO], + **kwargs: Any + ) -> LROPoller[_models.FirewallRule]: + """Creates a new firewall rule or updates an existing firewall rule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param firewall_rule_name: The name of the server firewall rule. Required. + :type firewall_rule_name: str + :param parameters: The required parameters for creating or updating a firewall rule. Is either + a model type or a IO type. Required. + :type parameters: ~azure.mgmt.rdbms.mysql.models.FirewallRule or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either FirewallRule or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql.models.FirewallRule] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[_models.FirewallRule] - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.FirewallRule] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = self._create_or_update_initial( # type: ignore resource_group_name=resource_group_name, @@ -328,66 +397,60 @@ def begin_create_or_update( parameters=parameters, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize('FirewallRule', pipeline_response) + deserialized = self._deserialize("FirewallRule", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - if polling is True: - polling_method = cast(PollingMethod, ARMPolling( - lro_delay, - - - **kwargs - )) # type: PollingMethod - elif polling is False: polling_method = cast(PollingMethod, NoPolling()) - else: polling_method = polling + polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_create_or_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/firewallRules/{firewallRuleName}"} # type: ignore + begin_create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/firewallRules/{firewallRuleName}"} # type: ignore def _delete_initial( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - server_name: str, - firewall_rule_name: str, - **kwargs: Any + self, resource_group_name: str, server_name: str, firewall_rule_name: str, **kwargs: Any ) -> None: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] - - request = build_delete_request_initial( - subscription_id=self._config.subscription_id, + request = build_delete_request( resource_group_name=resource_group_name, server_name=server_name, firewall_rule_name=firewall_rule_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._delete_initial.metadata['url'], + template_url=self._delete_initial.metadata["url"], headers=_headers, params=_params, ) @@ -395,10 +458,9 @@ def _delete_initial( # pylint: disable=inconsistent-return-statements request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: @@ -408,28 +470,21 @@ def _delete_initial( # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - _delete_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/firewallRules/{firewallRuleName}"} # type: ignore - + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/firewallRules/{firewallRuleName}"} # type: ignore @distributed_trace - def begin_delete( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - server_name: str, - firewall_rule_name: str, - **kwargs: Any + def begin_delete( + self, resource_group_name: str, server_name: str, firewall_rule_name: str, **kwargs: Any ) -> LROPoller[None]: """Deletes a server firewall rule. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param firewall_rule_name: The name of the server firewall rule. + :param firewall_rule_name: The name of the server firewall rule. Required. :type firewall_rule_name: str - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function 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 @@ -440,100 +495,89 @@ def begin_delete( # pylint: disable=inconsistent-return-statements Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = self._delete_initial( # type: ignore resource_group_name=resource_group_name, server_name=server_name, firewall_rule_name=firewall_rule_name, api_version=api_version, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - if polling is True: - polling_method = cast(PollingMethod, ARMPolling( - lro_delay, - - - **kwargs - )) # type: PollingMethod - elif polling is False: polling_method = cast(PollingMethod, NoPolling()) - else: polling_method = polling + polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_delete.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/firewallRules/{firewallRuleName}"} # type: ignore + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/firewallRules/{firewallRuleName}"} # type: ignore @distributed_trace def get( - self, - resource_group_name: str, - server_name: str, - firewall_rule_name: str, - **kwargs: Any + self, resource_group_name: str, server_name: str, firewall_rule_name: str, **kwargs: Any ) -> _models.FirewallRule: """Gets information about a server firewall rule. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param firewall_rule_name: The name of the server firewall rule. + :param firewall_rule_name: The name of the server firewall rule. Required. :type firewall_rule_name: str - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: FirewallRule, or the result of cls(response) + :return: FirewallRule or the result of cls(response) :rtype: ~azure.mgmt.rdbms.mysql.models.FirewallRule - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.FirewallRule] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.FirewallRule] - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, firewall_rule_name=firewall_rule_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], headers=_headers, params=_params, ) @@ -541,67 +585,63 @@ def get( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('FirewallRule', pipeline_response) + deserialized = self._deserialize("FirewallRule", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/firewallRules/{firewallRuleName}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/firewallRules/{firewallRuleName}"} # type: ignore @distributed_trace def list_by_server( - self, - resource_group_name: str, - server_name: str, - **kwargs: Any - ) -> Iterable[_models.FirewallRuleListResult]: + self, resource_group_name: str, server_name: str, **kwargs: Any + ) -> Iterable["_models.FirewallRule"]: """List all the firewall rules in a given server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either FirewallRuleListResult or the result of - cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql.models.FirewallRuleListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either FirewallRule or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql.models.FirewallRule] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.FirewallRuleListResult] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.FirewallRuleListResult] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_server_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_server.metadata['url'], + template_url=self.list_by_server.metadata["url"], headers=_headers, params=_params, ) @@ -609,16 +649,7 @@ def prepare_request(next_link=None): request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_by_server_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - server_name=server_name, - api_version=api_version, - template_url=next_link, - headers=_headers, - params=_params, - ) + request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" @@ -634,10 +665,8 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -647,8 +676,6 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list_by_server.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/firewallRules"} # type: ignore + list_by_server.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/firewallRules"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_location_based_performance_tier_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_location_based_performance_tier_operations.py index 236b79139611..707f246cb4ca 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_location_based_performance_tier_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_location_based_performance_tier_operations.py @@ -8,9 +8,14 @@ # -------------------------------------------------------------------------- from typing import Any, Callable, Dict, Iterable, Optional, TypeVar -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse @@ -20,46 +25,43 @@ from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer from .._vendor import MixinABC, _convert_request, _format_url_section -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_list_request( - subscription_id: str, - location_name: str, - **kwargs: Any -) -> HttpRequest: + +def build_list_request(location_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/locations/{locationName}/performanceTiers") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/locations/{locationName}/performanceTiers", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), - "locationName": _SERIALIZER.url("location_name", location_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "locationName": _SERIALIZER.url("location_name", location_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) class LocationBasedPerformanceTierOperations: """ @@ -80,44 +82,40 @@ def __init__(self, *args, **kwargs): self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace - def list( - self, - location_name: str, - **kwargs: Any - ) -> Iterable[_models.PerformanceTierListResult]: + def list(self, location_name: str, **kwargs: Any) -> Iterable["_models.PerformanceTierProperties"]: """List all the performance tiers at specified location in a given subscription. - :param location_name: The name of the location. + :param location_name: The name of the location. Required. :type location_name: str - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PerformanceTierListResult or the result of + :return: An iterator like instance of either PerformanceTierProperties or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql.models.PerformanceTierListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql.models.PerformanceTierProperties] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.PerformanceTierListResult] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PerformanceTierListResult] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( - subscription_id=self._config.subscription_id, location_name=location_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list.metadata['url'], + template_url=self.list.metadata["url"], headers=_headers, params=_params, ) @@ -125,15 +123,7 @@ def prepare_request(next_link=None): request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_request( - subscription_id=self._config.subscription_id, - location_name=location_name, - api_version=api_version, - template_url=next_link, - headers=_headers, - params=_params, - ) + request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" @@ -149,10 +139,8 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -162,8 +150,6 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/locations/{locationName}/performanceTiers"} # type: ignore + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/locations/{locationName}/performanceTiers"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_location_based_recommended_action_sessions_operation_status_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_location_based_recommended_action_sessions_operation_status_operations.py index cfbcc2a19a10..c4b69855509c 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_location_based_recommended_action_sessions_operation_status_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_location_based_recommended_action_sessions_operation_status_operations.py @@ -8,9 +8,14 @@ # -------------------------------------------------------------------------- from typing import Any, Callable, Dict, Optional, TypeVar -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest @@ -19,48 +24,44 @@ from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer from .._vendor import MixinABC, _convert_request, _format_url_section -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_get_request( - subscription_id: str, - location_name: str, - operation_id: str, - **kwargs: Any -) -> HttpRequest: + +def build_get_request(location_name: str, operation_id: str, subscription_id: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/locations/{locationName}/recommendedActionSessionsAzureAsyncOperation/{operationId}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/locations/{locationName}/recommendedActionSessionsAzureAsyncOperation/{operationId}", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), - "locationName": _SERIALIZER.url("location_name", location_name, 'str'), - "operationId": _SERIALIZER.url("operation_id", operation_id, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "locationName": _SERIALIZER.url("location_name", location_name, "str"), + "operationId": _SERIALIZER.url("operation_id", operation_id, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) class LocationBasedRecommendedActionSessionsOperationStatusOperations: """ @@ -81,46 +82,41 @@ def __init__(self, *args, **kwargs): self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace def get( - self, - location_name: str, - operation_id: str, - **kwargs: Any + self, location_name: str, operation_id: str, **kwargs: Any ) -> _models.RecommendedActionSessionsOperationStatus: """Recommendation action session operation status. - :param location_name: The name of the location. + :param location_name: The name of the location. Required. :type location_name: str - :param operation_id: The operation identifier. + :param operation_id: The operation identifier. Required. :type operation_id: str - :keyword api_version: Api Version. Default value is "2018-06-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RecommendedActionSessionsOperationStatus, or the result of cls(response) + :return: RecommendedActionSessionsOperationStatus or the result of cls(response) :rtype: ~azure.mgmt.rdbms.mysql.models.RecommendedActionSessionsOperationStatus - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.RecommendedActionSessionsOperationStatus] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RecommendedActionSessionsOperationStatus] - request = build_get_request( - subscription_id=self._config.subscription_id, location_name=location_name, operation_id=operation_id, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], headers=_headers, params=_params, ) @@ -128,22 +124,20 @@ def get( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('RecommendedActionSessionsOperationStatus', pipeline_response) + deserialized = self._deserialize("RecommendedActionSessionsOperationStatus", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/locations/{locationName}/recommendedActionSessionsAzureAsyncOperation/{operationId}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/locations/{locationName}/recommendedActionSessionsAzureAsyncOperation/{operationId}"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_location_based_recommended_action_sessions_result_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_location_based_recommended_action_sessions_result_operations.py index f779e31973bc..4456a430c3b3 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_location_based_recommended_action_sessions_result_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_location_based_recommended_action_sessions_result_operations.py @@ -8,9 +8,14 @@ # -------------------------------------------------------------------------- from typing import Any, Callable, Dict, Iterable, Optional, TypeVar -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse @@ -20,48 +25,44 @@ from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer from .._vendor import MixinABC, _convert_request, _format_url_section -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_list_request( - subscription_id: str, - location_name: str, - operation_id: str, - **kwargs: Any -) -> HttpRequest: + +def build_list_request(location_name: str, operation_id: str, subscription_id: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/locations/{locationName}/recommendedActionSessionsOperationResults/{operationId}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/locations/{locationName}/recommendedActionSessionsOperationResults/{operationId}", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), - "locationName": _SERIALIZER.url("location_name", location_name, 'str'), - "operationId": _SERIALIZER.url("operation_id", operation_id, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "locationName": _SERIALIZER.url("location_name", location_name, "str"), + "operationId": _SERIALIZER.url("operation_id", operation_id, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) class LocationBasedRecommendedActionSessionsResultOperations: """ @@ -82,49 +83,43 @@ def __init__(self, *args, **kwargs): self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace - def list( - self, - location_name: str, - operation_id: str, - **kwargs: Any - ) -> Iterable[_models.RecommendationActionsResultList]: + def list(self, location_name: str, operation_id: str, **kwargs: Any) -> Iterable["_models.RecommendationAction"]: """Recommendation action session operation result. - :param location_name: The name of the location. + :param location_name: The name of the location. Required. :type location_name: str - :param operation_id: The operation identifier. + :param operation_id: The operation identifier. Required. :type operation_id: str - :keyword api_version: Api Version. Default value is "2018-06-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RecommendationActionsResultList or the result of + :return: An iterator like instance of either RecommendationAction or the result of cls(response) - :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql.models.RecommendationActionsResultList] - :raises: ~azure.core.exceptions.HttpResponseError + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql.models.RecommendationAction] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.RecommendationActionsResultList] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RecommendationActionsResultList] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( - subscription_id=self._config.subscription_id, location_name=location_name, operation_id=operation_id, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list.metadata['url'], + template_url=self.list.metadata["url"], headers=_headers, params=_params, ) @@ -132,16 +127,7 @@ def prepare_request(next_link=None): request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_request( - subscription_id=self._config.subscription_id, - location_name=location_name, - operation_id=operation_id, - api_version=api_version, - template_url=next_link, - headers=_headers, - params=_params, - ) + request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" @@ -157,10 +143,8 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -170,8 +154,6 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/locations/{locationName}/recommendedActionSessionsOperationResults/{operationId}"} # type: ignore + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/locations/{locationName}/recommendedActionSessionsOperationResults/{operationId}"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_log_files_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_log_files_operations.py index cfa70b10504d..acaafc7611db 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_log_files_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_log_files_operations.py @@ -8,9 +8,14 @@ # -------------------------------------------------------------------------- from typing import Any, Callable, Dict, Iterable, Optional, TypeVar -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse @@ -20,48 +25,48 @@ from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer from .._vendor import MixinABC, _convert_request, _format_url_section -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False + def build_list_by_server_request( - subscription_id: str, - resource_group_name: str, - server_name: str, - **kwargs: Any + resource_group_name: str, server_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/logFiles") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/logFiles", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) class LogFilesOperations: """ @@ -82,47 +87,43 @@ def __init__(self, *args, **kwargs): self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace - def list_by_server( - self, - resource_group_name: str, - server_name: str, - **kwargs: Any - ) -> Iterable[_models.LogFileListResult]: + def list_by_server(self, resource_group_name: str, server_name: str, **kwargs: Any) -> Iterable["_models.LogFile"]: """List all the log files in a given server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either LogFileListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql.models.LogFileListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either LogFile or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql.models.LogFile] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.LogFileListResult] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.LogFileListResult] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_server_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_server.metadata['url'], + template_url=self.list_by_server.metadata["url"], headers=_headers, params=_params, ) @@ -130,16 +131,7 @@ def prepare_request(next_link=None): request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_by_server_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - server_name=server_name, - api_version=api_version, - template_url=next_link, - headers=_headers, - params=_params, - ) + request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" @@ -155,10 +147,8 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -168,8 +158,6 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list_by_server.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/logFiles"} # type: ignore + list_by_server.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/logFiles"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_my_sql_management_client_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_my_sql_management_client_operations.py index 0e640ed34e73..d4c0960aa8c1 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_my_sql_management_client_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_my_sql_management_client_operations.py @@ -8,9 +8,14 @@ # -------------------------------------------------------------------------- from typing import Any, Callable, Dict, Optional, TypeVar, Union, cast -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod @@ -21,125 +26,121 @@ from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models +from .._serialization import Serializer from .._vendor import MixinABC, _convert_request, _format_url_section -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False + def build_reset_query_performance_insight_data_request( - subscription_id: str, - resource_group_name: str, - server_name: str, - **kwargs: Any + resource_group_name: str, server_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/resetQueryPerformanceInsightData") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/resetQueryPerformanceInsightData", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="POST", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_create_recommended_action_session_request_initial( - subscription_id: str, +def build_create_recommended_action_session_request( resource_group_name: str, server_name: str, advisor_name: str, + subscription_id: str, *, database_name: str, **kwargs: Any ) -> HttpRequest: _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/advisors/{advisorName}/createRecommendedActionSession") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/advisors/{advisorName}/createRecommendedActionSession", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), - "advisorName": _SERIALIZER.url("advisor_name", advisor_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), + "advisorName": _SERIALIZER.url("advisor_name", advisor_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') - _params['databaseName'] = _SERIALIZER.query("database_name", database_name, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + _params["databaseName"] = _SERIALIZER.query("database_name", database_name, "str") - return HttpRequest( - method="POST", - url=_url, - params=_params, - **kwargs - ) + return HttpRequest(method="POST", url=_url, params=_params, **kwargs) -class MySQLManagementClientOperationsMixin(MixinABC): +class MySQLManagementClientOperationsMixin(MixinABC): @distributed_trace def reset_query_performance_insight_data( - self, - resource_group_name: str, - server_name: str, - **kwargs: Any + self, resource_group_name: str, server_name: str, **kwargs: Any ) -> _models.QueryPerformanceInsightResetDataResult: """Reset data for Query Performance Insight. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :keyword api_version: Api Version. Default value is "2018-06-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: QueryPerformanceInsightResetDataResult, or the result of cls(response) + :return: QueryPerformanceInsightResetDataResult or the result of cls(response) :rtype: ~azure.mgmt.rdbms.mysql.models.QueryPerformanceInsightResetDataResult - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.QueryPerformanceInsightResetDataResult] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.QueryPerformanceInsightResetDataResult] - request = build_reset_query_performance_insight_data_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.reset_query_performance_insight_data.metadata['url'], + template_url=self.reset_query_performance_insight_data.metadata["url"], headers=_headers, params=_params, ) @@ -147,54 +148,49 @@ def reset_query_performance_insight_data( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('QueryPerformanceInsightResetDataResult', pipeline_response) + deserialized = self._deserialize("QueryPerformanceInsightResetDataResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - reset_query_performance_insight_data.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/resetQueryPerformanceInsightData"} # type: ignore - + reset_query_performance_insight_data.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/resetQueryPerformanceInsightData"} # type: ignore def _create_recommended_action_session_initial( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - server_name: str, - advisor_name: str, - database_name: str, - **kwargs: Any + self, resource_group_name: str, server_name: str, advisor_name: str, database_name: str, **kwargs: Any ) -> None: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] - - request = build_create_recommended_action_session_request_initial( - subscription_id=self._config.subscription_id, + request = build_create_recommended_action_session_request( resource_group_name=resource_group_name, server_name=server_name, advisor_name=advisor_name, - api_version=api_version, + subscription_id=self._config.subscription_id, database_name=database_name, - template_url=self._create_recommended_action_session_initial.metadata['url'], + api_version=api_version, + template_url=self._create_recommended_action_session_initial.metadata["url"], headers=_headers, params=_params, ) @@ -202,10 +198,9 @@ def _create_recommended_action_session_initial( # pylint: disable=inconsistent- request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202]: @@ -215,31 +210,23 @@ def _create_recommended_action_session_initial( # pylint: disable=inconsistent- if cls: return cls(pipeline_response, None, {}) - _create_recommended_action_session_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/advisors/{advisorName}/createRecommendedActionSession"} # type: ignore - + _create_recommended_action_session_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/advisors/{advisorName}/createRecommendedActionSession"} # type: ignore @distributed_trace - def begin_create_recommended_action_session( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - server_name: str, - advisor_name: str, - database_name: str, - **kwargs: Any + def begin_create_recommended_action_session( + self, resource_group_name: str, server_name: str, advisor_name: str, database_name: str, **kwargs: Any ) -> LROPoller[None]: """Create recommendation action session for the advisor. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param advisor_name: The advisor name for recommendation action. + :param advisor_name: The advisor name for recommendation action. Required. :type advisor_name: str - :param database_name: The name of the database. + :param database_name: The name of the database. Required. :type database_name: str - :keyword api_version: Api Version. Default value is "2018-06-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function 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 @@ -250,19 +237,16 @@ def begin_create_recommended_action_session( # pylint: disable=inconsistent-ret Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = self._create_recommended_action_session_initial( # type: ignore resource_group_name=resource_group_name, @@ -270,34 +254,30 @@ def begin_create_recommended_action_session( # pylint: disable=inconsistent-ret advisor_name=advisor_name, database_name=database_name, api_version=api_version, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - if polling is True: - polling_method = cast(PollingMethod, ARMPolling( - lro_delay, - - - **kwargs - )) # type: PollingMethod - elif polling is False: polling_method = cast(PollingMethod, NoPolling()) - else: polling_method = polling + polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_create_recommended_action_session.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/advisors/{advisorName}/createRecommendedActionSession"} # type: ignore + begin_create_recommended_action_session.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/advisors/{advisorName}/createRecommendedActionSession"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_operations.py index 7c4f7751ce6e..885d269a43fb 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_operations.py @@ -8,9 +8,14 @@ # -------------------------------------------------------------------------- from typing import Any, Callable, Dict, Optional, TypeVar -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest @@ -19,38 +24,34 @@ from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer from .._vendor import MixinABC, _convert_request -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_list_request( - **kwargs: Any -) -> HttpRequest: + +def build_list_request(**kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop("template_url", "/providers/Microsoft.DBforMySQL/operations") # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) class Operations: """ @@ -71,37 +72,32 @@ def __init__(self, *args, **kwargs): self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace - def list( - self, - **kwargs: Any - ) -> _models.OperationListResult: + def list(self, **kwargs: Any) -> _models.OperationListResult: """Lists all of the available REST API operations. - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: OperationListResult, or the result of cls(response) + :return: OperationListResult or the result of cls(response) :rtype: ~azure.mgmt.rdbms.mysql.models.OperationListResult - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.OperationListResult] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.OperationListResult] - request = build_list_request( api_version=api_version, - template_url=self.list.metadata['url'], + template_url=self.list.metadata["url"], headers=_headers, params=_params, ) @@ -109,22 +105,20 @@ def list( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('OperationListResult', pipeline_response) + deserialized = self._deserialize("OperationListResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - list.metadata = {'url': "/providers/Microsoft.DBforMySQL/operations"} # type: ignore - + list.metadata = {"url": "/providers/Microsoft.DBforMySQL/operations"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_patch.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_patch.py index 0ad201a8c586..f7dd32510333 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_patch.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_patch.py @@ -10,6 +10,7 @@ __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. diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_private_endpoint_connections_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_private_endpoint_connections_operations.py index 8b4f0ac25d97..3652a4eed4a9 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_private_endpoint_connections_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_private_endpoint_connections_operations.py @@ -6,11 +6,16 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Iterable, Optional, TypeVar, Union, cast - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse @@ -22,13 +27,16 @@ from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models +from .._serialization import Serializer from .._vendor import MixinABC, _convert_request, _format_url_section -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False + def build_get_request( resource_group_name: str, server_name: str, @@ -39,83 +47,80 @@ def build_get_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}", + ) # pylint: disable=line-too-long path_format_arguments = { - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), - "privateEndpointConnectionName": _SERIALIZER.url("private_endpoint_connection_name", private_endpoint_connection_name, 'str'), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), + "privateEndpointConnectionName": _SERIALIZER.url( + "private_endpoint_connection_name", private_endpoint_connection_name, "str" + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_create_or_update_request_initial( +def build_create_or_update_request( resource_group_name: str, server_name: str, private_endpoint_connection_name: str, subscription_id: str, - *, - json: Optional[_models.PrivateEndpointConnection] = None, - content: Any = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', None)) # type: Optional[str] - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}", + ) # pylint: disable=line-too-long path_format_arguments = { - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), - "privateEndpointConnectionName": _SERIALIZER.url("private_endpoint_connection_name", private_endpoint_connection_name, 'str'), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), + "privateEndpointConnectionName": _SERIALIZER.url( + "private_endpoint_connection_name", private_endpoint_connection_name, "str" + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _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') + _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, - json=json, - content=content, - **kwargs - ) + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) -def build_delete_request_initial( +def build_delete_request( resource_group_name: str, server_name: str, private_endpoint_connection_name: str, @@ -125,117 +130,111 @@ def build_delete_request_initial( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}", + ) # pylint: disable=line-too-long path_format_arguments = { - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), - "privateEndpointConnectionName": _SERIALIZER.url("private_endpoint_connection_name", private_endpoint_connection_name, 'str'), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), + "privateEndpointConnectionName": _SERIALIZER.url( + "private_endpoint_connection_name", private_endpoint_connection_name, "str" + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="DELETE", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) -def build_update_tags_request_initial( - subscription_id: str, +def build_update_tags_request( resource_group_name: str, server_name: str, private_endpoint_connection_name: str, - *, - json: Optional[_models.TagsObject] = None, - content: Any = None, + subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', None)) # type: Optional[str] - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), - "privateEndpointConnectionName": _SERIALIZER.url("private_endpoint_connection_name", private_endpoint_connection_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), + "privateEndpointConnectionName": _SERIALIZER.url( + "private_endpoint_connection_name", private_endpoint_connection_name, "str" + ), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _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') + _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, - json=json, - content=content, - **kwargs - ) + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) def build_list_by_server_request( - resource_group_name: str, - server_name: str, - subscription_id: str, - **kwargs: Any + resource_group_name: str, server_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateEndpointConnections") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateEndpointConnections", + ) # pylint: disable=line-too-long path_format_arguments = { - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) class PrivateEndpointConnectionsOperations: """ @@ -256,50 +255,45 @@ def __init__(self, *args, **kwargs): self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace def get( - self, - resource_group_name: str, - server_name: str, - private_endpoint_connection_name: str, - **kwargs: Any + self, resource_group_name: str, server_name: str, private_endpoint_connection_name: str, **kwargs: Any ) -> _models.PrivateEndpointConnection: """Gets a private endpoint connection. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param private_endpoint_connection_name: The name of the private endpoint connection. + :param private_endpoint_connection_name: The name of the private endpoint connection. Required. :type private_endpoint_connection_name: str - :keyword api_version: Api Version. Default value is "2018-06-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: PrivateEndpointConnection, or the result of cls(response) + :return: PrivateEndpointConnection or the result of cls(response) :rtype: ~azure.mgmt.rdbms.mysql.models.PrivateEndpointConnection - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.PrivateEndpointConnection] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PrivateEndpointConnection] - request = build_get_request( resource_group_name=resource_group_name, server_name=server_name, private_endpoint_connection_name=private_endpoint_connection_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], headers=_headers, params=_params, ) @@ -307,49 +301,56 @@ def get( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore def _create_or_update_initial( self, resource_group_name: str, server_name: str, private_endpoint_connection_name: str, - parameters: _models.PrivateEndpointConnection, + parameters: Union[_models.PrivateEndpointConnection, IO], **kwargs: Any ) -> Optional[_models.PrivateEndpointConnection]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[Optional[_models.PrivateEndpointConnection]] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.PrivateEndpointConnection]] - _json = self._serialize.body(parameters, 'PrivateEndpointConnection') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PrivateEndpointConnection") - request = build_create_or_update_request_initial( + request = build_create_or_update_request( resource_group_name=resource_group_name, server_name=server_name, private_endpoint_connection_name=private_endpoint_connection_name, @@ -357,7 +358,8 @@ def _create_or_update_initial( api_version=api_version, content_type=content_type, json=_json, - template_url=self._create_or_update_initial.metadata['url'], + content=_content, + template_url=self._create_or_update_initial.metadata["url"], headers=_headers, params=_params, ) @@ -365,10 +367,9 @@ def _create_or_update_initial( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202]: @@ -377,38 +378,79 @@ def _create_or_update_initial( deserialized = None if response.status_code == 200: - deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _create_or_update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore + _create_or_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore - - @distributed_trace + @overload def begin_create_or_update( self, resource_group_name: str, server_name: str, private_endpoint_connection_name: str, parameters: _models.PrivateEndpointConnection, + *, + content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.PrivateEndpointConnection]: """Approve or reject a private endpoint connection with a given name. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param private_endpoint_connection_name: + :param private_endpoint_connection_name: Required. :type private_endpoint_connection_name: str - :param parameters: + :param parameters: Required. :type parameters: ~azure.mgmt.rdbms.mysql.models.PrivateEndpointConnection - :keyword api_version: Api Version. Default value is "2018-06-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either PrivateEndpointConnection or the result + of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql.models.PrivateEndpointConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + private_endpoint_connection_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.PrivateEndpointConnection]: + """Approve or reject a private endpoint connection with a given name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param private_endpoint_connection_name: Required. + :type private_endpoint_connection_name: str + :param parameters: Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :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 @@ -420,20 +462,54 @@ def begin_create_or_update( :return: An instance of LROPoller that returns either PrivateEndpointConnection or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql.models.PrivateEndpointConnection] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + private_endpoint_connection_name: str, + parameters: Union[_models.PrivateEndpointConnection, IO], + **kwargs: Any + ) -> LROPoller[_models.PrivateEndpointConnection]: + """Approve or reject a private endpoint connection with a given name. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param private_endpoint_connection_name: Required. + :type private_endpoint_connection_name: str + :param parameters: Is either a model type or a IO type. Required. + :type parameters: ~azure.mgmt.rdbms.mysql.models.PrivateEndpointConnection or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either PrivateEndpointConnection or the result + of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql.models.PrivateEndpointConnection] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[_models.PrivateEndpointConnection] - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.PrivateEndpointConnection] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = self._create_or_update_initial( # type: ignore resource_group_name=resource_group_name, @@ -442,66 +518,60 @@ def begin_create_or_update( parameters=parameters, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - if polling is True: - polling_method = cast(PollingMethod, ARMPolling( - lro_delay, - - - **kwargs - )) # type: PollingMethod - elif polling is False: polling_method = cast(PollingMethod, NoPolling()) - else: polling_method = polling + polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_create_or_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore + begin_create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore def _delete_initial( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - server_name: str, - private_endpoint_connection_name: str, - **kwargs: Any + self, resource_group_name: str, server_name: str, private_endpoint_connection_name: str, **kwargs: Any ) -> None: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] - - request = build_delete_request_initial( + request = build_delete_request( resource_group_name=resource_group_name, server_name=server_name, private_endpoint_connection_name=private_endpoint_connection_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._delete_initial.metadata['url'], + template_url=self._delete_initial.metadata["url"], headers=_headers, params=_params, ) @@ -509,10 +579,9 @@ def _delete_initial( # pylint: disable=inconsistent-return-statements request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: @@ -522,28 +591,21 @@ def _delete_initial( # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - _delete_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore - + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore @distributed_trace - def begin_delete( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - server_name: str, - private_endpoint_connection_name: str, - **kwargs: Any + def begin_delete( + self, resource_group_name: str, server_name: str, private_endpoint_connection_name: str, **kwargs: Any ) -> LROPoller[None]: """Deletes a private endpoint connection with a given name. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param private_endpoint_connection_name: + :param private_endpoint_connection_name: Required. :type private_endpoint_connection_name: str - :keyword api_version: Api Version. Default value is "2018-06-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function 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 @@ -554,88 +616,91 @@ def begin_delete( # pylint: disable=inconsistent-return-statements Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = self._delete_initial( # type: ignore resource_group_name=resource_group_name, server_name=server_name, private_endpoint_connection_name=private_endpoint_connection_name, api_version=api_version, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - if polling is True: - polling_method = cast(PollingMethod, ARMPolling( - lro_delay, - - - **kwargs - )) # type: PollingMethod - elif polling is False: polling_method = cast(PollingMethod, NoPolling()) - else: polling_method = polling + polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_delete.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore def _update_tags_initial( self, resource_group_name: str, server_name: str, private_endpoint_connection_name: str, - parameters: _models.TagsObject, + parameters: Union[_models.TagsObject, IO], **kwargs: Any ) -> _models.PrivateEndpointConnection: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[_models.PrivateEndpointConnection] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.PrivateEndpointConnection] - _json = self._serialize.body(parameters, 'TagsObject') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "TagsObject") - request = build_update_tags_request_initial( - subscription_id=self._config.subscription_id, + request = build_update_tags_request( resource_group_name=resource_group_name, server_name=server_name, private_endpoint_connection_name=private_endpoint_connection_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._update_tags_initial.metadata['url'], + content=_content, + template_url=self._update_tags_initial.metadata["url"], headers=_headers, params=_params, ) @@ -643,33 +708,33 @@ def _update_tags_initial( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _update_tags_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore + _update_tags_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore - - @distributed_trace + @overload def begin_update_tags( self, resource_group_name: str, server_name: str, private_endpoint_connection_name: str, parameters: _models.TagsObject, + *, + content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.PrivateEndpointConnection]: """Updates tags on private endpoint connection. @@ -677,17 +742,100 @@ def begin_update_tags( Updates private endpoint connection with the specified tags. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param private_endpoint_connection_name: + :param private_endpoint_connection_name: Required. :type private_endpoint_connection_name: str :param parameters: Parameters supplied to the Update private endpoint connection Tags - operation. + operation. Required. :type parameters: ~azure.mgmt.rdbms.mysql.models.TagsObject - :keyword api_version: Api Version. Default value is "2018-06-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either PrivateEndpointConnection or the result + of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql.models.PrivateEndpointConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_update_tags( + self, + resource_group_name: str, + server_name: str, + private_endpoint_connection_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.PrivateEndpointConnection]: + """Updates tags on private endpoint connection. + + Updates private endpoint connection with the specified tags. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param private_endpoint_connection_name: Required. + :type private_endpoint_connection_name: str + :param parameters: Parameters supplied to the Update private endpoint connection Tags + operation. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either PrivateEndpointConnection or the result + of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql.models.PrivateEndpointConnection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_update_tags( + self, + resource_group_name: str, + server_name: str, + private_endpoint_connection_name: str, + parameters: Union[_models.TagsObject, IO], + **kwargs: Any + ) -> LROPoller[_models.PrivateEndpointConnection]: + """Updates tags on private endpoint connection. + + Updates private endpoint connection with the specified tags. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param private_endpoint_connection_name: Required. + :type private_endpoint_connection_name: str + :param parameters: Parameters supplied to the Update private endpoint connection Tags + operation. Is either a model type or a IO type. Required. + :type parameters: ~azure.mgmt.rdbms.mysql.models.TagsObject or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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 @@ -699,20 +847,17 @@ def begin_update_tags( :return: An instance of LROPoller that returns either PrivateEndpointConnection or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql.models.PrivateEndpointConnection] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[_models.PrivateEndpointConnection] - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.PrivateEndpointConnection] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = self._update_tags_initial( # type: ignore resource_group_name=resource_group_name, @@ -721,82 +866,76 @@ def begin_update_tags( parameters=parameters, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize('PrivateEndpointConnection', pipeline_response) + deserialized = self._deserialize("PrivateEndpointConnection", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - if polling is True: - polling_method = cast(PollingMethod, ARMPolling( - lro_delay, - - - **kwargs - )) # type: PollingMethod - elif polling is False: polling_method = cast(PollingMethod, NoPolling()) - else: polling_method = polling + polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_update_tags.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore + begin_update_tags.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateEndpointConnections/{privateEndpointConnectionName}"} # type: ignore @distributed_trace def list_by_server( - self, - resource_group_name: str, - server_name: str, - **kwargs: Any - ) -> Iterable[_models.PrivateEndpointConnectionListResult]: + self, resource_group_name: str, server_name: str, **kwargs: Any + ) -> Iterable["_models.PrivateEndpointConnection"]: """Gets all private endpoint connections on a server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :keyword api_version: Api Version. Default value is "2018-06-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PrivateEndpointConnectionListResult or the result - of cls(response) - :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql.models.PrivateEndpointConnectionListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either PrivateEndpointConnection or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql.models.PrivateEndpointConnection] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.PrivateEndpointConnectionListResult] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PrivateEndpointConnectionListResult] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_server_request( resource_group_name=resource_group_name, server_name=server_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_server.metadata['url'], + template_url=self.list_by_server.metadata["url"], headers=_headers, params=_params, ) @@ -804,16 +943,7 @@ def prepare_request(next_link=None): request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_by_server_request( - resource_group_name=resource_group_name, - server_name=server_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - template_url=next_link, - headers=_headers, - params=_params, - ) + request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" @@ -829,10 +959,8 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -842,8 +970,6 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list_by_server.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateEndpointConnections"} # type: ignore + list_by_server.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateEndpointConnections"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_private_link_resources_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_private_link_resources_operations.py index 66cd9cfcbb08..31046a995d39 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_private_link_resources_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_private_link_resources_operations.py @@ -8,9 +8,14 @@ # -------------------------------------------------------------------------- from typing import Any, Callable, Dict, Iterable, Optional, TypeVar -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse @@ -20,87 +25,82 @@ from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer from .._vendor import MixinABC, _convert_request, _format_url_section -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False + def build_list_by_server_request( - resource_group_name: str, - server_name: str, - subscription_id: str, - **kwargs: Any + resource_group_name: str, server_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateLinkResources") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateLinkResources", + ) # pylint: disable=line-too-long path_format_arguments = { - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_get_request( - resource_group_name: str, - server_name: str, - group_name: str, - subscription_id: str, - **kwargs: Any + resource_group_name: str, server_name: str, group_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateLinkResources/{groupName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateLinkResources/{groupName}", + ) # pylint: disable=line-too-long path_format_arguments = { - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), - "groupName": _SERIALIZER.url("group_name", group_name, 'str'), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), + "groupName": _SERIALIZER.url("group_name", group_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) class PrivateLinkResourcesOperations: """ @@ -121,49 +121,45 @@ def __init__(self, *args, **kwargs): self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace def list_by_server( - self, - resource_group_name: str, - server_name: str, - **kwargs: Any - ) -> Iterable[_models.PrivateLinkResourceListResult]: + self, resource_group_name: str, server_name: str, **kwargs: Any + ) -> Iterable["_models.PrivateLinkResource"]: """Gets the private link resources for MySQL server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :keyword api_version: Api Version. Default value is "2018-06-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PrivateLinkResourceListResult or the result of - cls(response) - :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql.models.PrivateLinkResourceListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either PrivateLinkResource or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql.models.PrivateLinkResource] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.PrivateLinkResourceListResult] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PrivateLinkResourceListResult] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_server_request( resource_group_name=resource_group_name, server_name=server_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_server.metadata['url'], + template_url=self.list_by_server.metadata["url"], headers=_headers, params=_params, ) @@ -171,16 +167,7 @@ def prepare_request(next_link=None): request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_by_server_request( - resource_group_name=resource_group_name, - server_name=server_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - template_url=next_link, - headers=_headers, - params=_params, - ) + request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" @@ -196,10 +183,8 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -209,55 +194,49 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list_by_server.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateLinkResources"} # type: ignore + list_by_server.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateLinkResources"} # type: ignore @distributed_trace def get( - self, - resource_group_name: str, - server_name: str, - group_name: str, - **kwargs: Any + self, resource_group_name: str, server_name: str, group_name: str, **kwargs: Any ) -> _models.PrivateLinkResource: """Gets a private link resource for MySQL server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param group_name: The name of the private link resource. + :param group_name: The name of the private link resource. Required. :type group_name: str - :keyword api_version: Api Version. Default value is "2018-06-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: PrivateLinkResource, or the result of cls(response) + :return: PrivateLinkResource or the result of cls(response) :rtype: ~azure.mgmt.rdbms.mysql.models.PrivateLinkResource - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.PrivateLinkResource] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PrivateLinkResource] - request = build_get_request( resource_group_name=resource_group_name, server_name=server_name, group_name=group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], headers=_headers, params=_params, ) @@ -265,22 +244,20 @@ def get( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('PrivateLinkResource', pipeline_response) + deserialized = self._deserialize("PrivateLinkResource", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateLinkResources/{groupName}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/privateLinkResources/{groupName}"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_query_texts_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_query_texts_operations.py index 87a3e9b81a67..44a478e1da33 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_query_texts_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_query_texts_operations.py @@ -8,9 +8,14 @@ # -------------------------------------------------------------------------- from typing import Any, Callable, Dict, Iterable, List, Optional, TypeVar -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse @@ -20,90 +25,83 @@ from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer from .._vendor import MixinABC, _convert_request, _format_url_section -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False + def build_get_request( - subscription_id: str, - resource_group_name: str, - server_name: str, - query_id: str, - **kwargs: Any + resource_group_name: str, server_name: str, query_id: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/queryTexts/{queryId}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/queryTexts/{queryId}", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), - "queryId": _SERIALIZER.url("query_id", query_id, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), + "queryId": _SERIALIZER.url("query_id", query_id, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_list_by_server_request( - subscription_id: str, - resource_group_name: str, - server_name: str, - *, - query_ids: List[str], - **kwargs: Any + resource_group_name: str, server_name: str, subscription_id: str, *, query_ids: List[str], **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/queryTexts") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/queryTexts", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') - _params['queryIds'] = [_SERIALIZER.query("query_ids", q, 'str') if q is not None else '' for q in query_ids] + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + _params["queryIds"] = [_SERIALIZER.query("query_ids", q, "str") if q is not None else "" for q in query_ids] # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) class QueryTextsOperations: """ @@ -124,50 +122,43 @@ def __init__(self, *args, **kwargs): self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace - def get( - self, - resource_group_name: str, - server_name: str, - query_id: str, - **kwargs: Any - ) -> _models.QueryText: + def get(self, resource_group_name: str, server_name: str, query_id: str, **kwargs: Any) -> _models.QueryText: """Retrieve the Query-Store query texts for the queryId. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param query_id: The Query-Store query identifier. + :param query_id: The Query-Store query identifier. Required. :type query_id: str - :keyword api_version: Api Version. Default value is "2018-06-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: QueryText, or the result of cls(response) + :return: QueryText or the result of cls(response) :rtype: ~azure.mgmt.rdbms.mysql.models.QueryText - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.QueryText] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.QueryText] - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, query_id=query_id, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], headers=_headers, params=_params, ) @@ -175,71 +166,66 @@ def get( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('QueryText', pipeline_response) + deserialized = self._deserialize("QueryText", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/queryTexts/{queryId}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/queryTexts/{queryId}"} # type: ignore @distributed_trace def list_by_server( - self, - resource_group_name: str, - server_name: str, - query_ids: List[str], - **kwargs: Any - ) -> Iterable[_models.QueryTextsResultList]: + self, resource_group_name: str, server_name: str, query_ids: List[str], **kwargs: Any + ) -> Iterable["_models.QueryText"]: """Retrieve the Query-Store query texts for specified queryIds. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param query_ids: The query identifiers. + :param query_ids: The query identifiers. Required. :type query_ids: list[str] - :keyword api_version: Api Version. Default value is "2018-06-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either QueryTextsResultList or the result of - cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql.models.QueryTextsResultList] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either QueryText or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql.models.QueryText] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.QueryTextsResultList] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.QueryTextsResultList] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_server_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, - api_version=api_version, + subscription_id=self._config.subscription_id, query_ids=query_ids, - template_url=self.list_by_server.metadata['url'], + api_version=api_version, + template_url=self.list_by_server.metadata["url"], headers=_headers, params=_params, ) @@ -247,17 +233,7 @@ def prepare_request(next_link=None): request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_by_server_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - server_name=server_name, - api_version=api_version, - query_ids=query_ids, - template_url=next_link, - headers=_headers, - params=_params, - ) + request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" @@ -273,10 +249,8 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -286,8 +260,6 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list_by_server.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/queryTexts"} # type: ignore + list_by_server.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/queryTexts"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_recommended_actions_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_recommended_actions_operations.py index 1d1bc5eddbb7..f8beda5ace57 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_recommended_actions_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_recommended_actions_operations.py @@ -8,9 +8,14 @@ # -------------------------------------------------------------------------- from typing import Any, Callable, Dict, Iterable, Optional, TypeVar -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse @@ -20,59 +25,61 @@ from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer from .._vendor import MixinABC, _convert_request, _format_url_section -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False + def build_get_request( - subscription_id: str, resource_group_name: str, server_name: str, advisor_name: str, recommended_action_name: str, + subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/advisors/{advisorName}/recommendedActions/{recommendedActionName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/advisors/{advisorName}/recommendedActions/{recommendedActionName}", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), - "advisorName": _SERIALIZER.url("advisor_name", advisor_name, 'str'), - "recommendedActionName": _SERIALIZER.url("recommended_action_name", recommended_action_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), + "advisorName": _SERIALIZER.url("advisor_name", advisor_name, "str"), + "recommendedActionName": _SERIALIZER.url("recommended_action_name", recommended_action_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_list_by_server_request( - subscription_id: str, resource_group_name: str, server_name: str, advisor_name: str, + subscription_id: str, *, session_id: Optional[str] = None, **kwargs: Any @@ -80,35 +87,35 @@ def build_list_by_server_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/advisors/{advisorName}/recommendedActions") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/advisors/{advisorName}/recommendedActions", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), - "advisorName": _SERIALIZER.url("advisor_name", advisor_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), + "advisorName": _SERIALIZER.url("advisor_name", advisor_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if session_id is not None: - _params['sessionId'] = _SERIALIZER.query("session_id", session_id, 'str') + _params["sessionId"] = _SERIALIZER.query("session_id", session_id, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) class RecommendedActionsOperations: """ @@ -129,54 +136,48 @@ def __init__(self, *args, **kwargs): self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace def get( - self, - resource_group_name: str, - server_name: str, - advisor_name: str, - recommended_action_name: str, - **kwargs: Any + self, resource_group_name: str, server_name: str, advisor_name: str, recommended_action_name: str, **kwargs: Any ) -> _models.RecommendationAction: """Retrieve recommended actions from the advisor. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param advisor_name: The advisor name for recommendation action. + :param advisor_name: The advisor name for recommendation action. Required. :type advisor_name: str - :param recommended_action_name: The recommended action name. + :param recommended_action_name: The recommended action name. Required. :type recommended_action_name: str - :keyword api_version: Api Version. Default value is "2018-06-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RecommendationAction, or the result of cls(response) + :return: RecommendationAction or the result of cls(response) :rtype: ~azure.mgmt.rdbms.mysql.models.RecommendationAction - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.RecommendationAction] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RecommendationAction] - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, advisor_name=advisor_name, recommended_action_name=recommended_action_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], headers=_headers, params=_params, ) @@ -184,25 +185,23 @@ def get( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('RecommendationAction', pipeline_response) + deserialized = self._deserialize("RecommendationAction", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/advisors/{advisorName}/recommendedActions/{recommendedActionName}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/advisors/{advisorName}/recommendedActions/{recommendedActionName}"} # type: ignore @distributed_trace def list_by_server( @@ -212,48 +211,49 @@ def list_by_server( advisor_name: str, session_id: Optional[str] = None, **kwargs: Any - ) -> Iterable[_models.RecommendationActionsResultList]: + ) -> Iterable["_models.RecommendationAction"]: """Retrieve recommended actions from the advisor. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param advisor_name: The advisor name for recommendation action. + :param advisor_name: The advisor name for recommendation action. Required. :type advisor_name: str :param session_id: The recommendation action session identifier. Default value is None. :type session_id: str - :keyword api_version: Api Version. Default value is "2018-06-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RecommendationActionsResultList or the result of + :return: An iterator like instance of either RecommendationAction or the result of cls(response) - :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql.models.RecommendationActionsResultList] - :raises: ~azure.core.exceptions.HttpResponseError + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql.models.RecommendationAction] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.RecommendationActionsResultList] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RecommendationActionsResultList] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_server_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, advisor_name=advisor_name, - api_version=api_version, + subscription_id=self._config.subscription_id, session_id=session_id, - template_url=self.list_by_server.metadata['url'], + api_version=api_version, + template_url=self.list_by_server.metadata["url"], headers=_headers, params=_params, ) @@ -261,18 +261,7 @@ def prepare_request(next_link=None): request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_by_server_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - server_name=server_name, - advisor_name=advisor_name, - api_version=api_version, - session_id=session_id, - template_url=next_link, - headers=_headers, - params=_params, - ) + request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" @@ -288,10 +277,8 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -301,8 +288,6 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list_by_server.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/advisors/{advisorName}/recommendedActions"} # type: ignore + list_by_server.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/advisors/{advisorName}/recommendedActions"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_recoverable_servers_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_recoverable_servers_operations.py index 5e590bb8dd97..c6c927605f77 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_recoverable_servers_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_recoverable_servers_operations.py @@ -8,9 +8,14 @@ # -------------------------------------------------------------------------- from typing import Any, Callable, Dict, Optional, TypeVar -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest @@ -19,48 +24,46 @@ from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer from .._vendor import MixinABC, _convert_request, _format_url_section -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_get_request( - subscription_id: str, - resource_group_name: str, - server_name: str, - **kwargs: Any -) -> HttpRequest: + +def build_get_request(resource_group_name: str, server_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/recoverableServers") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/recoverableServers", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) class RecoverableServersOperations: """ @@ -81,46 +84,40 @@ def __init__(self, *args, **kwargs): self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace - def get( - self, - resource_group_name: str, - server_name: str, - **kwargs: Any - ) -> _models.RecoverableServerResource: + def get(self, resource_group_name: str, server_name: str, **kwargs: Any) -> _models.RecoverableServerResource: """Gets a recoverable MySQL Server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: RecoverableServerResource, or the result of cls(response) + :return: RecoverableServerResource or the result of cls(response) :rtype: ~azure.mgmt.rdbms.mysql.models.RecoverableServerResource - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.RecoverableServerResource] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RecoverableServerResource] - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], headers=_headers, params=_params, ) @@ -128,22 +125,20 @@ def get( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('RecoverableServerResource', pipeline_response) + deserialized = self._deserialize("RecoverableServerResource", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/recoverableServers"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/recoverableServers"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_replicas_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_replicas_operations.py index 081b77a63aec..4585730a4947 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_replicas_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_replicas_operations.py @@ -8,9 +8,14 @@ # -------------------------------------------------------------------------- from typing import Any, Callable, Dict, Iterable, Optional, TypeVar -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse @@ -20,48 +25,48 @@ from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer from .._vendor import MixinABC, _convert_request, _format_url_section -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False + def build_list_by_server_request( - subscription_id: str, - resource_group_name: str, - server_name: str, - **kwargs: Any + resource_group_name: str, server_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/replicas") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/replicas", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) class ReplicasOperations: """ @@ -82,47 +87,43 @@ def __init__(self, *args, **kwargs): self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace - def list_by_server( - self, - resource_group_name: str, - server_name: str, - **kwargs: Any - ) -> Iterable[_models.ServerListResult]: + def list_by_server(self, resource_group_name: str, server_name: str, **kwargs: Any) -> Iterable["_models.Server"]: """List all the replicas for a given server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ServerListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql.models.ServerListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Server or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql.models.Server] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.ServerListResult] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ServerListResult] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_server_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_server.metadata['url'], + template_url=self.list_by_server.metadata["url"], headers=_headers, params=_params, ) @@ -130,16 +131,7 @@ def prepare_request(next_link=None): request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_by_server_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - server_name=server_name, - api_version=api_version, - template_url=next_link, - headers=_headers, - params=_params, - ) + request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" @@ -155,10 +147,8 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -168,8 +158,6 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list_by_server.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/replicas"} # type: ignore + list_by_server.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/replicas"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_server_administrators_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_server_administrators_operations.py index ab1cfbf781c4..dd9d8d136e08 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_server_administrators_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_server_administrators_operations.py @@ -6,11 +6,16 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Iterable, Optional, TypeVar, Union, cast - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse @@ -22,167 +27,146 @@ from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models +from .._serialization import Serializer from .._vendor import MixinABC, _convert_request, _format_url_section -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_get_request( - subscription_id: str, - resource_group_name: str, - server_name: str, - **kwargs: Any -) -> HttpRequest: + +def build_get_request(resource_group_name: str, server_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/administrators/activeDirectory") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/administrators/activeDirectory", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) - - -def build_create_or_update_request_initial( - subscription_id: str, - resource_group_name: str, - server_name: str, - *, - json: Optional[_models.ServerAdministratorResource] = None, - content: Any = None, - **kwargs: Any + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_or_update_request( + resource_group_name: str, server_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', None)) # type: Optional[str] - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/administrators/activeDirectory") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/administrators/activeDirectory", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _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, - json=json, - content=content, - **kwargs - ) - - -def build_delete_request_initial( - subscription_id: str, - resource_group_name: str, - server_name: str, - **kwargs: Any + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_request( + resource_group_name: str, server_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/administrators/activeDirectory") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/administrators/activeDirectory", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="DELETE", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) - - -def build_list_request( - subscription_id: str, - resource_group_name: str, - server_name: str, - **kwargs: Any -) -> HttpRequest: + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_request(resource_group_name: str, server_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/administrators") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/administrators", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) class ServerAdministratorsOperations: """ @@ -203,46 +187,40 @@ def __init__(self, *args, **kwargs): self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace - def get( - self, - resource_group_name: str, - server_name: str, - **kwargs: Any - ) -> _models.ServerAdministratorResource: + def get(self, resource_group_name: str, server_name: str, **kwargs: Any) -> _models.ServerAdministratorResource: """Gets information about a AAD server administrator. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: ServerAdministratorResource, or the result of cls(response) + :return: ServerAdministratorResource or the result of cls(response) :rtype: ~azure.mgmt.rdbms.mysql.models.ServerAdministratorResource - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.ServerAdministratorResource] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ServerAdministratorResource] - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], headers=_headers, params=_params, ) @@ -250,55 +228,63 @@ def get( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('ServerAdministratorResource', pipeline_response) + deserialized = self._deserialize("ServerAdministratorResource", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/administrators/activeDirectory"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/administrators/activeDirectory"} # type: ignore def _create_or_update_initial( self, resource_group_name: str, server_name: str, - properties: _models.ServerAdministratorResource, + properties: Union[_models.ServerAdministratorResource, IO], **kwargs: Any ) -> _models.ServerAdministratorResource: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[_models.ServerAdministratorResource] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ServerAdministratorResource] - _json = self._serialize.body(properties, 'ServerAdministratorResource') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(properties, (IO, bytes)): + _content = properties + else: + _json = self._serialize.body(properties, "ServerAdministratorResource") - request = build_create_or_update_request_initial( - subscription_id=self._config.subscription_id, + request = build_create_or_update_request( resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._create_or_update_initial.metadata['url'], + content=_content, + template_url=self._create_or_update_initial.metadata["url"], headers=_headers, params=_params, ) @@ -306,10 +292,9 @@ def _create_or_update_initial( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202]: @@ -317,40 +302,118 @@ def _create_or_update_initial( raise HttpResponseError(response=response, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('ServerAdministratorResource', pipeline_response) + deserialized = self._deserialize("ServerAdministratorResource", pipeline_response) if response.status_code == 202: - deserialized = self._deserialize('ServerAdministratorResource', pipeline_response) + deserialized = self._deserialize("ServerAdministratorResource", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _create_or_update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/administrators/activeDirectory"} # type: ignore - + _create_or_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/administrators/activeDirectory"} # type: ignore - @distributed_trace + @overload def begin_create_or_update( self, resource_group_name: str, server_name: str, properties: _models.ServerAdministratorResource, + *, + content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.ServerAdministratorResource]: """Creates or update active directory administrator on an existing server. The update action will overwrite the existing administrator. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str :param properties: The required parameters for creating or updating an AAD server - administrator. + administrator. Required. :type properties: ~azure.mgmt.rdbms.mysql.models.ServerAdministratorResource - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :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 ServerAdministratorResource or the result + of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql.models.ServerAdministratorResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + properties: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.ServerAdministratorResource]: + """Creates or update active directory administrator on an existing server. The update action will + overwrite the existing administrator. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param properties: The required parameters for creating or updating an AAD server + administrator. Required. + :type properties: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either ServerAdministratorResource or the result + of cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql.models.ServerAdministratorResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + properties: Union[_models.ServerAdministratorResource, IO], + **kwargs: Any + ) -> LROPoller[_models.ServerAdministratorResource]: + """Creates or update active directory administrator on an existing server. The update action will + overwrite the existing administrator. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param properties: The required parameters for creating or updating an AAD server + administrator. Is either a model type or a IO type. Required. + :type properties: ~azure.mgmt.rdbms.mysql.models.ServerAdministratorResource or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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 @@ -363,20 +426,17 @@ def begin_create_or_update( of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql.models.ServerAdministratorResource] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[_models.ServerAdministratorResource] - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ServerAdministratorResource] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = self._create_or_update_initial( # type: ignore resource_group_name=resource_group_name, @@ -384,64 +444,59 @@ def begin_create_or_update( properties=properties, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize('ServerAdministratorResource', pipeline_response) + deserialized = self._deserialize("ServerAdministratorResource", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - if polling is True: - polling_method = cast(PollingMethod, ARMPolling( - lro_delay, - - - **kwargs - )) # type: PollingMethod - elif polling is False: polling_method = cast(PollingMethod, NoPolling()) - else: polling_method = polling + polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_create_or_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/administrators/activeDirectory"} # type: ignore + begin_create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/administrators/activeDirectory"} # type: ignore def _delete_initial( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - server_name: str, - **kwargs: Any + self, resource_group_name: str, server_name: str, **kwargs: Any ) -> None: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] - - request = build_delete_request_initial( - subscription_id=self._config.subscription_id, + request = build_delete_request( resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._delete_initial.metadata['url'], + template_url=self._delete_initial.metadata["url"], headers=_headers, params=_params, ) @@ -449,10 +504,9 @@ def _delete_initial( # pylint: disable=inconsistent-return-statements request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: @@ -462,25 +516,17 @@ def _delete_initial( # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - _delete_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/administrators/activeDirectory"} # type: ignore - + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/administrators/activeDirectory"} # type: ignore @distributed_trace - def begin_delete( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - server_name: str, - **kwargs: Any - ) -> LROPoller[None]: + def begin_delete(self, resource_group_name: str, server_name: str, **kwargs: Any) -> LROPoller[None]: """Deletes server active directory administrator. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function 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 @@ -491,98 +537,90 @@ def begin_delete( # pylint: disable=inconsistent-return-statements Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = self._delete_initial( # type: ignore resource_group_name=resource_group_name, server_name=server_name, api_version=api_version, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - if polling is True: - polling_method = cast(PollingMethod, ARMPolling( - lro_delay, - - - **kwargs - )) # type: PollingMethod - elif polling is False: polling_method = cast(PollingMethod, NoPolling()) - else: polling_method = polling + polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_delete.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/administrators/activeDirectory"} # type: ignore + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/administrators/activeDirectory"} # type: ignore @distributed_trace def list( - self, - resource_group_name: str, - server_name: str, - **kwargs: Any - ) -> Iterable[_models.ServerAdministratorResourceListResult]: + self, resource_group_name: str, server_name: str, **kwargs: Any + ) -> Iterable["_models.ServerAdministratorResource"]: """Returns a list of server Administrators. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ServerAdministratorResourceListResult or the - result of cls(response) + :return: An iterator like instance of either ServerAdministratorResource or the result of + cls(response) :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql.models.ServerAdministratorResourceListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql.models.ServerAdministratorResource] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.ServerAdministratorResourceListResult] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ServerAdministratorResourceListResult] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list.metadata['url'], + template_url=self.list.metadata["url"], headers=_headers, params=_params, ) @@ -590,16 +628,7 @@ def prepare_request(next_link=None): request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - server_name=server_name, - api_version=api_version, - template_url=next_link, - headers=_headers, - params=_params, - ) + request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" @@ -615,10 +644,8 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -628,8 +655,6 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/administrators"} # type: ignore + list.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/administrators"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_server_based_performance_tier_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_server_based_performance_tier_operations.py index a8f4ae99954b..1191370051d4 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_server_based_performance_tier_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_server_based_performance_tier_operations.py @@ -8,9 +8,14 @@ # -------------------------------------------------------------------------- from typing import Any, Callable, Dict, Iterable, Optional, TypeVar -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse @@ -20,48 +25,46 @@ from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer from .._vendor import MixinABC, _convert_request, _format_url_section -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_list_request( - subscription_id: str, - resource_group_name: str, - server_name: str, - **kwargs: Any -) -> HttpRequest: + +def build_list_request(resource_group_name: str, server_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/performanceTiers") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/performanceTiers", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) class ServerBasedPerformanceTierOperations: """ @@ -82,48 +85,46 @@ def __init__(self, *args, **kwargs): self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace def list( - self, - resource_group_name: str, - server_name: str, - **kwargs: Any - ) -> Iterable[_models.PerformanceTierListResult]: + self, resource_group_name: str, server_name: str, **kwargs: Any + ) -> Iterable["_models.PerformanceTierProperties"]: """List all the performance tiers for a MySQL server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PerformanceTierListResult or the result of + :return: An iterator like instance of either PerformanceTierProperties or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql.models.PerformanceTierListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql.models.PerformanceTierProperties] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.PerformanceTierListResult] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PerformanceTierListResult] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list.metadata['url'], + template_url=self.list.metadata["url"], headers=_headers, params=_params, ) @@ -131,16 +132,7 @@ def prepare_request(next_link=None): request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - server_name=server_name, - api_version=api_version, - template_url=next_link, - headers=_headers, - params=_params, - ) + request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" @@ -156,10 +148,8 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -169,8 +159,6 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/performanceTiers"} # type: ignore + list.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/performanceTiers"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_server_keys_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_server_keys_operations.py index 4e0c1c31c17f..51e7e91f6e12 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_server_keys_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_server_keys_operations.py @@ -6,11 +6,16 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Iterable, Optional, TypeVar, Union, cast - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse @@ -22,173 +27,151 @@ from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models +from .._serialization import Serializer from .._vendor import MixinABC, _convert_request, _format_url_section -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_list_request( - subscription_id: str, - resource_group_name: str, - server_name: str, - **kwargs: Any -) -> HttpRequest: + +def build_list_request(resource_group_name: str, server_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2020-01-01")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-01-01")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/keys") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/keys", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_get_request( - resource_group_name: str, - server_name: str, - key_name: str, - subscription_id: str, - **kwargs: Any + resource_group_name: str, server_name: str, key_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2020-01-01")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-01-01")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/keys/{keyName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/keys/{keyName}", + ) # pylint: disable=line-too-long path_format_arguments = { - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), - "keyName": _SERIALIZER.url("key_name", key_name, 'str'), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), + "keyName": _SERIALIZER.url("key_name", key_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) - - -def build_create_or_update_request_initial( - server_name: str, - key_name: str, - subscription_id: str, - resource_group_name: str, - *, - json: Optional[_models.ServerKey] = None, - content: Any = None, - **kwargs: Any + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_or_update_request( + server_name: str, key_name: str, resource_group_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2020-01-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', None)) # type: Optional[str] - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-01-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/keys/{keyName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/keys/{keyName}", + ) # pylint: disable=line-too-long path_format_arguments = { - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), - "keyName": _SERIALIZER.url("key_name", key_name, 'str'), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), + "keyName": _SERIALIZER.url("key_name", key_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _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, - json=json, - content=content, - **kwargs - ) - - -def build_delete_request_initial( - server_name: str, - key_name: str, - subscription_id: str, - resource_group_name: str, - **kwargs: Any + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_request( + server_name: str, key_name: str, resource_group_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2020-01-01")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-01-01")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/keys/{keyName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/keys/{keyName}", + ) # pylint: disable=line-too-long path_format_arguments = { - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), - "keyName": _SERIALIZER.url("key_name", key_name, 'str'), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), + "keyName": _SERIALIZER.url("key_name", key_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - return HttpRequest( - method="DELETE", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) class ServerKeysOperations: """ @@ -209,47 +192,43 @@ def __init__(self, *args, **kwargs): self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace - def list( - self, - resource_group_name: str, - server_name: str, - **kwargs: Any - ) -> Iterable[_models.ServerKeyListResult]: + def list(self, resource_group_name: str, server_name: str, **kwargs: Any) -> Iterable["_models.ServerKey"]: """Gets a list of Server keys. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :keyword api_version: Api Version. Default value is "2020-01-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ServerKeyListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql.models.ServerKeyListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either ServerKey or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql.models.ServerKey] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2020-01-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.ServerKeyListResult] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-01-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ServerKeyListResult] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list.metadata['url'], + template_url=self.list.metadata["url"], headers=_headers, params=_params, ) @@ -257,16 +236,7 @@ def prepare_request(next_link=None): request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - server_name=server_name, - api_version=api_version, - template_url=next_link, - headers=_headers, - params=_params, - ) + request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" @@ -282,10 +252,8 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -295,55 +263,47 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/keys"} # type: ignore + list.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/keys"} # type: ignore @distributed_trace - def get( - self, - resource_group_name: str, - server_name: str, - key_name: str, - **kwargs: Any - ) -> _models.ServerKey: + def get(self, resource_group_name: str, server_name: str, key_name: str, **kwargs: Any) -> _models.ServerKey: """Gets a MySQL Server key. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param key_name: The name of the MySQL Server key to be retrieved. + :param key_name: The name of the MySQL Server key to be retrieved. Required. :type key_name: str - :keyword api_version: Api Version. Default value is "2020-01-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: ServerKey, or the result of cls(response) + :return: ServerKey or the result of cls(response) :rtype: ~azure.mgmt.rdbms.mysql.models.ServerKey - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2020-01-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.ServerKey] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-01-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ServerKey] - request = build_get_request( resource_group_name=resource_group_name, server_name=server_name, key_name=key_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], headers=_headers, params=_params, ) @@ -351,57 +311,65 @@ def get( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('ServerKey', pipeline_response) + deserialized = self._deserialize("ServerKey", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/keys/{keyName}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/keys/{keyName}"} # type: ignore def _create_or_update_initial( self, server_name: str, key_name: str, resource_group_name: str, - parameters: _models.ServerKey, + parameters: Union[_models.ServerKey, IO], **kwargs: Any ) -> _models.ServerKey: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2020-01-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[_models.ServerKey] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-01-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ServerKey] - _json = self._serialize.body(parameters, 'ServerKey') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ServerKey") - request = build_create_or_update_request_initial( + request = build_create_or_update_request( server_name=server_name, key_name=key_name, - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._create_or_update_initial.metadata['url'], + content=_content, + template_url=self._create_or_update_initial.metadata["url"], headers=_headers, params=_params, ) @@ -409,10 +377,9 @@ def _create_or_update_initial( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202]: @@ -420,41 +387,44 @@ def _create_or_update_initial( raise HttpResponseError(response=response, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('ServerKey', pipeline_response) + deserialized = self._deserialize("ServerKey", pipeline_response) if response.status_code == 202: - deserialized = self._deserialize('ServerKey', pipeline_response) + deserialized = self._deserialize("ServerKey", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _create_or_update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/keys/{keyName}"} # type: ignore - + _create_or_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/keys/{keyName}"} # type: ignore - @distributed_trace + @overload def begin_create_or_update( self, server_name: str, key_name: str, resource_group_name: str, parameters: _models.ServerKey, + *, + content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.ServerKey]: """Creates or updates a MySQL Server key. - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str :param key_name: The name of the MySQL Server key to be operated on (updated or created). + Required. :type key_name: str :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param parameters: The requested MySQL Server key resource state. + :param parameters: The requested MySQL Server key resource state. Required. :type parameters: ~azure.mgmt.rdbms.mysql.models.ServerKey - :keyword api_version: Api Version. Default value is "2020-01-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this @@ -465,20 +435,94 @@ def begin_create_or_update( Retry-After header is present. :return: An instance of LROPoller that returns either ServerKey or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql.models.ServerKey] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_or_update( + self, + server_name: str, + key_name: str, + resource_group_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.ServerKey]: + """Creates or updates a MySQL Server key. + + :param server_name: The name of the server. Required. + :type server_name: str + :param key_name: The name of the MySQL Server key to be operated on (updated or created). + Required. + :type key_name: str + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param parameters: The requested MySQL Server key resource state. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :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 ServerKey or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql.models.ServerKey] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_or_update( + self, + server_name: str, + key_name: str, + resource_group_name: str, + parameters: Union[_models.ServerKey, IO], + **kwargs: Any + ) -> LROPoller[_models.ServerKey]: + """Creates or updates a MySQL Server key. + + :param server_name: The name of the server. Required. + :type server_name: str + :param key_name: The name of the MySQL Server key to be operated on (updated or created). + Required. + :type key_name: str + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param parameters: The requested MySQL Server key resource state. Is either a model type or a + IO type. Required. + :type parameters: ~azure.mgmt.rdbms.mysql.models.ServerKey or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either ServerKey or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql.models.ServerKey] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2020-01-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[_models.ServerKey] - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-01-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ServerKey] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = self._create_or_update_initial( # type: ignore server_name=server_name, @@ -487,66 +531,60 @@ def begin_create_or_update( parameters=parameters, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize('ServerKey', pipeline_response) + deserialized = self._deserialize("ServerKey", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - if polling is True: - polling_method = cast(PollingMethod, ARMPolling( - lro_delay, - - - **kwargs - )) # type: PollingMethod - elif polling is False: polling_method = cast(PollingMethod, NoPolling()) - else: polling_method = polling + polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_create_or_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/keys/{keyName}"} # type: ignore + begin_create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/keys/{keyName}"} # type: ignore def _delete_initial( # pylint: disable=inconsistent-return-statements - self, - server_name: str, - key_name: str, - resource_group_name: str, - **kwargs: Any + self, server_name: str, key_name: str, resource_group_name: str, **kwargs: Any ) -> None: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2020-01-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-01-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] - - request = build_delete_request_initial( + request = build_delete_request( server_name=server_name, key_name=key_name, - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._delete_initial.metadata['url'], + template_url=self._delete_initial.metadata["url"], headers=_headers, params=_params, ) @@ -554,10 +592,9 @@ def _delete_initial( # pylint: disable=inconsistent-return-statements request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: @@ -567,28 +604,19 @@ def _delete_initial( # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - _delete_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/keys/{keyName}"} # type: ignore - + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/keys/{keyName}"} # type: ignore @distributed_trace - def begin_delete( # pylint: disable=inconsistent-return-statements - self, - server_name: str, - key_name: str, - resource_group_name: str, - **kwargs: Any - ) -> LROPoller[None]: + def begin_delete(self, server_name: str, key_name: str, resource_group_name: str, **kwargs: Any) -> LROPoller[None]: """Deletes the MySQL Server key with the given name. - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param key_name: The name of the MySQL Server key to be deleted. + :param key_name: The name of the MySQL Server key to be deleted. Required. :type key_name: str :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :keyword api_version: Api Version. Default value is "2020-01-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function 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 @@ -599,53 +627,46 @@ def begin_delete( # pylint: disable=inconsistent-return-statements Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2020-01-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-01-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = self._delete_initial( # type: ignore server_name=server_name, key_name=key_name, resource_group_name=resource_group_name, api_version=api_version, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - if polling is True: - polling_method = cast(PollingMethod, ARMPolling( - lro_delay, - - - **kwargs - )) # type: PollingMethod - elif polling is False: polling_method = cast(PollingMethod, NoPolling()) - else: polling_method = polling + polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_delete.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/keys/{keyName}"} # type: ignore + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/keys/{keyName}"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_server_parameters_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_server_parameters_operations.py index 7d18174d5d15..4fc3850460dc 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_server_parameters_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_server_parameters_operations.py @@ -6,11 +6,16 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Optional, TypeVar, Union, cast - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod @@ -21,56 +26,51 @@ from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models +from .._serialization import Serializer from .._vendor import MixinABC, _convert_request, _format_url_section -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_list_update_configurations_request_initial( - subscription_id: str, - resource_group_name: str, - server_name: str, - *, - json: Optional[_models.ConfigurationListResult] = None, - content: Any = None, - **kwargs: Any + +def build_list_update_configurations_request( + resource_group_name: str, server_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', None)) # type: Optional[str] - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/updateConfigurations") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/updateConfigurations", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if content_type is not None: - _headers['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="POST", - url=_url, - params=_params, - headers=_headers, - json=json, - content=content, - **kwargs - ) + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + class ServerParametersOperations: """ @@ -91,36 +91,45 @@ def __init__(self, *args, **kwargs): 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") - def _list_update_configurations_initial( self, resource_group_name: str, server_name: str, - value: _models.ConfigurationListResult, + value: Union[_models.ConfigurationListResult, IO], **kwargs: Any ) -> Optional[_models.ConfigurationListResult]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[Optional[_models.ConfigurationListResult]] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.ConfigurationListResult]] - _json = self._serialize.body(value, 'ConfigurationListResult') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(value, (IO, bytes)): + _content = value + else: + _json = self._serialize.body(value, "ConfigurationListResult") - request = build_list_update_configurations_request_initial( - subscription_id=self._config.subscription_id, + request = build_list_update_configurations_request( resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._list_update_configurations_initial.metadata['url'], + content=_content, + template_url=self._list_update_configurations_initial.metadata["url"], headers=_headers, params=_params, ) @@ -128,10 +137,9 @@ def _list_update_configurations_initial( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202]: @@ -140,35 +148,37 @@ def _list_update_configurations_initial( deserialized = None if response.status_code == 200: - deserialized = self._deserialize('ConfigurationListResult', pipeline_response) + deserialized = self._deserialize("ConfigurationListResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _list_update_configurations_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/updateConfigurations"} # type: ignore + _list_update_configurations_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/updateConfigurations"} # type: ignore - - @distributed_trace + @overload def begin_list_update_configurations( self, resource_group_name: str, server_name: str, value: _models.ConfigurationListResult, + *, + content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.ConfigurationListResult]: """Update a list of configurations in a given server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param value: The parameters for updating a list of server configuration. + :param value: The parameters for updating a list of server configuration. Required. :type value: ~azure.mgmt.rdbms.mysql.models.ConfigurationListResult - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :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 @@ -180,20 +190,88 @@ def begin_list_update_configurations( :return: An instance of LROPoller that returns either ConfigurationListResult or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql.models.ConfigurationListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_list_update_configurations( + self, + resource_group_name: str, + server_name: str, + value: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.ConfigurationListResult]: + """Update a list of configurations in a given server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param value: The parameters for updating a list of server configuration. Required. + :type value: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either ConfigurationListResult or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql.models.ConfigurationListResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_list_update_configurations( + self, + resource_group_name: str, + server_name: str, + value: Union[_models.ConfigurationListResult, IO], + **kwargs: Any + ) -> LROPoller[_models.ConfigurationListResult]: + """Update a list of configurations in a given server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param value: The parameters for updating a list of server configuration. Is either a model + type or a IO type. Required. + :type value: ~azure.mgmt.rdbms.mysql.models.ConfigurationListResult or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either ConfigurationListResult or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql.models.ConfigurationListResult] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[_models.ConfigurationListResult] - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ConfigurationListResult] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = self._list_update_configurations_initial( # type: ignore resource_group_name=resource_group_name, @@ -201,36 +279,34 @@ def begin_list_update_configurations( value=value, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize('ConfigurationListResult', pipeline_response) + deserialized = self._deserialize("ConfigurationListResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - if polling is True: - polling_method = cast(PollingMethod, ARMPolling( - lro_delay, - lro_options={'final-state-via': 'azure-async-operation'}, - - **kwargs - )) # type: PollingMethod - elif polling is False: polling_method = cast(PollingMethod, NoPolling()) - else: polling_method = polling + polling_method = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs) + ) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_list_update_configurations.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/updateConfigurations"} # type: ignore + begin_list_update_configurations.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/updateConfigurations"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_server_security_alert_policies_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_server_security_alert_policies_operations.py index 0beb234c03bd..d359040df1e0 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_server_security_alert_policies_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_server_security_alert_policies_operations.py @@ -6,11 +6,16 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Iterable, Optional, TypeVar, Union, cast - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse @@ -22,134 +27,127 @@ from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models +from .._serialization import Serializer from .._vendor import MixinABC, _convert_request, _format_url_section -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False + def build_get_request( resource_group_name: str, server_name: str, - security_alert_policy_name: Union[str, "_models.SecurityAlertPolicyName"], + security_alert_policy_name: Union[str, _models.SecurityAlertPolicyName], subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/securityAlertPolicies/{securityAlertPolicyName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/securityAlertPolicies/{securityAlertPolicyName}", + ) # pylint: disable=line-too-long path_format_arguments = { - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), - "securityAlertPolicyName": _SERIALIZER.url("security_alert_policy_name", security_alert_policy_name, 'str'), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), + "securityAlertPolicyName": _SERIALIZER.url("security_alert_policy_name", security_alert_policy_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_create_or_update_request_initial( +def build_create_or_update_request( resource_group_name: str, server_name: str, - security_alert_policy_name: Union[str, "_models.SecurityAlertPolicyName"], + security_alert_policy_name: Union[str, _models.SecurityAlertPolicyName], subscription_id: str, - *, - json: Optional[_models.ServerSecurityAlertPolicy] = None, - content: Any = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', None)) # type: Optional[str] - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/securityAlertPolicies/{securityAlertPolicyName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/securityAlertPolicies/{securityAlertPolicyName}", + ) # pylint: disable=line-too-long path_format_arguments = { - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), - "securityAlertPolicyName": _SERIALIZER.url("security_alert_policy_name", security_alert_policy_name, 'str'), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), + "securityAlertPolicyName": _SERIALIZER.url("security_alert_policy_name", security_alert_policy_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _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') + _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, - json=json, - content=content, - **kwargs - ) + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) def build_list_by_server_request( - resource_group_name: str, - server_name: str, - subscription_id: str, - **kwargs: Any + resource_group_name: str, server_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/securityAlertPolicies") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/securityAlertPolicies", + ) # pylint: disable=line-too-long path_format_arguments = { - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) class ServerSecurityAlertPoliciesOperations: """ @@ -170,50 +168,49 @@ def __init__(self, *args, **kwargs): self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace def get( self, resource_group_name: str, server_name: str, - security_alert_policy_name: Union[str, "_models.SecurityAlertPolicyName"], + security_alert_policy_name: Union[str, _models.SecurityAlertPolicyName], **kwargs: Any ) -> _models.ServerSecurityAlertPolicy: """Get a server's security alert policy. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param security_alert_policy_name: The name of the security alert policy. + :param security_alert_policy_name: The name of the security alert policy. "Default" Required. :type security_alert_policy_name: str or ~azure.mgmt.rdbms.mysql.models.SecurityAlertPolicyName - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: ServerSecurityAlertPolicy, or the result of cls(response) + :return: ServerSecurityAlertPolicy or the result of cls(response) :rtype: ~azure.mgmt.rdbms.mysql.models.ServerSecurityAlertPolicy - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.ServerSecurityAlertPolicy] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ServerSecurityAlertPolicy] - request = build_get_request( resource_group_name=resource_group_name, server_name=server_name, security_alert_policy_name=security_alert_policy_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], headers=_headers, params=_params, ) @@ -221,49 +218,56 @@ def get( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('ServerSecurityAlertPolicy', pipeline_response) + deserialized = self._deserialize("ServerSecurityAlertPolicy", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/securityAlertPolicies/{securityAlertPolicyName}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/securityAlertPolicies/{securityAlertPolicyName}"} # type: ignore def _create_or_update_initial( self, resource_group_name: str, server_name: str, - security_alert_policy_name: Union[str, "_models.SecurityAlertPolicyName"], - parameters: _models.ServerSecurityAlertPolicy, + security_alert_policy_name: Union[str, _models.SecurityAlertPolicyName], + parameters: Union[_models.ServerSecurityAlertPolicy, IO], **kwargs: Any ) -> Optional[_models.ServerSecurityAlertPolicy]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[Optional[_models.ServerSecurityAlertPolicy]] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.ServerSecurityAlertPolicy]] - _json = self._serialize.body(parameters, 'ServerSecurityAlertPolicy') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ServerSecurityAlertPolicy") - request = build_create_or_update_request_initial( + request = build_create_or_update_request( resource_group_name=resource_group_name, server_name=server_name, security_alert_policy_name=security_alert_policy_name, @@ -271,7 +275,8 @@ def _create_or_update_initial( api_version=api_version, content_type=content_type, json=_json, - template_url=self._create_or_update_initial.metadata['url'], + content=_content, + template_url=self._create_or_update_initial.metadata["url"], headers=_headers, params=_params, ) @@ -279,10 +284,9 @@ def _create_or_update_initial( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202]: @@ -291,38 +295,79 @@ def _create_or_update_initial( deserialized = None if response.status_code == 200: - deserialized = self._deserialize('ServerSecurityAlertPolicy', pipeline_response) + deserialized = self._deserialize("ServerSecurityAlertPolicy", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _create_or_update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/securityAlertPolicies/{securityAlertPolicyName}"} # type: ignore + _create_or_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/securityAlertPolicies/{securityAlertPolicyName}"} # type: ignore - - @distributed_trace + @overload def begin_create_or_update( self, resource_group_name: str, server_name: str, - security_alert_policy_name: Union[str, "_models.SecurityAlertPolicyName"], + security_alert_policy_name: Union[str, _models.SecurityAlertPolicyName], parameters: _models.ServerSecurityAlertPolicy, + *, + content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.ServerSecurityAlertPolicy]: """Creates or updates a threat detection policy. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param security_alert_policy_name: The name of the threat detection policy. + :param security_alert_policy_name: The name of the threat detection policy. "Default" Required. :type security_alert_policy_name: str or ~azure.mgmt.rdbms.mysql.models.SecurityAlertPolicyName - :param parameters: The server security alert policy. + :param parameters: The server security alert policy. Required. :type parameters: ~azure.mgmt.rdbms.mysql.models.ServerSecurityAlertPolicy - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :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 ServerSecurityAlertPolicy or the result + of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql.models.ServerSecurityAlertPolicy] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + security_alert_policy_name: Union[str, _models.SecurityAlertPolicyName], + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.ServerSecurityAlertPolicy]: + """Creates or updates a threat detection policy. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param security_alert_policy_name: The name of the threat detection policy. "Default" Required. + :type security_alert_policy_name: str or ~azure.mgmt.rdbms.mysql.models.SecurityAlertPolicyName + :param parameters: The server security alert policy. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :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 @@ -334,20 +379,55 @@ def begin_create_or_update( :return: An instance of LROPoller that returns either ServerSecurityAlertPolicy or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql.models.ServerSecurityAlertPolicy] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + security_alert_policy_name: Union[str, _models.SecurityAlertPolicyName], + parameters: Union[_models.ServerSecurityAlertPolicy, IO], + **kwargs: Any + ) -> LROPoller[_models.ServerSecurityAlertPolicy]: + """Creates or updates a threat detection policy. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param security_alert_policy_name: The name of the threat detection policy. "Default" Required. + :type security_alert_policy_name: str or ~azure.mgmt.rdbms.mysql.models.SecurityAlertPolicyName + :param parameters: The server security alert policy. Is either a model type or a IO type. + Required. + :type parameters: ~azure.mgmt.rdbms.mysql.models.ServerSecurityAlertPolicy or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either ServerSecurityAlertPolicy or the result + of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql.models.ServerSecurityAlertPolicy] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[_models.ServerSecurityAlertPolicy] - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ServerSecurityAlertPolicy] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = self._create_or_update_initial( # type: ignore resource_group_name=resource_group_name, @@ -356,82 +436,76 @@ def begin_create_or_update( parameters=parameters, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize('ServerSecurityAlertPolicy', pipeline_response) + deserialized = self._deserialize("ServerSecurityAlertPolicy", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - if polling is True: - polling_method = cast(PollingMethod, ARMPolling( - lro_delay, - - - **kwargs - )) # type: PollingMethod - elif polling is False: polling_method = cast(PollingMethod, NoPolling()) - else: polling_method = polling + polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_create_or_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/securityAlertPolicies/{securityAlertPolicyName}"} # type: ignore + begin_create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/securityAlertPolicies/{securityAlertPolicyName}"} # type: ignore @distributed_trace def list_by_server( - self, - resource_group_name: str, - server_name: str, - **kwargs: Any - ) -> Iterable[_models.ServerSecurityAlertPolicyListResult]: + self, resource_group_name: str, server_name: str, **kwargs: Any + ) -> Iterable["_models.ServerSecurityAlertPolicy"]: """Get the server's threat detection policies. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ServerSecurityAlertPolicyListResult or the result - of cls(response) - :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql.models.ServerSecurityAlertPolicyListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either ServerSecurityAlertPolicy or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql.models.ServerSecurityAlertPolicy] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.ServerSecurityAlertPolicyListResult] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ServerSecurityAlertPolicyListResult] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_server_request( resource_group_name=resource_group_name, server_name=server_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_server.metadata['url'], + template_url=self.list_by_server.metadata["url"], headers=_headers, params=_params, ) @@ -439,16 +513,7 @@ def prepare_request(next_link=None): request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_by_server_request( - resource_group_name=resource_group_name, - server_name=server_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - template_url=next_link, - headers=_headers, - params=_params, - ) + request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" @@ -464,10 +529,8 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -477,8 +540,6 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list_by_server.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/securityAlertPolicies"} # type: ignore + list_by_server.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/securityAlertPolicies"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_servers_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_servers_operations.py index 10c158fbc531..7a9914f0c788 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_servers_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_servers_operations.py @@ -6,11 +6,16 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Iterable, Optional, TypeVar, Union, cast - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse @@ -22,399 +27,336 @@ from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models +from .._serialization import Serializer from .._vendor import MixinABC, _convert_request, _format_url_section -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_create_request_initial( - subscription_id: str, - resource_group_name: str, - server_name: str, - *, - json: Optional[_models.ServerForCreate] = None, - content: Any = None, - **kwargs: Any + +def build_create_request( + resource_group_name: str, server_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', None)) # type: Optional[str] - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _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, - json=json, - content=content, - **kwargs - ) - - -def build_update_request_initial( - subscription_id: str, - resource_group_name: str, - server_name: str, - *, - json: Optional[_models.ServerUpdateParameters] = None, - content: Any = None, - **kwargs: Any + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_update_request( + resource_group_name: str, server_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', None)) # type: Optional[str] - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _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, - json=json, - content=content, - **kwargs - ) - - -def build_delete_request_initial( - subscription_id: str, - resource_group_name: str, - server_name: str, - **kwargs: Any + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_request( + resource_group_name: str, server_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="DELETE", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) - - -def build_get_request( - subscription_id: str, - resource_group_name: str, - server_name: str, - **kwargs: Any -) -> HttpRequest: + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_request(resource_group_name: str, server_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="GET", - 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( - subscription_id: str, - resource_group_name: str, - **kwargs: Any -) -> HttpRequest: +def build_list_by_resource_group_request(resource_group_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers", + ) # 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), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_list_request( - subscription_id: str, - **kwargs: Any -) -> HttpRequest: +def build_list_request(subscription_id: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/servers") path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) - - -def build_restart_request_initial( - subscription_id: str, - resource_group_name: str, - server_name: str, - **kwargs: Any + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_restart_request( + resource_group_name: str, server_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/restart") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/restart", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="POST", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) - - -def build_start_request_initial( - subscription_id: str, - resource_group_name: str, - server_name: str, - **kwargs: Any -) -> HttpRequest: + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_start_request(resource_group_name: str, server_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2020-01-01")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-01-01")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/start") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/start", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="POST", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) - - -def build_stop_request_initial( - subscription_id: str, - resource_group_name: str, - server_name: str, - **kwargs: Any -) -> HttpRequest: + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_stop_request(resource_group_name: str, server_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2020-01-01")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-01-01")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/stop") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/stop", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="POST", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) - - -def build_upgrade_request_initial( - subscription_id: str, - resource_group_name: str, - server_name: str, - *, - json: Optional[_models.ServerUpgradeParameters] = None, - content: Any = None, - **kwargs: Any + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_upgrade_request( + resource_group_name: str, server_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2020-01-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', None)) # type: Optional[str] - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-01-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/upgrade") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/upgrade", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if content_type is not None: - _headers['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="POST", - url=_url, - params=_params, - headers=_headers, - json=json, - content=content, - **kwargs - ) + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + class ServersOperations: """ @@ -435,36 +377,41 @@ def __init__(self, *args, **kwargs): 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") - def _create_initial( - self, - resource_group_name: str, - server_name: str, - parameters: _models.ServerForCreate, - **kwargs: Any + self, resource_group_name: str, server_name: str, parameters: Union[_models.ServerForCreate, IO], **kwargs: Any ) -> Optional[_models.Server]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[Optional[_models.Server]] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.Server]] - _json = self._serialize.body(parameters, 'ServerForCreate') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ServerForCreate") - request = build_create_request_initial( - subscription_id=self._config.subscription_id, + request = build_create_request( resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._create_initial.metadata['url'], + content=_content, + template_url=self._create_initial.metadata["url"], headers=_headers, params=_params, ) @@ -472,10 +419,9 @@ def _create_initial( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 201, 202]: @@ -484,39 +430,108 @@ def _create_initial( deserialized = None if response.status_code == 200: - deserialized = self._deserialize('Server', pipeline_response) + deserialized = self._deserialize("Server", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('Server', pipeline_response) + deserialized = self._deserialize("Server", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _create_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}"} # type: ignore - + _create_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}"} # type: ignore - @distributed_trace + @overload def begin_create( self, resource_group_name: str, server_name: str, parameters: _models.ServerForCreate, + *, + content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.Server]: """Creates a new server or updates an existing server. The update action will overwrite the existing server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param parameters: The required parameters for creating or updating a server. + :param parameters: The required parameters for creating or updating a server. Required. :type parameters: ~azure.mgmt.rdbms.mysql.models.ServerForCreate - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :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 Server or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql.models.Server] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create( + self, + resource_group_name: str, + server_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.Server]: + """Creates a new server or updates an existing server. The update action will overwrite the + existing server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param parameters: The required parameters for creating or updating a server. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :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 Server or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql.models.Server] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create( + self, resource_group_name: str, server_name: str, parameters: Union[_models.ServerForCreate, IO], **kwargs: Any + ) -> LROPoller[_models.Server]: + """Creates a new server or updates an existing server. The update action will overwrite the + existing server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param parameters: The required parameters for creating or updating a server. Is either a model + type or a IO type. Required. + :type parameters: ~azure.mgmt.rdbms.mysql.models.ServerForCreate or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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 @@ -527,20 +542,17 @@ def begin_create( Retry-After header is present. :return: An instance of LROPoller that returns either Server or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql.models.Server] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[_models.Server] - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Server] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = self._create_initial( # type: ignore resource_group_name=resource_group_name, @@ -548,69 +560,75 @@ def begin_create( parameters=parameters, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize('Server', pipeline_response) + deserialized = self._deserialize("Server", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - if polling is True: - polling_method = cast(PollingMethod, ARMPolling( - lro_delay, - - - **kwargs - )) # type: PollingMethod - elif polling is False: polling_method = cast(PollingMethod, NoPolling()) - else: polling_method = polling + polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_create.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}"} # type: ignore + begin_create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}"} # type: ignore def _update_initial( self, resource_group_name: str, server_name: str, - parameters: _models.ServerUpdateParameters, + parameters: Union[_models.ServerUpdateParameters, IO], **kwargs: Any ) -> Optional[_models.Server]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[Optional[_models.Server]] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.Server]] - _json = self._serialize.body(parameters, 'ServerUpdateParameters') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ServerUpdateParameters") - request = build_update_request_initial( - subscription_id=self._config.subscription_id, + request = build_update_request( resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._update_initial.metadata['url'], + content=_content, + template_url=self._update_initial.metadata["url"], headers=_headers, params=_params, ) @@ -618,10 +636,9 @@ def _update_initial( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202]: @@ -630,36 +647,74 @@ def _update_initial( deserialized = None if response.status_code == 200: - deserialized = self._deserialize('Server', pipeline_response) + deserialized = self._deserialize("Server", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}"} # type: ignore - + _update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}"} # type: ignore - @distributed_trace + @overload def begin_update( self, resource_group_name: str, server_name: str, parameters: _models.ServerUpdateParameters, + *, + content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.Server]: """Updates an existing server. The request body can contain one to many of the properties present in the normal server definition. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param parameters: The required parameters for updating a server. + :param parameters: The required parameters for updating a server. Required. :type parameters: ~azure.mgmt.rdbms.mysql.models.ServerUpdateParameters - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :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 Server or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql.models.Server] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_update( + self, + resource_group_name: str, + server_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.Server]: + """Updates an existing server. The request body can contain one to many of the properties present + in the normal server definition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param parameters: The required parameters for updating a server. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :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 @@ -670,20 +725,52 @@ def begin_update( Retry-After header is present. :return: An instance of LROPoller that returns either Server or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql.models.Server] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_update( + self, + resource_group_name: str, + server_name: str, + parameters: Union[_models.ServerUpdateParameters, IO], + **kwargs: Any + ) -> LROPoller[_models.Server]: + """Updates an existing server. The request body can contain one to many of the properties present + in the normal server definition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param parameters: The required parameters for updating a server. Is either a model type or a + IO type. Required. + :type parameters: ~azure.mgmt.rdbms.mysql.models.ServerUpdateParameters or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either Server or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql.models.Server] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[_models.Server] - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Server] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = self._update_initial( # type: ignore resource_group_name=resource_group_name, @@ -691,64 +778,59 @@ def begin_update( parameters=parameters, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize('Server', pipeline_response) + deserialized = self._deserialize("Server", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - if polling is True: - polling_method = cast(PollingMethod, ARMPolling( - lro_delay, - - - **kwargs - )) # type: PollingMethod - elif polling is False: polling_method = cast(PollingMethod, NoPolling()) - else: polling_method = polling + polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}"} # type: ignore + begin_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}"} # type: ignore def _delete_initial( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - server_name: str, - **kwargs: Any + self, resource_group_name: str, server_name: str, **kwargs: Any ) -> None: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] - - request = build_delete_request_initial( - subscription_id=self._config.subscription_id, + request = build_delete_request( resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._delete_initial.metadata['url'], + template_url=self._delete_initial.metadata["url"], headers=_headers, params=_params, ) @@ -756,10 +838,9 @@ def _delete_initial( # pylint: disable=inconsistent-return-statements request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: @@ -769,25 +850,17 @@ def _delete_initial( # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - _delete_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}"} # type: ignore - + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}"} # type: ignore @distributed_trace - def begin_delete( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - server_name: str, - **kwargs: Any - ) -> LROPoller[None]: + def begin_delete(self, resource_group_name: str, server_name: str, **kwargs: Any) -> LROPoller[None]: """Deletes a server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function 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 @@ -798,95 +871,83 @@ def begin_delete( # pylint: disable=inconsistent-return-statements Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = self._delete_initial( # type: ignore resource_group_name=resource_group_name, server_name=server_name, api_version=api_version, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - if polling is True: - polling_method = cast(PollingMethod, ARMPolling( - lro_delay, - - - **kwargs - )) # type: PollingMethod - elif polling is False: polling_method = cast(PollingMethod, NoPolling()) - else: polling_method = polling + polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_delete.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}"} # type: ignore + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}"} # type: ignore @distributed_trace - def get( - self, - resource_group_name: str, - server_name: str, - **kwargs: Any - ) -> _models.Server: + def get(self, resource_group_name: str, server_name: str, **kwargs: Any) -> _models.Server: """Gets information about a server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Server, or the result of cls(response) + :return: Server or the result of cls(response) :rtype: ~azure.mgmt.rdbms.mysql.models.Server - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.Server] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.Server] - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], headers=_headers, params=_params, ) @@ -894,62 +955,58 @@ def get( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('Server', pipeline_response) + deserialized = self._deserialize("Server", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}"} # type: ignore @distributed_trace - def list_by_resource_group( - self, - resource_group_name: str, - **kwargs: Any - ) -> Iterable[_models.ServerListResult]: + def list_by_resource_group(self, resource_group_name: str, **kwargs: Any) -> Iterable["_models.Server"]: """List all the servers in a given resource group. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ServerListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql.models.ServerListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Server or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql.models.Server] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.ServerListResult] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ServerListResult] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_resource_group_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata['url'], + template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) @@ -957,15 +1014,7 @@ def prepare_request(next_link=None): request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_by_resource_group_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - api_version=api_version, - template_url=next_link, - headers=_headers, - params=_params, - ) + request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" @@ -981,10 +1030,8 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -994,44 +1041,40 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list_by_resource_group.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers"} # type: ignore + list_by_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers"} # type: ignore @distributed_trace - def list( - self, - **kwargs: Any - ) -> Iterable[_models.ServerListResult]: + def list(self, **kwargs: Any) -> Iterable["_models.Server"]: """List all the servers in a given subscription. - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ServerListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql.models.ServerListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Server or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql.models.Server] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.ServerListResult] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ServerListResult] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list.metadata['url'], + template_url=self.list.metadata["url"], headers=_headers, params=_params, ) @@ -1039,14 +1082,7 @@ def prepare_request(next_link=None): request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_request( - subscription_id=self._config.subscription_id, - api_version=api_version, - template_url=next_link, - headers=_headers, - params=_params, - ) + request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" @@ -1062,10 +1098,8 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -1075,36 +1109,33 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/servers"} # type: ignore + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/servers"} # type: ignore def _restart_initial( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - server_name: str, - **kwargs: Any + self, resource_group_name: str, server_name: str, **kwargs: Any ) -> None: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] - - request = build_restart_request_initial( - subscription_id=self._config.subscription_id, + request = build_restart_request( resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._restart_initial.metadata['url'], + template_url=self._restart_initial.metadata["url"], headers=_headers, params=_params, ) @@ -1112,10 +1143,9 @@ def _restart_initial( # pylint: disable=inconsistent-return-statements request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202]: @@ -1125,25 +1155,17 @@ def _restart_initial( # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - _restart_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/restart"} # type: ignore - + _restart_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/restart"} # type: ignore @distributed_trace - def begin_restart( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - server_name: str, - **kwargs: Any - ) -> LROPoller[None]: + def begin_restart(self, resource_group_name: str, server_name: str, **kwargs: Any) -> LROPoller[None]: """Restarts a server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function 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 @@ -1154,80 +1176,72 @@ def begin_restart( # pylint: disable=inconsistent-return-statements Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = self._restart_initial( # type: ignore resource_group_name=resource_group_name, server_name=server_name, api_version=api_version, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - if polling is True: - polling_method = cast(PollingMethod, ARMPolling( - lro_delay, - - - **kwargs - )) # type: PollingMethod - elif polling is False: polling_method = cast(PollingMethod, NoPolling()) - else: polling_method = polling + polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_restart.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/restart"} # type: ignore + begin_restart.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/restart"} # type: ignore def _start_initial( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - server_name: str, - **kwargs: Any + self, resource_group_name: str, server_name: str, **kwargs: Any ) -> None: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2020-01-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-01-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] - - request = build_start_request_initial( - subscription_id=self._config.subscription_id, + request = build_start_request( resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._start_initial.metadata['url'], + template_url=self._start_initial.metadata["url"], headers=_headers, params=_params, ) @@ -1235,38 +1249,30 @@ def _start_initial( # pylint: disable=inconsistent-return-statements request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.CloudErrorAutoGenerated, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - _start_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/start"} # type: ignore - + _start_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/start"} # type: ignore @distributed_trace - def begin_start( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - server_name: str, - **kwargs: Any - ) -> LROPoller[None]: + def begin_start(self, resource_group_name: str, server_name: str, **kwargs: Any) -> LROPoller[None]: """Starts a stopped server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :keyword api_version: Api Version. Default value is "2020-01-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function 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 @@ -1277,80 +1283,72 @@ def begin_start( # pylint: disable=inconsistent-return-statements Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2020-01-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-01-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = self._start_initial( # type: ignore resource_group_name=resource_group_name, server_name=server_name, api_version=api_version, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - if polling is True: - polling_method = cast(PollingMethod, ARMPolling( - lro_delay, - - - **kwargs - )) # type: PollingMethod - elif polling is False: polling_method = cast(PollingMethod, NoPolling()) - else: polling_method = polling + polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_start.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/start"} # type: ignore + begin_start.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/start"} # type: ignore def _stop_initial( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - server_name: str, - **kwargs: Any + self, resource_group_name: str, server_name: str, **kwargs: Any ) -> None: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2020-01-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-01-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] - - request = build_stop_request_initial( - subscription_id=self._config.subscription_id, + request = build_stop_request( resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._stop_initial.metadata['url'], + template_url=self._stop_initial.metadata["url"], headers=_headers, params=_params, ) @@ -1358,38 +1356,30 @@ def _stop_initial( # pylint: disable=inconsistent-return-statements request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.CloudErrorAutoGenerated, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - _stop_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/stop"} # type: ignore - + _stop_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/stop"} # type: ignore @distributed_trace - def begin_stop( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - server_name: str, - **kwargs: Any - ) -> LROPoller[None]: + def begin_stop(self, resource_group_name: str, server_name: str, **kwargs: Any) -> LROPoller[None]: """Stops a running server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :keyword api_version: Api Version. Default value is "2020-01-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function 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 @@ -1400,85 +1390,88 @@ def begin_stop( # pylint: disable=inconsistent-return-statements Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2020-01-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-01-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = self._stop_initial( # type: ignore resource_group_name=resource_group_name, server_name=server_name, api_version=api_version, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - if polling is True: - polling_method = cast(PollingMethod, ARMPolling( - lro_delay, - - - **kwargs - )) # type: PollingMethod - elif polling is False: polling_method = cast(PollingMethod, NoPolling()) - else: polling_method = polling + polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_stop.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/stop"} # type: ignore + begin_stop.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/stop"} # type: ignore def _upgrade_initial( # pylint: disable=inconsistent-return-statements self, resource_group_name: str, server_name: str, - parameters: _models.ServerUpgradeParameters, + parameters: Union[_models.ServerUpgradeParameters, IO], **kwargs: Any ) -> None: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2020-01-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[None] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-01-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[None] - _json = self._serialize.body(parameters, 'ServerUpgradeParameters') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ServerUpgradeParameters") - request = build_upgrade_request_initial( - subscription_id=self._config.subscription_id, + request = build_upgrade_request( resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._upgrade_initial.metadata['url'], + content=_content, + template_url=self._upgrade_initial.metadata["url"], headers=_headers, params=_params, ) @@ -1486,41 +1479,43 @@ def _upgrade_initial( # pylint: disable=inconsistent-return-statements request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, error_format=ARMErrorFormat) + error = self._deserialize.failsafe_deserialize(_models.CloudErrorAutoGenerated, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - _upgrade_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/upgrade"} # type: ignore - + _upgrade_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/upgrade"} # type: ignore - @distributed_trace - def begin_upgrade( # pylint: disable=inconsistent-return-statements + @overload + def begin_upgrade( self, resource_group_name: str, server_name: str, parameters: _models.ServerUpgradeParameters, + *, + content_type: str = "application/json", **kwargs: Any ) -> LROPoller[None]: """Upgrade server version. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param parameters: The required parameters for updating a server. + :param parameters: The required parameters for updating a server. Required. :type parameters: ~azure.mgmt.rdbms.mysql.models.ServerUpgradeParameters - :keyword api_version: Api Version. Default value is "2020-01-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :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 @@ -1531,20 +1526,86 @@ def begin_upgrade( # pylint: disable=inconsistent-return-statements Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_upgrade( + self, + resource_group_name: str, + server_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[None]: + """Upgrade server version. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param parameters: The required parameters for updating a server. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :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: + """ + + @distributed_trace + def begin_upgrade( + self, + resource_group_name: str, + server_name: str, + parameters: Union[_models.ServerUpgradeParameters, IO], + **kwargs: Any + ) -> LROPoller[None]: + """Upgrade server version. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param parameters: The required parameters for updating a server. Is either a model type or a + IO type. Required. + :type parameters: ~azure.mgmt.rdbms.mysql.models.ServerUpgradeParameters or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2020-01-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[None] - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-01-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = self._upgrade_initial( # type: ignore resource_group_name=resource_group_name, @@ -1552,34 +1613,30 @@ def begin_upgrade( # pylint: disable=inconsistent-return-statements parameters=parameters, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - if polling is True: - polling_method = cast(PollingMethod, ARMPolling( - lro_delay, - - - **kwargs - )) # type: PollingMethod - elif polling is False: polling_method = cast(PollingMethod, NoPolling()) - else: polling_method = polling + polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_upgrade.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/upgrade"} # type: ignore + begin_upgrade.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/upgrade"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_top_query_statistics_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_top_query_statistics_operations.py index 158b13cd751b..ad1718a83f41 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_top_query_statistics_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_top_query_statistics_operations.py @@ -6,11 +6,16 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Iterable, Optional, TypeVar - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse @@ -20,95 +25,85 @@ from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer from .._vendor import MixinABC, _convert_request, _format_url_section -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False + def build_get_request( - subscription_id: str, - resource_group_name: str, - server_name: str, - query_statistic_id: str, - **kwargs: Any + resource_group_name: str, server_name: str, query_statistic_id: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/topQueryStatistics/{queryStatisticId}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/topQueryStatistics/{queryStatisticId}", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), - "queryStatisticId": _SERIALIZER.url("query_statistic_id", query_statistic_id, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), + "queryStatisticId": _SERIALIZER.url("query_statistic_id", query_statistic_id, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_list_by_server_request( - subscription_id: str, - resource_group_name: str, - server_name: str, - *, - json: Optional[_models.TopQueryStatisticsInput] = None, - content: Any = None, - **kwargs: Any + resource_group_name: str, server_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', None)) # type: Optional[str] - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/topQueryStatistics") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/topQueryStatistics", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _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, - json=json, - content=content, - **kwargs - ) + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + class TopQueryStatisticsOperations: """ @@ -129,50 +124,45 @@ def __init__(self, *args, **kwargs): self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace def get( - self, - resource_group_name: str, - server_name: str, - query_statistic_id: str, - **kwargs: Any + self, resource_group_name: str, server_name: str, query_statistic_id: str, **kwargs: Any ) -> _models.QueryStatistic: """Retrieve the query statistic for specified identifier. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param query_statistic_id: The Query Statistic identifier. + :param query_statistic_id: The Query Statistic identifier. Required. :type query_statistic_id: str - :keyword api_version: Api Version. Default value is "2018-06-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: QueryStatistic, or the result of cls(response) + :return: QueryStatistic or the result of cls(response) :rtype: ~azure.mgmt.rdbms.mysql.models.QueryStatistic - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.QueryStatistic] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.QueryStatistic] - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, query_statistic_id=query_statistic_id, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], headers=_headers, params=_params, ) @@ -180,75 +170,140 @@ def get( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('QueryStatistic', pipeline_response) + deserialized = self._deserialize("QueryStatistic", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/topQueryStatistics/{queryStatisticId}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/topQueryStatistics/{queryStatisticId}"} # type: ignore - @distributed_trace + @overload def list_by_server( self, resource_group_name: str, server_name: str, parameters: _models.TopQueryStatisticsInput, + *, + content_type: str = "application/json", **kwargs: Any - ) -> Iterable[_models.TopQueryStatisticsResultList]: + ) -> Iterable["_models.QueryStatistic"]: """Retrieve the Query-Store top queries for specified metric and aggregation. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param parameters: The required parameters for retrieving top query statistics. + :param parameters: The required parameters for retrieving top query statistics. Required. :type parameters: ~azure.mgmt.rdbms.mysql.models.TopQueryStatisticsInput - :keyword api_version: Api Version. Default value is "2018-06-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either QueryStatistic or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql.models.QueryStatistic] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def list_by_server( + self, + resource_group_name: str, + server_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> Iterable["_models.QueryStatistic"]: + """Retrieve the Query-Store top queries for specified metric and aggregation. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param parameters: The required parameters for retrieving top query statistics. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either TopQueryStatisticsResultList or the result of - cls(response) - :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql.models.TopQueryStatisticsResultList] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either QueryStatistic or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql.models.QueryStatistic] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def list_by_server( + self, + resource_group_name: str, + server_name: str, + parameters: Union[_models.TopQueryStatisticsInput, IO], + **kwargs: Any + ) -> Iterable["_models.QueryStatistic"]: + """Retrieve the Query-Store top queries for specified metric and aggregation. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param parameters: The required parameters for retrieving top query statistics. Is either a + model type or a IO type. Required. + :type parameters: ~azure.mgmt.rdbms.mysql.models.TopQueryStatisticsInput or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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: An iterator like instance of either QueryStatistic or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql.models.QueryStatistic] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[_models.TopQueryStatisticsResultList] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.TopQueryStatisticsResultList] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "TopQueryStatisticsInput") + def prepare_request(next_link=None): if not next_link: - _json = self._serialize.body(parameters, 'TopQueryStatisticsInput') - + request = build_list_by_server_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self.list_by_server.metadata['url'], + content=_content, + template_url=self.list_by_server.metadata["url"], headers=_headers, params=_params, ) @@ -256,19 +311,7 @@ def prepare_request(next_link=None): request.url = self._client.format_url(request.url) # type: ignore else: - _json = self._serialize.body(parameters, 'TopQueryStatisticsInput') - - request = build_list_by_server_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - server_name=server_name, - api_version=api_version, - content_type=content_type, - json=_json, - template_url=next_link, - headers=_headers, - params=_params, - ) + request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" @@ -284,10 +327,8 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -297,8 +338,6 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list_by_server.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/topQueryStatistics"} # type: ignore + list_by_server.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/topQueryStatistics"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_virtual_network_rules_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_virtual_network_rules_operations.py index a930d3336a17..79053c218740 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_virtual_network_rules_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_virtual_network_rules_operations.py @@ -6,11 +6,16 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Iterable, Optional, TypeVar, Union, cast - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse @@ -22,166 +27,147 @@ from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models +from .._serialization import Serializer from .._vendor import MixinABC, _convert_request, _format_url_section -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False + def build_get_request( - resource_group_name: str, - server_name: str, - subscription_id: str, - virtual_network_rule_name: str, - **kwargs: Any + resource_group_name: str, server_name: str, virtual_network_rule_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}", + ) # pylint: disable=line-too-long path_format_arguments = { - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), - "virtualNetworkRuleName": _SERIALIZER.url("virtual_network_rule_name", virtual_network_rule_name, 'str'), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "virtualNetworkRuleName": _SERIALIZER.url("virtual_network_rule_name", virtual_network_rule_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) - - -def build_create_or_update_request_initial( - resource_group_name: str, - server_name: str, - subscription_id: str, - virtual_network_rule_name: str, - *, - json: Optional[_models.VirtualNetworkRule] = None, - content: Any = None, - **kwargs: Any + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_or_update_request( + resource_group_name: str, server_name: str, virtual_network_rule_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', None)) # type: Optional[str] - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}", + ) # pylint: disable=line-too-long path_format_arguments = { - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), - "virtualNetworkRuleName": _SERIALIZER.url("virtual_network_rule_name", virtual_network_rule_name, 'str'), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "virtualNetworkRuleName": _SERIALIZER.url("virtual_network_rule_name", virtual_network_rule_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _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, - json=json, - content=content, - **kwargs - ) - - -def build_delete_request_initial( - resource_group_name: str, - server_name: str, - virtual_network_rule_name: str, - subscription_id: str, - **kwargs: Any + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_request( + resource_group_name: str, server_name: str, virtual_network_rule_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}", + ) # pylint: disable=line-too-long path_format_arguments = { - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), - "virtualNetworkRuleName": _SERIALIZER.url("virtual_network_rule_name", virtual_network_rule_name, 'str'), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), + "virtualNetworkRuleName": _SERIALIZER.url("virtual_network_rule_name", virtual_network_rule_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - return HttpRequest( - method="DELETE", - url=_url, - params=_params, - **kwargs - ) + return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) def build_list_by_server_request( - resource_group_name: str, - server_name: str, - subscription_id: str, - **kwargs: Any + resource_group_name: str, server_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/virtualNetworkRules") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/virtualNetworkRules", + ) # pylint: disable=line-too-long path_format_arguments = { - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) class VirtualNetworkRulesOperations: """ @@ -202,50 +188,45 @@ def __init__(self, *args, **kwargs): self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace def get( - self, - resource_group_name: str, - server_name: str, - virtual_network_rule_name: str, - **kwargs: Any + self, resource_group_name: str, server_name: str, virtual_network_rule_name: str, **kwargs: Any ) -> _models.VirtualNetworkRule: """Gets a virtual network rule. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param virtual_network_rule_name: The name of the virtual network rule. + :param virtual_network_rule_name: The name of the virtual network rule. Required. :type virtual_network_rule_name: str - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: VirtualNetworkRule, or the result of cls(response) + :return: VirtualNetworkRule or the result of cls(response) :rtype: ~azure.mgmt.rdbms.mysql.models.VirtualNetworkRule - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.VirtualNetworkRule] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.VirtualNetworkRule] - request = build_get_request( resource_group_name=resource_group_name, server_name=server_name, - subscription_id=self._config.subscription_id, virtual_network_rule_name=virtual_network_rule_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], headers=_headers, params=_params, ) @@ -253,57 +234,65 @@ def get( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('VirtualNetworkRule', pipeline_response) + deserialized = self._deserialize("VirtualNetworkRule", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}"} # type: ignore def _create_or_update_initial( self, resource_group_name: str, server_name: str, virtual_network_rule_name: str, - parameters: _models.VirtualNetworkRule, + parameters: Union[_models.VirtualNetworkRule, IO], **kwargs: Any ) -> Optional[_models.VirtualNetworkRule]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[Optional[_models.VirtualNetworkRule]] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.VirtualNetworkRule]] - _json = self._serialize.body(parameters, 'VirtualNetworkRule') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "VirtualNetworkRule") - request = build_create_or_update_request_initial( + request = build_create_or_update_request( resource_group_name=resource_group_name, server_name=server_name, - subscription_id=self._config.subscription_id, virtual_network_rule_name=virtual_network_rule_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._create_or_update_initial.metadata['url'], + content=_content, + template_url=self._create_or_update_initial.metadata["url"], headers=_headers, params=_params, ) @@ -311,10 +300,9 @@ def _create_or_update_initial( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 201, 202]: @@ -323,41 +311,120 @@ def _create_or_update_initial( deserialized = None if response.status_code == 200: - deserialized = self._deserialize('VirtualNetworkRule', pipeline_response) + deserialized = self._deserialize("VirtualNetworkRule", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('VirtualNetworkRule', pipeline_response) + deserialized = self._deserialize("VirtualNetworkRule", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _create_or_update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}"} # type: ignore - + _create_or_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}"} # type: ignore - @distributed_trace + @overload def begin_create_or_update( self, resource_group_name: str, server_name: str, virtual_network_rule_name: str, parameters: _models.VirtualNetworkRule, + *, + content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.VirtualNetworkRule]: """Creates or updates an existing virtual network rule. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param virtual_network_rule_name: The name of the virtual network rule. + :param virtual_network_rule_name: The name of the virtual network rule. Required. :type virtual_network_rule_name: str - :param parameters: The requested virtual Network Rule Resource state. + :param parameters: The requested virtual Network Rule Resource state. Required. :type parameters: ~azure.mgmt.rdbms.mysql.models.VirtualNetworkRule - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :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 VirtualNetworkRule or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql.models.VirtualNetworkRule] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + virtual_network_rule_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.VirtualNetworkRule]: + """Creates or updates an existing virtual network rule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param virtual_network_rule_name: The name of the virtual network rule. Required. + :type virtual_network_rule_name: str + :param parameters: The requested virtual Network Rule Resource state. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :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 VirtualNetworkRule or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql.models.VirtualNetworkRule] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + virtual_network_rule_name: str, + parameters: Union[_models.VirtualNetworkRule, IO], + **kwargs: Any + ) -> LROPoller[_models.VirtualNetworkRule]: + """Creates or updates an existing virtual network rule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param virtual_network_rule_name: The name of the virtual network rule. Required. + :type virtual_network_rule_name: str + :param parameters: The requested virtual Network Rule Resource state. Is either a model type or + a IO type. Required. + :type parameters: ~azure.mgmt.rdbms.mysql.models.VirtualNetworkRule or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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 @@ -369,20 +436,17 @@ def begin_create_or_update( :return: An instance of LROPoller that returns either VirtualNetworkRule or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql.models.VirtualNetworkRule] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[_models.VirtualNetworkRule] - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.VirtualNetworkRule] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = self._create_or_update_initial( # type: ignore resource_group_name=resource_group_name, @@ -391,66 +455,60 @@ def begin_create_or_update( parameters=parameters, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize('VirtualNetworkRule', pipeline_response) + deserialized = self._deserialize("VirtualNetworkRule", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - if polling is True: - polling_method = cast(PollingMethod, ARMPolling( - lro_delay, - - - **kwargs - )) # type: PollingMethod - elif polling is False: polling_method = cast(PollingMethod, NoPolling()) - else: polling_method = polling + polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_create_or_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}"} # type: ignore + begin_create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}"} # type: ignore def _delete_initial( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - server_name: str, - virtual_network_rule_name: str, - **kwargs: Any + self, resource_group_name: str, server_name: str, virtual_network_rule_name: str, **kwargs: Any ) -> None: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] - - request = build_delete_request_initial( + request = build_delete_request( resource_group_name=resource_group_name, server_name=server_name, virtual_network_rule_name=virtual_network_rule_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._delete_initial.metadata['url'], + template_url=self._delete_initial.metadata["url"], headers=_headers, params=_params, ) @@ -458,10 +516,9 @@ def _delete_initial( # pylint: disable=inconsistent-return-statements request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: @@ -471,28 +528,21 @@ def _delete_initial( # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - _delete_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}"} # type: ignore - + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}"} # type: ignore @distributed_trace - def begin_delete( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - server_name: str, - virtual_network_rule_name: str, - **kwargs: Any + def begin_delete( + self, resource_group_name: str, server_name: str, virtual_network_rule_name: str, **kwargs: Any ) -> LROPoller[None]: """Deletes the virtual network rule with the given name. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param virtual_network_rule_name: The name of the virtual network rule. + :param virtual_network_rule_name: The name of the virtual network rule. Required. :type virtual_network_rule_name: str - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function 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 @@ -503,99 +553,89 @@ def begin_delete( # pylint: disable=inconsistent-return-statements Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = self._delete_initial( # type: ignore resource_group_name=resource_group_name, server_name=server_name, virtual_network_rule_name=virtual_network_rule_name, api_version=api_version, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - if polling is True: - polling_method = cast(PollingMethod, ARMPolling( - lro_delay, - - - **kwargs - )) # type: PollingMethod - elif polling is False: polling_method = cast(PollingMethod, NoPolling()) - else: polling_method = polling + polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_delete.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}"} # type: ignore + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/virtualNetworkRules/{virtualNetworkRuleName}"} # type: ignore @distributed_trace def list_by_server( - self, - resource_group_name: str, - server_name: str, - **kwargs: Any - ) -> Iterable[_models.VirtualNetworkRuleListResult]: + self, resource_group_name: str, server_name: str, **kwargs: Any + ) -> Iterable["_models.VirtualNetworkRule"]: """Gets a list of virtual network rules in a server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :keyword api_version: Api Version. Default value is "2017-12-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either VirtualNetworkRuleListResult or the result of - cls(response) - :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql.models.VirtualNetworkRuleListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either VirtualNetworkRule or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql.models.VirtualNetworkRule] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2017-12-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.VirtualNetworkRuleListResult] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2017-12-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.VirtualNetworkRuleListResult] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_server_request( resource_group_name=resource_group_name, server_name=server_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_server.metadata['url'], + template_url=self.list_by_server.metadata["url"], headers=_headers, params=_params, ) @@ -603,16 +643,7 @@ def prepare_request(next_link=None): request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_by_server_request( - resource_group_name=resource_group_name, - server_name=server_name, - subscription_id=self._config.subscription_id, - api_version=api_version, - template_url=next_link, - headers=_headers, - params=_params, - ) + request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" @@ -628,10 +659,8 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -641,8 +670,6 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list_by_server.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/virtualNetworkRules"} # type: ignore + list_by_server.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/virtualNetworkRules"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_wait_statistics_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_wait_statistics_operations.py index d59b26676b9b..9ab06a1a9275 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_wait_statistics_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/_wait_statistics_operations.py @@ -6,11 +6,16 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Iterable, Optional, TypeVar - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse @@ -20,95 +25,85 @@ from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer from .._vendor import MixinABC, _convert_request, _format_url_section -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False + def build_get_request( - subscription_id: str, - resource_group_name: str, - server_name: str, - wait_statistics_id: str, - **kwargs: Any + resource_group_name: str, server_name: str, wait_statistics_id: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/waitStatistics/{waitStatisticsId}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/waitStatistics/{waitStatisticsId}", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), - "waitStatisticsId": _SERIALIZER.url("wait_statistics_id", wait_statistics_id, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), + "waitStatisticsId": _SERIALIZER.url("wait_statistics_id", wait_statistics_id, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_list_by_server_request( - subscription_id: str, - resource_group_name: str, - server_name: str, - *, - json: Optional[_models.WaitStatisticsInput] = None, - content: Any = None, - **kwargs: Any + resource_group_name: str, server_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', None)) # type: Optional[str] - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/waitStatistics") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/waitStatistics", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _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, - json=json, - content=content, - **kwargs - ) + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + class WaitStatisticsOperations: """ @@ -129,50 +124,45 @@ def __init__(self, *args, **kwargs): self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace def get( - self, - resource_group_name: str, - server_name: str, - wait_statistics_id: str, - **kwargs: Any + self, resource_group_name: str, server_name: str, wait_statistics_id: str, **kwargs: Any ) -> _models.WaitStatistic: """Retrieve wait statistics for specified identifier. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param wait_statistics_id: The Wait Statistic identifier. + :param wait_statistics_id: The Wait Statistic identifier. Required. :type wait_statistics_id: str - :keyword api_version: Api Version. Default value is "2018-06-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: WaitStatistic, or the result of cls(response) + :return: WaitStatistic or the result of cls(response) :rtype: ~azure.mgmt.rdbms.mysql.models.WaitStatistic - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.WaitStatistic] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.WaitStatistic] - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, wait_statistics_id=wait_statistics_id, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], headers=_headers, params=_params, ) @@ -180,74 +170,140 @@ def get( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('WaitStatistic', pipeline_response) + deserialized = self._deserialize("WaitStatistic", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/waitStatistics/{waitStatisticsId}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/waitStatistics/{waitStatisticsId}"} # type: ignore - @distributed_trace + @overload def list_by_server( self, resource_group_name: str, server_name: str, parameters: _models.WaitStatisticsInput, + *, + content_type: str = "application/json", **kwargs: Any - ) -> Iterable[_models.WaitStatisticsResultList]: + ) -> Iterable["_models.WaitStatistic"]: """Retrieve wait statistics for specified aggregation window. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param parameters: The required parameters for retrieving wait statistics. + :param parameters: The required parameters for retrieving wait statistics. Required. :type parameters: ~azure.mgmt.rdbms.mysql.models.WaitStatisticsInput - :keyword api_version: Api Version. Default value is "2018-06-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either WaitStatistic or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql.models.WaitStatistic] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def list_by_server( + self, + resource_group_name: str, + server_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> Iterable["_models.WaitStatistic"]: + """Retrieve wait statistics for specified aggregation window. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param parameters: The required parameters for retrieving wait statistics. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either WaitStatisticsResultList or the result of - cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql.models.WaitStatisticsResultList] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either WaitStatistic or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql.models.WaitStatistic] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def list_by_server( + self, + resource_group_name: str, + server_name: str, + parameters: Union[_models.WaitStatisticsInput, IO], + **kwargs: Any + ) -> Iterable["_models.WaitStatistic"]: + """Retrieve wait statistics for specified aggregation window. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param parameters: The required parameters for retrieving wait statistics. Is either a model + type or a IO type. Required. + :type parameters: ~azure.mgmt.rdbms.mysql.models.WaitStatisticsInput or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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: An iterator like instance of either WaitStatistic or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql.models.WaitStatistic] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2018-06-01")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[_models.WaitStatisticsResultList] + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-06-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.WaitStatisticsResultList] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "WaitStatisticsInput") + def prepare_request(next_link=None): if not next_link: - _json = self._serialize.body(parameters, 'WaitStatisticsInput') - + request = build_list_by_server_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self.list_by_server.metadata['url'], + content=_content, + template_url=self.list_by_server.metadata["url"], headers=_headers, params=_params, ) @@ -255,19 +311,7 @@ def prepare_request(next_link=None): request.url = self._client.format_url(request.url) # type: ignore else: - _json = self._serialize.body(parameters, 'WaitStatisticsInput') - - request = build_list_by_server_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - server_name=server_name, - api_version=api_version, - content_type=content_type, - json=_json, - template_url=next_link, - headers=_headers, - params=_params, - ) + request = HttpRequest("GET", next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore request.method = "GET" @@ -283,10 +327,8 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -296,8 +338,6 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list_by_server.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/waitStatistics"} # type: ignore + list_by_server.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/waitStatistics"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/__init__.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/__init__.py index 3ca776ae04a9..3ba002b536c9 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/__init__.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/__init__.py @@ -17,7 +17,8 @@ except ImportError: _patch_all = [] from ._patch import patch_sdk as _patch_sdk -__all__ = ['MySQLManagementClient'] + +__all__ = ["MySQLManagementClient"] __all__.extend([p for p in _patch_all if p not in __all__]) _patch_sdk() diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/_configuration.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/_configuration.py index 6e7ab734383a..6f90763ad072 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/_configuration.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/_configuration.py @@ -25,23 +25,18 @@ class MySQLManagementClientConfiguration(Configuration): # pylint: disable=too- Note that all parameters used to create this instance are saved as instance attributes. - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: The ID of the target subscription. + :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str :keyword api_version: Api Version. Default value is "2021-12-01-preview". Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str """ - def __init__( - self, - credential: "TokenCredential", - subscription_id: str, - **kwargs: Any - ) -> None: + def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: super(MySQLManagementClientConfiguration, self).__init__(**kwargs) - api_version = kwargs.pop('api_version', "2021-12-01-preview") # type: str + api_version = kwargs.pop("api_version", "2021-12-01-preview") # type: str if credential is None: raise ValueError("Parameter 'credential' must not be None.") @@ -51,23 +46,24 @@ def __init__( self.credential = credential self.subscription_id = subscription_id self.api_version = api_version - self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'mgmt-rdbms/{}'.format(VERSION)) + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-rdbms/{}".format(VERSION)) self._configure(**kwargs) def _configure( - self, - **kwargs # type: Any + self, **kwargs # type: Any ): # type: (...) -> None - self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get('retry_policy') or policies.RetryPolicy(**kwargs) - self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get('redirect_policy') or policies.RedirectPolicy(**kwargs) - self.authentication_policy = kwargs.get('authentication_policy') + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: - self.authentication_policy = ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs) + self.authentication_policy = ARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/_my_sql_management_client.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/_my_sql_management_client.py index 7c0dcc425705..7bb1f4c48afd 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/_my_sql_management_client.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/_my_sql_management_client.py @@ -9,20 +9,35 @@ from copy import deepcopy from typing import Any, TYPE_CHECKING -from msrest import Deserializer, Serializer - from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient from . import models from ._configuration import MySQLManagementClientConfiguration -from .operations import AzureADAdministratorsOperations, BackupsOperations, CheckNameAvailabilityOperations, CheckNameAvailabilityWithoutLocationOperations, CheckVirtualNetworkSubnetUsageOperations, ConfigurationsOperations, DatabasesOperations, FirewallRulesOperations, GetPrivateDnsZoneSuffixOperations, LocationBasedCapabilitiesOperations, LogFilesOperations, Operations, ReplicasOperations, ServersOperations +from ._serialization import Deserializer, Serializer +from .operations import ( + AzureADAdministratorsOperations, + BackupsOperations, + CheckNameAvailabilityOperations, + CheckNameAvailabilityWithoutLocationOperations, + CheckVirtualNetworkSubnetUsageOperations, + ConfigurationsOperations, + DatabasesOperations, + FirewallRulesOperations, + GetPrivateDnsZoneSuffixOperations, + LocationBasedCapabilitiesOperations, + LogFilesOperations, + Operations, + ReplicasOperations, + ServersOperations, +) if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class MySQLManagementClient: # pylint: disable=too-many-instance-attributes + +class MySQLManagementClient: # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes """The Microsoft Azure management API provides create, read, update, and delete functionality for Azure MySQL resources including servers, databases, firewall rules, VNET rules, log files and configurations with new business model. @@ -64,9 +79,9 @@ class MySQLManagementClient: # pylint: disable=too-many-instance-attributes :ivar azure_ad_administrators: AzureADAdministratorsOperations operations :vartype azure_ad_administrators: azure.mgmt.rdbms.mysql_flexibleservers.operations.AzureADAdministratorsOperations - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: The ID of the target subscription. + :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str :param base_url: Service URL. Default value is "https://management.azure.com". :type base_url: str @@ -84,34 +99,22 @@ def __init__( base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: - self._config = MySQLManagementClientConfiguration(credential=credential, subscription_id=subscription_id, **kwargs) + self._config = MySQLManagementClientConfiguration( + credential=credential, subscription_id=subscription_id, **kwargs + ) self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) self._deserialize = Deserializer(client_models) self._serialize.client_side_validation = False - self.backups = BackupsOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.configurations = ConfigurationsOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.databases = DatabasesOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.firewall_rules = FirewallRulesOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.servers = ServersOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.replicas = ReplicasOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.log_files = LogFilesOperations( - self._client, self._config, self._serialize, self._deserialize - ) + self.backups = BackupsOperations(self._client, self._config, self._serialize, self._deserialize) + self.configurations = ConfigurationsOperations(self._client, self._config, self._serialize, self._deserialize) + self.databases = DatabasesOperations(self._client, self._config, self._serialize, self._deserialize) + self.firewall_rules = FirewallRulesOperations(self._client, self._config, self._serialize, self._deserialize) + self.servers = ServersOperations(self._client, self._config, self._serialize, self._deserialize) + self.replicas = ReplicasOperations(self._client, self._config, self._serialize, self._deserialize) + self.log_files = LogFilesOperations(self._client, self._config, self._serialize, self._deserialize) self.location_based_capabilities = LocationBasedCapabilitiesOperations( self._client, self._config, self._serialize, self._deserialize ) @@ -127,19 +130,12 @@ def __init__( self.get_private_dns_zone_suffix = GetPrivateDnsZoneSuffixOperations( 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) self.azure_ad_administrators = AzureADAdministratorsOperations( self._client, self._config, self._serialize, self._deserialize ) - - def _send_request( - self, - request: HttpRequest, - **kwargs: Any - ) -> HttpResponse: + def _send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: """Runs the network request through the client's chained policies. >>> from azure.core.rest import HttpRequest @@ -148,7 +144,7 @@ def _send_request( >>> response = client._send_request(request) - For more information on this code flow, see https://aka.ms/azsdk/python/protocol/quickstart + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request :param request: The network request you want to make. Required. :type request: ~azure.core.rest.HttpRequest diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/_patch.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/_patch.py index 74e48ecd07cf..f99e77fef986 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/_patch.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/_patch.py @@ -28,4 +28,4 @@ # This file is used for handwritten extensions to the generated code. Example: # https://github.com/Azure/azure-sdk-for-python/blob/main/doc/dev/customize_code/how-to-patch-sdk-code.md def patch_sdk(): - pass \ No newline at end of file + pass diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/_serialization.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/_serialization.py new file mode 100644 index 000000000000..7c1dedb5133d --- /dev/null +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/_serialization.py @@ -0,0 +1,1970 @@ +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- + +# pylint: skip-file + +from base64 import b64decode, b64encode +import calendar +import datetime +import decimal +import email +from enum import Enum +import json +import logging +import re +import sys +import codecs + +try: + from urllib import quote # type: ignore +except ImportError: + from urllib.parse import quote # type: ignore +import xml.etree.ElementTree as ET + +import isodate + +from typing import Dict, Any, cast, TYPE_CHECKING + +from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback + +_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") + +if TYPE_CHECKING: + from typing import Optional, Union, AnyStr, IO, Mapping + + +class RawDeserializer: + + # Accept "text" because we're open minded people... + JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") + + # Name used in context + CONTEXT_NAME = "deserialized_data" + + @classmethod + def deserialize_from_text(cls, data, content_type=None): + # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any + """Decode data according to content-type. + + Accept a stream of data as well, but will be load at once in memory for now. + + If no content-type, will return the string version (not bytes, not stream) + + :param data: Input, could be bytes or stream (will be decoded with UTF8) or text + :type data: str or bytes or IO + :param str content_type: The content type. + """ + if hasattr(data, "read"): + # Assume a stream + data = cast(IO, data).read() + + if isinstance(data, bytes): + data_as_str = data.decode(encoding="utf-8-sig") + else: + # Explain to mypy the correct type. + data_as_str = cast(str, data) + + # Remove Byte Order Mark if present in string + data_as_str = data_as_str.lstrip(_BOM) + + if content_type is None: + return data + + if cls.JSON_REGEXP.match(content_type): + try: + return json.loads(data_as_str) + except ValueError as err: + raise DeserializationError("JSON is invalid: {}".format(err), err) + elif "xml" in (content_type or []): + try: + + try: + if isinstance(data, unicode): # type: ignore + # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string + data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore + except NameError: + pass + + return ET.fromstring(data_as_str) # nosec + except ET.ParseError: + # It might be because the server has an issue, and returned JSON with + # content-type XML.... + # So let's try a JSON load, and if it's still broken + # let's flow the initial exception + def _json_attemp(data): + try: + return True, json.loads(data) + except ValueError: + return False, None # Don't care about this one + + success, json_result = _json_attemp(data) + if success: + return json_result + # If i'm here, it's not JSON, it's not XML, let's scream + # and raise the last context in this block (the XML exception) + # The function hack is because Py2.7 messes up with exception + # context otherwise. + _LOGGER.critical("Wasn't XML not JSON, failing") + raise_with_traceback(DeserializationError, "XML is invalid") + raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) + + @classmethod + def deserialize_from_http_generics(cls, body_bytes, headers): + # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any + """Deserialize from HTTP response. + + Use bytes and headers to NOT use any requests/aiohttp or whatever + specific implementation. + Headers will tested for "content-type" + """ + # Try to use content-type from headers if available + content_type = None + if "content-type" in headers: + content_type = headers["content-type"].split(";")[0].strip().lower() + # Ouch, this server did not declare what it sent... + # Let's guess it's JSON... + # Also, since Autorest was considering that an empty body was a valid JSON, + # need that test as well.... + else: + content_type = "application/json" + + if body_bytes: + return cls.deserialize_from_text(body_bytes, content_type) + return None + + +try: + basestring # type: ignore + unicode_str = unicode # type: ignore +except NameError: + basestring = str # type: ignore + unicode_str = str # type: ignore + +_LOGGER = logging.getLogger(__name__) + +try: + _long_type = long # type: ignore +except NameError: + _long_type = int + + +class UTC(datetime.tzinfo): + """Time Zone info for handling UTC""" + + def utcoffset(self, dt): + """UTF offset for UTC is 0.""" + return datetime.timedelta(0) + + def tzname(self, dt): + """Timestamp representation.""" + return "Z" + + def dst(self, dt): + """No daylight saving for UTC.""" + return datetime.timedelta(hours=1) + + +try: + from datetime import timezone as _FixedOffset +except ImportError: # Python 2.7 + + class _FixedOffset(datetime.tzinfo): # type: ignore + """Fixed offset in minutes east from UTC. + Copy/pasted from Python doc + :param datetime.timedelta offset: offset in timedelta format + """ + + def __init__(self, offset): + self.__offset = offset + + def utcoffset(self, dt): + return self.__offset + + def tzname(self, dt): + return str(self.__offset.total_seconds() / 3600) + + def __repr__(self): + return "".format(self.tzname(None)) + + def dst(self, dt): + return datetime.timedelta(0) + + def __getinitargs__(self): + return (self.__offset,) + + +try: + from datetime import timezone + + TZ_UTC = timezone.utc # type: ignore +except ImportError: + TZ_UTC = UTC() # type: ignore + +_FLATTEN = re.compile(r"(? y, + "minimum": lambda x, y: x < y, + "maximum": lambda x, y: x > y, + "minimum_ex": lambda x, y: x <= y, + "maximum_ex": lambda x, y: x >= y, + "min_items": lambda x, y: len(x) < y, + "max_items": lambda x, y: len(x) > y, + "pattern": lambda x, y: not re.match(y, x, re.UNICODE), + "unique": lambda x, y: len(x) != len(set(x)), + "multiple": lambda x, y: x % y != 0, + } + + def __init__(self, classes=None): + self.serialize_type = { + "iso-8601": Serializer.serialize_iso, + "rfc-1123": Serializer.serialize_rfc, + "unix-time": Serializer.serialize_unix, + "duration": Serializer.serialize_duration, + "date": Serializer.serialize_date, + "time": Serializer.serialize_time, + "decimal": Serializer.serialize_decimal, + "long": Serializer.serialize_long, + "bytearray": Serializer.serialize_bytearray, + "base64": Serializer.serialize_base64, + "object": self.serialize_object, + "[]": self.serialize_iter, + "{}": self.serialize_dict, + } + self.dependencies = dict(classes) if classes else {} + self.key_transformer = full_restapi_key_transformer + self.client_side_validation = True + + def _serialize(self, target_obj, data_type=None, **kwargs): + """Serialize data into a string according to type. + + :param target_obj: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str, dict + :raises: SerializationError if serialization fails. + """ + key_transformer = kwargs.get("key_transformer", self.key_transformer) + keep_readonly = kwargs.get("keep_readonly", False) + if target_obj is None: + return None + + attr_name = None + class_name = target_obj.__class__.__name__ + + if data_type: + return self.serialize_data(target_obj, data_type, **kwargs) + + if not hasattr(target_obj, "_attribute_map"): + data_type = type(target_obj).__name__ + if data_type in self.basic_types.values(): + return self.serialize_data(target_obj, data_type, **kwargs) + + # Force "is_xml" kwargs if we detect a XML model + try: + is_xml_model_serialization = kwargs["is_xml"] + except KeyError: + is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) + + serialized = {} + if is_xml_model_serialization: + serialized = target_obj._create_xml_node() + try: + attributes = target_obj._attribute_map + for attr, attr_desc in attributes.items(): + attr_name = attr + if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): + continue + + if attr_name == "additional_properties" and attr_desc["key"] == "": + if target_obj.additional_properties is not None: + serialized.update(target_obj.additional_properties) + continue + try: + + orig_attr = getattr(target_obj, attr) + if is_xml_model_serialization: + pass # Don't provide "transformer" for XML for now. Keep "orig_attr" + else: # JSON + keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) + keys = keys if isinstance(keys, list) else [keys] + + kwargs["serialization_ctxt"] = attr_desc + new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) + + if is_xml_model_serialization: + xml_desc = attr_desc.get("xml", {}) + xml_name = xml_desc.get("name", attr_desc["key"]) + xml_prefix = xml_desc.get("prefix", None) + xml_ns = xml_desc.get("ns", None) + if xml_desc.get("attr", False): + if xml_ns: + ET.register_namespace(xml_prefix, xml_ns) + xml_name = "{}{}".format(xml_ns, xml_name) + serialized.set(xml_name, new_attr) + continue + if xml_desc.get("text", False): + serialized.text = new_attr + continue + if isinstance(new_attr, list): + serialized.extend(new_attr) + elif isinstance(new_attr, ET.Element): + # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. + if "name" not in getattr(orig_attr, "_xml_map", {}): + splitted_tag = new_attr.tag.split("}") + if len(splitted_tag) == 2: # Namespace + new_attr.tag = "}".join([splitted_tag[0], xml_name]) + else: + new_attr.tag = xml_name + serialized.append(new_attr) + else: # That's a basic type + # Integrate namespace if necessary + local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) + local_node.text = unicode_str(new_attr) + serialized.append(local_node) + else: # JSON + for k in reversed(keys): + unflattened = {k: new_attr} + new_attr = unflattened + + _new_attr = new_attr + _serialized = serialized + for k in keys: + if k not in _serialized: + _serialized.update(_new_attr) + _new_attr = _new_attr[k] + _serialized = _serialized[k] + except ValueError: + continue + + except (AttributeError, KeyError, TypeError) as err: + msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) + raise_with_traceback(SerializationError, msg, err) + else: + return serialized + + def body(self, data, data_type, **kwargs): + """Serialize data intended for a request body. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: dict + :raises: SerializationError if serialization fails. + :raises: ValueError if data is None + """ + + # Just in case this is a dict + internal_data_type = data_type.strip("[]{}") + internal_data_type = self.dependencies.get(internal_data_type, None) + try: + is_xml_model_serialization = kwargs["is_xml"] + except KeyError: + if internal_data_type and issubclass(internal_data_type, Model): + is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) + else: + is_xml_model_serialization = False + if internal_data_type and not isinstance(internal_data_type, Enum): + try: + deserializer = Deserializer(self.dependencies) + # Since it's on serialization, it's almost sure that format is not JSON REST + # We're not able to deal with additional properties for now. + deserializer.additional_properties_detection = False + if is_xml_model_serialization: + deserializer.key_extractors = [ + attribute_key_case_insensitive_extractor, + ] + else: + deserializer.key_extractors = [ + rest_key_case_insensitive_extractor, + attribute_key_case_insensitive_extractor, + last_rest_key_case_insensitive_extractor, + ] + data = deserializer._deserialize(data_type, data) + except DeserializationError as err: + raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) + + return self._serialize(data, data_type, **kwargs) + + def url(self, name, data, data_type, **kwargs): + """Serialize data intended for a URL path. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :raises: TypeError if serialization fails. + :raises: ValueError if data is None + """ + try: + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + + if kwargs.get("skip_quote") is True: + output = str(output) + else: + output = quote(str(output), safe="") + except SerializationError: + raise TypeError("{} must be type {}.".format(name, data_type)) + else: + return output + + def query(self, name, data, data_type, **kwargs): + """Serialize data intended for a URL query. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :raises: TypeError if serialization fails. + :raises: ValueError if data is None + """ + try: + # Treat the list aside, since we don't want to encode the div separator + if data_type.startswith("["): + internal_data_type = data_type[1:-1] + data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] + if not kwargs.get("skip_quote", False): + data = [quote(str(d), safe="") for d in data] + return str(self.serialize_iter(data, internal_data_type, **kwargs)) + + # Not a list, regular serialization + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + if kwargs.get("skip_quote") is True: + output = str(output) + else: + output = quote(str(output), safe="") + except SerializationError: + raise TypeError("{} must be type {}.".format(name, data_type)) + else: + return str(output) + + def header(self, name, data, data_type, **kwargs): + """Serialize data intended for a request header. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :raises: TypeError if serialization fails. + :raises: ValueError if data is None + """ + try: + if data_type in ["[str]"]: + data = ["" if d is None else d for d in data] + + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + except SerializationError: + raise TypeError("{} must be type {}.".format(name, data_type)) + else: + return str(output) + + def serialize_data(self, data, data_type, **kwargs): + """Serialize generic data according to supplied data type. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :param bool required: Whether it's essential that the data not be + empty or None + :raises: AttributeError if required data is None. + :raises: ValueError if data is None + :raises: SerializationError if serialization fails. + """ + if data is None: + raise ValueError("No value for given attribute") + + try: + if data_type in self.basic_types.values(): + return self.serialize_basic(data, data_type, **kwargs) + + elif data_type in self.serialize_type: + return self.serialize_type[data_type](data, **kwargs) + + # If dependencies is empty, try with current data class + # It has to be a subclass of Enum anyway + enum_type = self.dependencies.get(data_type, data.__class__) + if issubclass(enum_type, Enum): + return Serializer.serialize_enum(data, enum_obj=enum_type) + + iter_type = data_type[0] + data_type[-1] + if iter_type in self.serialize_type: + return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) + + except (ValueError, TypeError) as err: + msg = "Unable to serialize value: {!r} as type: {!r}." + raise_with_traceback(SerializationError, msg.format(data, data_type), err) + else: + return self._serialize(data, **kwargs) + + @classmethod + def _get_custom_serializers(cls, data_type, **kwargs): + custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) + if custom_serializer: + return custom_serializer + if kwargs.get("is_xml", False): + return cls._xml_basic_types_serializers.get(data_type) + + @classmethod + def serialize_basic(cls, data, data_type, **kwargs): + """Serialize basic builting data type. + Serializes objects to str, int, float or bool. + + Possible kwargs: + - basic_types_serializers dict[str, callable] : If set, use the callable as serializer + - is_xml bool : If set, use xml_basic_types_serializers + + :param data: Object to be serialized. + :param str data_type: Type of object in the iterable. + """ + custom_serializer = cls._get_custom_serializers(data_type, **kwargs) + if custom_serializer: + return custom_serializer(data) + if data_type == "str": + return cls.serialize_unicode(data) + return eval(data_type)(data) # nosec + + @classmethod + def serialize_unicode(cls, data): + """Special handling for serializing unicode strings in Py2. + Encode to UTF-8 if unicode, otherwise handle as a str. + + :param data: Object to be serialized. + :rtype: str + """ + try: # If I received an enum, return its value + return data.value + except AttributeError: + pass + + try: + if isinstance(data, unicode): + # Don't change it, JSON and XML ElementTree are totally able + # to serialize correctly u'' strings + return data + except NameError: + return str(data) + else: + return str(data) + + def serialize_iter(self, data, iter_type, div=None, **kwargs): + """Serialize iterable. + + Supported kwargs: + - serialization_ctxt dict : The current entry of _attribute_map, or same format. + serialization_ctxt['type'] should be same as data_type. + - is_xml bool : If set, serialize as XML + + :param list attr: Object to be serialized. + :param str iter_type: Type of object in the iterable. + :param bool required: Whether the objects in the iterable must + not be None or empty. + :param str div: If set, this str will be used to combine the elements + in the iterable into a combined string. Default is 'None'. + :rtype: list, str + """ + if isinstance(data, str): + raise SerializationError("Refuse str type as a valid iter type.") + + serialization_ctxt = kwargs.get("serialization_ctxt", {}) + is_xml = kwargs.get("is_xml", False) + + serialized = [] + for d in data: + try: + serialized.append(self.serialize_data(d, iter_type, **kwargs)) + except ValueError: + serialized.append(None) + + if div: + serialized = ["" if s is None else str(s) for s in serialized] + serialized = div.join(serialized) + + if "xml" in serialization_ctxt or is_xml: + # XML serialization is more complicated + xml_desc = serialization_ctxt.get("xml", {}) + xml_name = xml_desc.get("name") + if not xml_name: + xml_name = serialization_ctxt["key"] + + # Create a wrap node if necessary (use the fact that Element and list have "append") + is_wrapped = xml_desc.get("wrapped", False) + node_name = xml_desc.get("itemsName", xml_name) + if is_wrapped: + final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + else: + final_result = [] + # All list elements to "local_node" + for el in serialized: + if isinstance(el, ET.Element): + el_node = el + else: + el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + if el is not None: # Otherwise it writes "None" :-p + el_node.text = str(el) + final_result.append(el_node) + return final_result + return serialized + + def serialize_dict(self, attr, dict_type, **kwargs): + """Serialize a dictionary of objects. + + :param dict attr: Object to be serialized. + :param str dict_type: Type of object in the dictionary. + :param bool required: Whether the objects in the dictionary must + not be None or empty. + :rtype: dict + """ + serialization_ctxt = kwargs.get("serialization_ctxt", {}) + serialized = {} + for key, value in attr.items(): + try: + serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) + except ValueError: + serialized[self.serialize_unicode(key)] = None + + if "xml" in serialization_ctxt: + # XML serialization is more complicated + xml_desc = serialization_ctxt["xml"] + xml_name = xml_desc["name"] + + final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + for key, value in serialized.items(): + ET.SubElement(final_result, key).text = value + return final_result + + return serialized + + def serialize_object(self, attr, **kwargs): + """Serialize a generic object. + This will be handled as a dictionary. If object passed in is not + a basic type (str, int, float, dict, list) it will simply be + cast to str. + + :param dict attr: Object to be serialized. + :rtype: dict or str + """ + if attr is None: + return None + if isinstance(attr, ET.Element): + return attr + obj_type = type(attr) + if obj_type in self.basic_types: + return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) + if obj_type is _long_type: + return self.serialize_long(attr) + if obj_type is unicode_str: + return self.serialize_unicode(attr) + if obj_type is datetime.datetime: + return self.serialize_iso(attr) + if obj_type is datetime.date: + return self.serialize_date(attr) + if obj_type is datetime.time: + return self.serialize_time(attr) + if obj_type is datetime.timedelta: + return self.serialize_duration(attr) + if obj_type is decimal.Decimal: + return self.serialize_decimal(attr) + + # If it's a model or I know this dependency, serialize as a Model + elif obj_type in self.dependencies.values() or isinstance(attr, Model): + return self._serialize(attr) + + if obj_type == dict: + serialized = {} + for key, value in attr.items(): + try: + serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) + except ValueError: + serialized[self.serialize_unicode(key)] = None + return serialized + + if obj_type == list: + serialized = [] + for obj in attr: + try: + serialized.append(self.serialize_object(obj, **kwargs)) + except ValueError: + pass + return serialized + return str(attr) + + @staticmethod + def serialize_enum(attr, enum_obj=None): + try: + result = attr.value + except AttributeError: + result = attr + try: + enum_obj(result) + return result + except ValueError: + for enum_value in enum_obj: + if enum_value.value.lower() == str(attr).lower(): + return enum_value.value + error = "{!r} is not valid value for enum {!r}" + raise SerializationError(error.format(attr, enum_obj)) + + @staticmethod + def serialize_bytearray(attr, **kwargs): + """Serialize bytearray into base-64 string. + + :param attr: Object to be serialized. + :rtype: str + """ + return b64encode(attr).decode() + + @staticmethod + def serialize_base64(attr, **kwargs): + """Serialize str into base-64 string. + + :param attr: Object to be serialized. + :rtype: str + """ + encoded = b64encode(attr).decode("ascii") + return encoded.strip("=").replace("+", "-").replace("/", "_") + + @staticmethod + def serialize_decimal(attr, **kwargs): + """Serialize Decimal object to float. + + :param attr: Object to be serialized. + :rtype: float + """ + return float(attr) + + @staticmethod + def serialize_long(attr, **kwargs): + """Serialize long (Py2) or int (Py3). + + :param attr: Object to be serialized. + :rtype: int/long + """ + return _long_type(attr) + + @staticmethod + def serialize_date(attr, **kwargs): + """Serialize Date object into ISO-8601 formatted string. + + :param Date attr: Object to be serialized. + :rtype: str + """ + if isinstance(attr, str): + attr = isodate.parse_date(attr) + t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) + return t + + @staticmethod + def serialize_time(attr, **kwargs): + """Serialize Time object into ISO-8601 formatted string. + + :param datetime.time attr: Object to be serialized. + :rtype: str + """ + if isinstance(attr, str): + attr = isodate.parse_time(attr) + t = "{:02}:{:02}:{:02}".format(attr.hour, attr.minute, attr.second) + if attr.microsecond: + t += ".{:02}".format(attr.microsecond) + return t + + @staticmethod + def serialize_duration(attr, **kwargs): + """Serialize TimeDelta object into ISO-8601 formatted string. + + :param TimeDelta attr: Object to be serialized. + :rtype: str + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + return isodate.duration_isoformat(attr) + + @staticmethod + def serialize_rfc(attr, **kwargs): + """Serialize Datetime object into RFC-1123 formatted string. + + :param Datetime attr: Object to be serialized. + :rtype: str + :raises: TypeError if format invalid. + """ + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + utc = attr.utctimetuple() + except AttributeError: + raise TypeError("RFC1123 object must be valid Datetime object.") + + return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( + Serializer.days[utc.tm_wday], + utc.tm_mday, + Serializer.months[utc.tm_mon], + utc.tm_year, + utc.tm_hour, + utc.tm_min, + utc.tm_sec, + ) + + @staticmethod + def serialize_iso(attr, **kwargs): + """Serialize Datetime object into ISO-8601 formatted string. + + :param Datetime attr: Object to be serialized. + :rtype: str + :raises: SerializationError if format invalid. + """ + if isinstance(attr, str): + attr = isodate.parse_datetime(attr) + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + utc = attr.utctimetuple() + if utc.tm_year > 9999 or utc.tm_year < 1: + raise OverflowError("Hit max or min date") + + microseconds = str(attr.microsecond).rjust(6, "0").rstrip("0").ljust(3, "0") + if microseconds: + microseconds = "." + microseconds + date = "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}".format( + utc.tm_year, utc.tm_mon, utc.tm_mday, utc.tm_hour, utc.tm_min, utc.tm_sec + ) + return date + microseconds + "Z" + except (ValueError, OverflowError) as err: + msg = "Unable to serialize datetime object." + raise_with_traceback(SerializationError, msg, err) + except AttributeError as err: + msg = "ISO-8601 object must be valid Datetime object." + raise_with_traceback(TypeError, msg, err) + + @staticmethod + def serialize_unix(attr, **kwargs): + """Serialize Datetime object into IntTime format. + This is represented as seconds. + + :param Datetime attr: Object to be serialized. + :rtype: int + :raises: SerializationError if format invalid + """ + if isinstance(attr, int): + return attr + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + return int(calendar.timegm(attr.utctimetuple())) + except AttributeError: + raise TypeError("Unix time object must be valid Datetime object.") + + +def rest_key_extractor(attr, attr_desc, data): + key = attr_desc["key"] + working_data = data + + while "." in key: + dict_keys = _FLATTEN.split(key) + if len(dict_keys) == 1: + key = _decode_attribute_map_key(dict_keys[0]) + break + working_key = _decode_attribute_map_key(dict_keys[0]) + working_data = working_data.get(working_key, data) + if working_data is None: + # If at any point while following flatten JSON path see None, it means + # that all properties under are None as well + # https://github.com/Azure/msrest-for-python/issues/197 + return None + key = ".".join(dict_keys[1:]) + + return working_data.get(key) + + +def rest_key_case_insensitive_extractor(attr, attr_desc, data): + key = attr_desc["key"] + working_data = data + + while "." in key: + dict_keys = _FLATTEN.split(key) + if len(dict_keys) == 1: + key = _decode_attribute_map_key(dict_keys[0]) + break + working_key = _decode_attribute_map_key(dict_keys[0]) + working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) + if working_data is None: + # If at any point while following flatten JSON path see None, it means + # that all properties under are None as well + # https://github.com/Azure/msrest-for-python/issues/197 + return None + key = ".".join(dict_keys[1:]) + + if working_data: + return attribute_key_case_insensitive_extractor(key, None, working_data) + + +def last_rest_key_extractor(attr, attr_desc, data): + """Extract the attribute in "data" based on the last part of the JSON path key.""" + key = attr_desc["key"] + dict_keys = _FLATTEN.split(key) + return attribute_key_extractor(dict_keys[-1], None, data) + + +def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): + """Extract the attribute in "data" based on the last part of the JSON path key. + + This is the case insensitive version of "last_rest_key_extractor" + """ + key = attr_desc["key"] + dict_keys = _FLATTEN.split(key) + return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) + + +def attribute_key_extractor(attr, _, data): + return data.get(attr) + + +def attribute_key_case_insensitive_extractor(attr, _, data): + found_key = None + lower_attr = attr.lower() + for key in data: + if lower_attr == key.lower(): + found_key = key + break + + return data.get(found_key) + + +def _extract_name_from_internal_type(internal_type): + """Given an internal type XML description, extract correct XML name with namespace. + + :param dict internal_type: An model type + :rtype: tuple + :returns: A tuple XML name + namespace dict + """ + internal_type_xml_map = getattr(internal_type, "_xml_map", {}) + xml_name = internal_type_xml_map.get("name", internal_type.__name__) + xml_ns = internal_type_xml_map.get("ns", None) + if xml_ns: + xml_name = "{}{}".format(xml_ns, xml_name) + return xml_name + + +def xml_key_extractor(attr, attr_desc, data): + if isinstance(data, dict): + return None + + # Test if this model is XML ready first + if not isinstance(data, ET.Element): + return None + + xml_desc = attr_desc.get("xml", {}) + xml_name = xml_desc.get("name", attr_desc["key"]) + + # Look for a children + is_iter_type = attr_desc["type"].startswith("[") + is_wrapped = xml_desc.get("wrapped", False) + internal_type = attr_desc.get("internalType", None) + internal_type_xml_map = getattr(internal_type, "_xml_map", {}) + + # Integrate namespace if necessary + xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) + if xml_ns: + xml_name = "{}{}".format(xml_ns, xml_name) + + # If it's an attribute, that's simple + if xml_desc.get("attr", False): + return data.get(xml_name) + + # If it's x-ms-text, that's simple too + if xml_desc.get("text", False): + return data.text + + # Scenario where I take the local name: + # - Wrapped node + # - Internal type is an enum (considered basic types) + # - Internal type has no XML/Name node + if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): + children = data.findall(xml_name) + # If internal type has a local name and it's not a list, I use that name + elif not is_iter_type and internal_type and "name" in internal_type_xml_map: + xml_name = _extract_name_from_internal_type(internal_type) + children = data.findall(xml_name) + # That's an array + else: + if internal_type: # Complex type, ignore itemsName and use the complex type name + items_name = _extract_name_from_internal_type(internal_type) + else: + items_name = xml_desc.get("itemsName", xml_name) + children = data.findall(items_name) + + if len(children) == 0: + if is_iter_type: + if is_wrapped: + return None # is_wrapped no node, we want None + else: + return [] # not wrapped, assume empty list + return None # Assume it's not there, maybe an optional node. + + # If is_iter_type and not wrapped, return all found children + if is_iter_type: + if not is_wrapped: + return children + else: # Iter and wrapped, should have found one node only (the wrap one) + if len(children) != 1: + raise DeserializationError( + "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( + xml_name + ) + ) + return list(children[0]) # Might be empty list and that's ok. + + # Here it's not a itertype, we should have found one element only or empty + if len(children) > 1: + raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) + return children[0] + + +class Deserializer(object): + """Response object model deserializer. + + :param dict classes: Class type dictionary for deserializing complex types. + :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. + """ + + basic_types = {str: "str", int: "int", bool: "bool", float: "float"} + + valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}" r"\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") + + def __init__(self, classes=None): + self.deserialize_type = { + "iso-8601": Deserializer.deserialize_iso, + "rfc-1123": Deserializer.deserialize_rfc, + "unix-time": Deserializer.deserialize_unix, + "duration": Deserializer.deserialize_duration, + "date": Deserializer.deserialize_date, + "time": Deserializer.deserialize_time, + "decimal": Deserializer.deserialize_decimal, + "long": Deserializer.deserialize_long, + "bytearray": Deserializer.deserialize_bytearray, + "base64": Deserializer.deserialize_base64, + "object": self.deserialize_object, + "[]": self.deserialize_iter, + "{}": self.deserialize_dict, + } + self.deserialize_expected_types = { + "duration": (isodate.Duration, datetime.timedelta), + "iso-8601": (datetime.datetime), + } + self.dependencies = dict(classes) if classes else {} + self.key_extractors = [rest_key_extractor, xml_key_extractor] + # Additional properties only works if the "rest_key_extractor" is used to + # extract the keys. Making it to work whatever the key extractor is too much + # complicated, with no real scenario for now. + # So adding a flag to disable additional properties detection. This flag should be + # used if your expect the deserialization to NOT come from a JSON REST syntax. + # Otherwise, result are unexpected + self.additional_properties_detection = True + + def __call__(self, target_obj, response_data, content_type=None): + """Call the deserializer to process a REST response. + + :param str target_obj: Target data type to deserialize to. + :param requests.Response response_data: REST response object. + :param str content_type: Swagger "produces" if available. + :raises: DeserializationError if deserialization fails. + :return: Deserialized object. + """ + data = self._unpack_content(response_data, content_type) + return self._deserialize(target_obj, data) + + def _deserialize(self, target_obj, data): + """Call the deserializer on a model. + + Data needs to be already deserialized as JSON or XML ElementTree + + :param str target_obj: Target data type to deserialize to. + :param object data: Object to deserialize. + :raises: DeserializationError if deserialization fails. + :return: Deserialized object. + """ + # This is already a model, go recursive just in case + if hasattr(data, "_attribute_map"): + constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] + try: + for attr, mapconfig in data._attribute_map.items(): + if attr in constants: + continue + value = getattr(data, attr) + if value is None: + continue + local_type = mapconfig["type"] + internal_data_type = local_type.strip("[]{}") + if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): + continue + setattr(data, attr, self._deserialize(local_type, value)) + return data + except AttributeError: + return + + response, class_name = self._classify_target(target_obj, data) + + if isinstance(response, basestring): + return self.deserialize_data(data, response) + elif isinstance(response, type) and issubclass(response, Enum): + return self.deserialize_enum(data, response) + + if data is None: + return data + try: + attributes = response._attribute_map + d_attrs = {} + for attr, attr_desc in attributes.items(): + # Check empty string. If it's not empty, someone has a real "additionalProperties"... + if attr == "additional_properties" and attr_desc["key"] == "": + continue + raw_value = None + # Enhance attr_desc with some dynamic data + attr_desc = attr_desc.copy() # Do a copy, do not change the real one + internal_data_type = attr_desc["type"].strip("[]{}") + if internal_data_type in self.dependencies: + attr_desc["internalType"] = self.dependencies[internal_data_type] + + for key_extractor in self.key_extractors: + found_value = key_extractor(attr, attr_desc, data) + if found_value is not None: + if raw_value is not None and raw_value != found_value: + msg = ( + "Ignoring extracted value '%s' from %s for key '%s'" + " (duplicate extraction, follow extractors order)" + ) + _LOGGER.warning(msg, found_value, key_extractor, attr) + continue + raw_value = found_value + + value = self.deserialize_data(raw_value, attr_desc["type"]) + d_attrs[attr] = value + except (AttributeError, TypeError, KeyError) as err: + msg = "Unable to deserialize to object: " + class_name + raise_with_traceback(DeserializationError, msg, err) + else: + additional_properties = self._build_additional_properties(attributes, data) + return self._instantiate_model(response, d_attrs, additional_properties) + + def _build_additional_properties(self, attribute_map, data): + if not self.additional_properties_detection: + return None + if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": + # Check empty string. If it's not empty, someone has a real "additionalProperties" + return None + if isinstance(data, ET.Element): + data = {el.tag: el.text for el in data} + + known_keys = { + _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) + for desc in attribute_map.values() + if desc["key"] != "" + } + present_keys = set(data.keys()) + missing_keys = present_keys - known_keys + return {key: data[key] for key in missing_keys} + + def _classify_target(self, target, data): + """Check to see whether the deserialization target object can + be classified into a subclass. + Once classification has been determined, initialize object. + + :param str target: The target object type to deserialize to. + :param str/dict data: The response data to deseralize. + """ + if target is None: + return None, None + + if isinstance(target, basestring): + try: + target = self.dependencies[target] + except KeyError: + return target, target + + try: + target = target._classify(data, self.dependencies) + except AttributeError: + pass # Target is not a Model, no classify + return target, target.__class__.__name__ + + def failsafe_deserialize(self, target_obj, data, content_type=None): + """Ignores any errors encountered in deserialization, + and falls back to not deserializing the object. Recommended + for use in error deserialization, as we want to return the + HttpResponseError to users, and not have them deal with + a deserialization error. + + :param str target_obj: The target object type to deserialize to. + :param str/dict data: The response data to deseralize. + :param str content_type: Swagger "produces" if available. + """ + try: + return self(target_obj, data, content_type=content_type) + except: + _LOGGER.debug( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + @staticmethod + def _unpack_content(raw_data, content_type=None): + """Extract the correct structure for deserialization. + + If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. + if we can't, raise. Your Pipeline should have a RawDeserializer. + + If not a pipeline response and raw_data is bytes or string, use content-type + to decode it. If no content-type, try JSON. + + If raw_data is something else, bypass all logic and return it directly. + + :param raw_data: Data to be processed. + :param content_type: How to parse if raw_data is a string/bytes. + :raises JSONDecodeError: If JSON is requested and parsing is impossible. + :raises UnicodeDecodeError: If bytes is not UTF8 + """ + # Assume this is enough to detect a Pipeline Response without importing it + context = getattr(raw_data, "context", {}) + if context: + if RawDeserializer.CONTEXT_NAME in context: + return context[RawDeserializer.CONTEXT_NAME] + raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") + + # Assume this is enough to recognize universal_http.ClientResponse without importing it + if hasattr(raw_data, "body"): + return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) + + # Assume this enough to recognize requests.Response without importing it. + if hasattr(raw_data, "_content_consumed"): + return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) + + if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): + return RawDeserializer.deserialize_from_text(raw_data, content_type) + return raw_data + + def _instantiate_model(self, response, attrs, additional_properties=None): + """Instantiate a response model passing in deserialized args. + + :param response: The response model class. + :param d_attrs: The deserialized response attributes. + """ + if callable(response): + subtype = getattr(response, "_subtype_map", {}) + try: + readonly = [k for k, v in response._validation.items() if v.get("readonly")] + const = [k for k, v in response._validation.items() if v.get("constant")] + kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} + response_obj = response(**kwargs) + for attr in readonly: + setattr(response_obj, attr, attrs.get(attr)) + if additional_properties: + response_obj.additional_properties = additional_properties + return response_obj + except TypeError as err: + msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) + raise DeserializationError(msg + str(err)) + else: + try: + for attr, value in attrs.items(): + setattr(response, attr, value) + return response + except Exception as exp: + msg = "Unable to populate response model. " + msg += "Type: {}, Error: {}".format(type(response), exp) + raise DeserializationError(msg) + + def deserialize_data(self, data, data_type): + """Process data for deserialization according to data type. + + :param str data: The response string to be deserialized. + :param str data_type: The type to deserialize to. + :raises: DeserializationError if deserialization fails. + :return: Deserialized object. + """ + if data is None: + return data + + try: + if not data_type: + return data + if data_type in self.basic_types.values(): + return self.deserialize_basic(data, data_type) + if data_type in self.deserialize_type: + if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): + return data + + is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] + if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: + return None + data_val = self.deserialize_type[data_type](data) + return data_val + + iter_type = data_type[0] + data_type[-1] + if iter_type in self.deserialize_type: + return self.deserialize_type[iter_type](data, data_type[1:-1]) + + obj_type = self.dependencies[data_type] + if issubclass(obj_type, Enum): + if isinstance(data, ET.Element): + data = data.text + return self.deserialize_enum(data, obj_type) + + except (ValueError, TypeError, AttributeError) as err: + msg = "Unable to deserialize response data." + msg += " Data: {}, {}".format(data, data_type) + raise_with_traceback(DeserializationError, msg, err) + else: + return self._deserialize(obj_type, data) + + def deserialize_iter(self, attr, iter_type): + """Deserialize an iterable. + + :param list attr: Iterable to be deserialized. + :param str iter_type: The type of object in the iterable. + :rtype: list + """ + if attr is None: + return None + if isinstance(attr, ET.Element): # If I receive an element here, get the children + attr = list(attr) + if not isinstance(attr, (list, set)): + raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) + return [self.deserialize_data(a, iter_type) for a in attr] + + def deserialize_dict(self, attr, dict_type): + """Deserialize a dictionary. + + :param dict/list attr: Dictionary to be deserialized. Also accepts + a list of key, value pairs. + :param str dict_type: The object type of the items in the dictionary. + :rtype: dict + """ + if isinstance(attr, list): + return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} + + if isinstance(attr, ET.Element): + # Transform value into {"Key": "value"} + attr = {el.tag: el.text for el in attr} + return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} + + def deserialize_object(self, attr, **kwargs): + """Deserialize a generic object. + This will be handled as a dictionary. + + :param dict attr: Dictionary to be deserialized. + :rtype: dict + :raises: TypeError if non-builtin datatype encountered. + """ + if attr is None: + return None + if isinstance(attr, ET.Element): + # Do no recurse on XML, just return the tree as-is + return attr + if isinstance(attr, basestring): + return self.deserialize_basic(attr, "str") + obj_type = type(attr) + if obj_type in self.basic_types: + return self.deserialize_basic(attr, self.basic_types[obj_type]) + if obj_type is _long_type: + return self.deserialize_long(attr) + + if obj_type == dict: + deserialized = {} + for key, value in attr.items(): + try: + deserialized[key] = self.deserialize_object(value, **kwargs) + except ValueError: + deserialized[key] = None + return deserialized + + if obj_type == list: + deserialized = [] + for obj in attr: + try: + deserialized.append(self.deserialize_object(obj, **kwargs)) + except ValueError: + pass + return deserialized + + else: + error = "Cannot deserialize generic object with type: " + raise TypeError(error + str(obj_type)) + + def deserialize_basic(self, attr, data_type): + """Deserialize basic builtin data type from string. + Will attempt to convert to str, int, float and bool. + This function will also accept '1', '0', 'true' and 'false' as + valid bool values. + + :param str attr: response string to be deserialized. + :param str data_type: deserialization data type. + :rtype: str, int, float or bool + :raises: TypeError if string format is not valid. + """ + # If we're here, data is supposed to be a basic type. + # If it's still an XML node, take the text + if isinstance(attr, ET.Element): + attr = attr.text + if not attr: + if data_type == "str": + # None or '', node is empty string. + return "" + else: + # None or '', node with a strong type is None. + # Don't try to model "empty bool" or "empty int" + return None + + if data_type == "bool": + if attr in [True, False, 1, 0]: + return bool(attr) + elif isinstance(attr, basestring): + if attr.lower() in ["true", "1"]: + return True + elif attr.lower() in ["false", "0"]: + return False + raise TypeError("Invalid boolean value: {}".format(attr)) + + if data_type == "str": + return self.deserialize_unicode(attr) + return eval(data_type)(attr) # nosec + + @staticmethod + def deserialize_unicode(data): + """Preserve unicode objects in Python 2, otherwise return data + as a string. + + :param str data: response string to be deserialized. + :rtype: str or unicode + """ + # We might be here because we have an enum modeled as string, + # and we try to deserialize a partial dict with enum inside + if isinstance(data, Enum): + return data + + # Consider this is real string + try: + if isinstance(data, unicode): + return data + except NameError: + return str(data) + else: + return str(data) + + @staticmethod + def deserialize_enum(data, enum_obj): + """Deserialize string into enum object. + + If the string is not a valid enum value it will be returned as-is + and a warning will be logged. + + :param str data: Response string to be deserialized. If this value is + None or invalid it will be returned as-is. + :param Enum enum_obj: Enum object to deserialize to. + :rtype: Enum + """ + if isinstance(data, enum_obj) or data is None: + return data + if isinstance(data, Enum): + data = data.value + if isinstance(data, int): + # Workaround. We might consider remove it in the future. + # https://github.com/Azure/azure-rest-api-specs/issues/141 + try: + return list(enum_obj.__members__.values())[data] + except IndexError: + error = "{!r} is not a valid index for enum {!r}" + raise DeserializationError(error.format(data, enum_obj)) + try: + return enum_obj(str(data)) + except ValueError: + for enum_value in enum_obj: + if enum_value.value.lower() == str(data).lower(): + return enum_value + # We don't fail anymore for unknown value, we deserialize as a string + _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) + return Deserializer.deserialize_unicode(data) + + @staticmethod + def deserialize_bytearray(attr): + """Deserialize string into bytearray. + + :param str attr: response string to be deserialized. + :rtype: bytearray + :raises: TypeError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + return bytearray(b64decode(attr)) + + @staticmethod + def deserialize_base64(attr): + """Deserialize base64 encoded string into string. + + :param str attr: response string to be deserialized. + :rtype: bytearray + :raises: TypeError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + padding = "=" * (3 - (len(attr) + 3) % 4) + attr = attr + padding + encoded = attr.replace("-", "+").replace("_", "/") + return b64decode(encoded) + + @staticmethod + def deserialize_decimal(attr): + """Deserialize string into Decimal object. + + :param str attr: response string to be deserialized. + :rtype: Decimal + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + return decimal.Decimal(attr) + except decimal.DecimalException as err: + msg = "Invalid decimal {}".format(attr) + raise_with_traceback(DeserializationError, msg, err) + + @staticmethod + def deserialize_long(attr): + """Deserialize string into long (Py2) or int (Py3). + + :param str attr: response string to be deserialized. + :rtype: long or int + :raises: ValueError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + return _long_type(attr) + + @staticmethod + def deserialize_duration(attr): + """Deserialize ISO-8601 formatted string into TimeDelta object. + + :param str attr: response string to be deserialized. + :rtype: TimeDelta + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = isodate.parse_duration(attr) + except (ValueError, OverflowError, AttributeError) as err: + msg = "Cannot deserialize duration object." + raise_with_traceback(DeserializationError, msg, err) + else: + return duration + + @staticmethod + def deserialize_date(attr): + """Deserialize ISO-8601 formatted string into Date object. + + :param str attr: response string to be deserialized. + :rtype: Date + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + if re.search(r"[^\W\d_]", attr, re.I + re.U): + raise DeserializationError("Date must have only digits and -. Received: %s" % attr) + # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. + return isodate.parse_date(attr, defaultmonth=None, defaultday=None) + + @staticmethod + def deserialize_time(attr): + """Deserialize ISO-8601 formatted string into time object. + + :param str attr: response string to be deserialized. + :rtype: datetime.time + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + if re.search(r"[^\W\d_]", attr, re.I + re.U): + raise DeserializationError("Date must have only digits and -. Received: %s" % attr) + return isodate.parse_time(attr) + + @staticmethod + def deserialize_rfc(attr): + """Deserialize RFC-1123 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: Datetime + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + parsed_date = email.utils.parsedate_tz(attr) + date_obj = datetime.datetime( + *parsed_date[:6], tzinfo=_FixedOffset(datetime.timedelta(minutes=(parsed_date[9] or 0) / 60)) + ) + if not date_obj.tzinfo: + date_obj = date_obj.astimezone(tz=TZ_UTC) + except ValueError as err: + msg = "Cannot deserialize to rfc datetime object." + raise_with_traceback(DeserializationError, msg, err) + else: + return date_obj + + @staticmethod + def deserialize_iso(attr): + """Deserialize ISO-8601 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: Datetime + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + attr = attr.upper() + match = Deserializer.valid_date.match(attr) + if not match: + raise ValueError("Invalid datetime string: " + attr) + + check_decimal = attr.split(".") + if len(check_decimal) > 1: + decimal_str = "" + for digit in check_decimal[1]: + if digit.isdigit(): + decimal_str += digit + else: + break + if len(decimal_str) > 6: + attr = attr.replace(decimal_str, decimal_str[0:6]) + + date_obj = isodate.parse_datetime(attr) + test_utc = date_obj.utctimetuple() + if test_utc.tm_year > 9999 or test_utc.tm_year < 1: + raise OverflowError("Hit max or min date") + except (ValueError, OverflowError, AttributeError) as err: + msg = "Cannot deserialize datetime object." + raise_with_traceback(DeserializationError, msg, err) + else: + return date_obj + + @staticmethod + def deserialize_unix(attr): + """Serialize Datetime object into IntTime format. + This is represented as seconds. + + :param int attr: Object to be serialized. + :rtype: Datetime + :raises: DeserializationError if format invalid + """ + if isinstance(attr, ET.Element): + attr = int(attr.text) + try: + date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) + except ValueError as err: + msg = "Cannot deserialize to unix datetime object." + raise_with_traceback(DeserializationError, msg, err) + else: + return date_obj diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/_vendor.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/_vendor.py index 138f663c53a4..9aad73fc743e 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/_vendor.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/_vendor.py @@ -7,6 +7,7 @@ from azure.core.pipeline.transport import HttpRequest + def _convert_request(request, files=None): data = request.content if not files else None request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) @@ -14,6 +15,7 @@ def _convert_request(request, files=None): request.set_formdata_body(files) return request + def _format_url_section(template, **kwargs): components = template.split("/") while components: @@ -21,7 +23,5 @@ def _format_url_section(template, **kwargs): return template.format(**kwargs) except KeyError as key: formatted_components = template.split("/") - components = [ - c for c in formatted_components if "{}".format(key.args[0]) not in c - ] + components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] template = "/".join(components) diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/_version.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/_version.py index a172f504a7eb..e5754a47ce68 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/_version.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "10.2.0b3" +VERSION = "1.0.0b1" diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/__init__.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/__init__.py index a25065677613..2899d38f999d 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/__init__.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/__init__.py @@ -14,7 +14,8 @@ except ImportError: _patch_all = [] from ._patch import patch_sdk as _patch_sdk -__all__ = ['MySQLManagementClient'] + +__all__ = ["MySQLManagementClient"] __all__.extend([p for p in _patch_all if p not in __all__]) _patch_sdk() diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/_configuration.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/_configuration.py index d1e5eaabd12d..d80ef78031da 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/_configuration.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/_configuration.py @@ -25,23 +25,18 @@ class MySQLManagementClientConfiguration(Configuration): # pylint: disable=too- Note that all parameters used to create this instance are saved as instance attributes. - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: The ID of the target subscription. + :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str :keyword api_version: Api Version. Default value is "2021-12-01-preview". Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str """ - def __init__( - self, - credential: "AsyncTokenCredential", - subscription_id: str, - **kwargs: Any - ) -> None: + def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: super(MySQLManagementClientConfiguration, self).__init__(**kwargs) - api_version = kwargs.pop('api_version', "2021-12-01-preview") # type: str + api_version = kwargs.pop("api_version", "2021-12-01-preview") # type: str if credential is None: raise ValueError("Parameter 'credential' must not be None.") @@ -51,22 +46,21 @@ def __init__( self.credential = credential self.subscription_id = subscription_id self.api_version = api_version - self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'mgmt-rdbms/{}'.format(VERSION)) + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-rdbms/{}".format(VERSION)) self._configure(**kwargs) - def _configure( - self, - **kwargs: Any - ) -> None: - self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get('retry_policy') or policies.AsyncRetryPolicy(**kwargs) - self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get('redirect_policy') or policies.AsyncRedirectPolicy(**kwargs) - self.authentication_policy = kwargs.get('authentication_policy') + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: - self.authentication_policy = AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs) + self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/_my_sql_management_client.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/_my_sql_management_client.py index a8f9e6ac2e4b..b2d6f50f5fca 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/_my_sql_management_client.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/_my_sql_management_client.py @@ -9,20 +9,35 @@ from copy import deepcopy from typing import Any, Awaitable, TYPE_CHECKING -from msrest import Deserializer, Serializer - from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient from .. import models +from .._serialization import Deserializer, Serializer from ._configuration import MySQLManagementClientConfiguration -from .operations import AzureADAdministratorsOperations, BackupsOperations, CheckNameAvailabilityOperations, CheckNameAvailabilityWithoutLocationOperations, CheckVirtualNetworkSubnetUsageOperations, ConfigurationsOperations, DatabasesOperations, FirewallRulesOperations, GetPrivateDnsZoneSuffixOperations, LocationBasedCapabilitiesOperations, LogFilesOperations, Operations, ReplicasOperations, ServersOperations +from .operations import ( + AzureADAdministratorsOperations, + BackupsOperations, + CheckNameAvailabilityOperations, + CheckNameAvailabilityWithoutLocationOperations, + CheckVirtualNetworkSubnetUsageOperations, + ConfigurationsOperations, + DatabasesOperations, + FirewallRulesOperations, + GetPrivateDnsZoneSuffixOperations, + LocationBasedCapabilitiesOperations, + LogFilesOperations, + Operations, + ReplicasOperations, + ServersOperations, +) if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class MySQLManagementClient: # pylint: disable=too-many-instance-attributes + +class MySQLManagementClient: # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes """The Microsoft Azure management API provides create, read, update, and delete functionality for Azure MySQL resources including servers, databases, firewall rules, VNET rules, log files and configurations with new business model. @@ -64,9 +79,9 @@ class MySQLManagementClient: # pylint: disable=too-many-instance-attributes :ivar azure_ad_administrators: AzureADAdministratorsOperations operations :vartype azure_ad_administrators: azure.mgmt.rdbms.mysql_flexibleservers.aio.operations.AzureADAdministratorsOperations - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: The ID of the target subscription. + :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str :param base_url: Service URL. Default value is "https://management.azure.com". :type base_url: str @@ -84,34 +99,22 @@ def __init__( base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: - self._config = MySQLManagementClientConfiguration(credential=credential, subscription_id=subscription_id, **kwargs) + self._config = MySQLManagementClientConfiguration( + credential=credential, subscription_id=subscription_id, **kwargs + ) self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) self._deserialize = Deserializer(client_models) self._serialize.client_side_validation = False - self.backups = BackupsOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.configurations = ConfigurationsOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.databases = DatabasesOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.firewall_rules = FirewallRulesOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.servers = ServersOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.replicas = ReplicasOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.log_files = LogFilesOperations( - self._client, self._config, self._serialize, self._deserialize - ) + self.backups = BackupsOperations(self._client, self._config, self._serialize, self._deserialize) + self.configurations = ConfigurationsOperations(self._client, self._config, self._serialize, self._deserialize) + self.databases = DatabasesOperations(self._client, self._config, self._serialize, self._deserialize) + self.firewall_rules = FirewallRulesOperations(self._client, self._config, self._serialize, self._deserialize) + self.servers = ServersOperations(self._client, self._config, self._serialize, self._deserialize) + self.replicas = ReplicasOperations(self._client, self._config, self._serialize, self._deserialize) + self.log_files = LogFilesOperations(self._client, self._config, self._serialize, self._deserialize) self.location_based_capabilities = LocationBasedCapabilitiesOperations( self._client, self._config, self._serialize, self._deserialize ) @@ -127,19 +130,12 @@ def __init__( self.get_private_dns_zone_suffix = GetPrivateDnsZoneSuffixOperations( 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) self.azure_ad_administrators = AzureADAdministratorsOperations( self._client, self._config, self._serialize, self._deserialize ) - - def _send_request( - self, - request: HttpRequest, - **kwargs: Any - ) -> Awaitable[AsyncHttpResponse]: + def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: """Runs the network request through the client's chained policies. >>> from azure.core.rest import HttpRequest @@ -148,7 +144,7 @@ def _send_request( >>> response = await client._send_request(request) - For more information on this code flow, see https://aka.ms/azsdk/python/protocol/quickstart + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request :param request: The network request you want to make. Required. :type request: ~azure.core.rest.HttpRequest diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/_patch.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/_patch.py index 74e48ecd07cf..f99e77fef986 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/_patch.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/_patch.py @@ -28,4 +28,4 @@ # This file is used for handwritten extensions to the generated code. Example: # https://github.com/Azure/azure-sdk-for-python/blob/main/doc/dev/customize_code/how-to-patch-sdk-code.md def patch_sdk(): - pass \ No newline at end of file + pass diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/__init__.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/__init__.py index fe672c1663f0..ee84bcc56466 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/__init__.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/__init__.py @@ -24,21 +24,22 @@ from ._patch import __all__ as _patch_all from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import from ._patch import patch_sdk as _patch_sdk + __all__ = [ - 'BackupsOperations', - 'ConfigurationsOperations', - 'DatabasesOperations', - 'FirewallRulesOperations', - 'ServersOperations', - 'ReplicasOperations', - 'LogFilesOperations', - 'LocationBasedCapabilitiesOperations', - 'CheckVirtualNetworkSubnetUsageOperations', - 'CheckNameAvailabilityOperations', - 'CheckNameAvailabilityWithoutLocationOperations', - 'GetPrivateDnsZoneSuffixOperations', - 'Operations', - 'AzureADAdministratorsOperations', + "BackupsOperations", + "ConfigurationsOperations", + "DatabasesOperations", + "FirewallRulesOperations", + "ServersOperations", + "ReplicasOperations", + "LogFilesOperations", + "LocationBasedCapabilitiesOperations", + "CheckVirtualNetworkSubnetUsageOperations", + "CheckNameAvailabilityOperations", + "CheckNameAvailabilityWithoutLocationOperations", + "GetPrivateDnsZoneSuffixOperations", + "Operations", + "AzureADAdministratorsOperations", ] __all__.extend([p for p in _patch_all if p not in __all__]) -_patch_sdk() \ No newline at end of file +_patch_sdk() diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_azure_ad_administrators_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_azure_ad_administrators_operations.py index ae248d49ef60..70f165da2195 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_azure_ad_administrators_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_azure_ad_administrators_operations.py @@ -6,10 +6,18 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar, Union, cast +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod @@ -22,10 +30,17 @@ from ... import models as _models from ..._vendor import _convert_request -from ...operations._azure_ad_administrators_operations import build_create_or_update_request_initial, build_delete_request_initial, build_get_request, build_list_by_server_request -T = TypeVar('T') +from ...operations._azure_ad_administrators_operations import ( + build_create_or_update_request, + build_delete_request, + build_get_request, + build_list_by_server_request, +) + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class AzureADAdministratorsOperations: """ .. warning:: @@ -45,38 +60,47 @@ def __init__(self, *args, **kwargs) -> None: 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") - async def _create_or_update_initial( self, resource_group_name: str, server_name: str, - administrator_name: Union[str, "_models.AdministratorName"], - parameters: _models.AzureADAdministrator, + administrator_name: Union[str, _models.AdministratorName], + parameters: Union[_models.AzureADAdministrator, IO], **kwargs: Any ) -> Optional[_models.AzureADAdministrator]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[Optional[_models.AzureADAdministrator]] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.AzureADAdministrator]] - _json = self._serialize.body(parameters, 'AzureADAdministrator') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "AzureADAdministrator") - request = build_create_or_update_request_initial( - subscription_id=self._config.subscription_id, + request = build_create_or_update_request( resource_group_name=resource_group_name, server_name=server_name, administrator_name=administrator_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._create_or_update_initial.metadata['url'], + content=_content, + template_url=self._create_or_update_initial.metadata["url"], headers=_headers, params=_params, ) @@ -84,10 +108,9 @@ async def _create_or_update_initial( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 201, 202]: @@ -96,39 +119,45 @@ async def _create_or_update_initial( deserialized = None if response.status_code == 200: - deserialized = self._deserialize('AzureADAdministrator', pipeline_response) + deserialized = self._deserialize("AzureADAdministrator", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('AzureADAdministrator', pipeline_response) + deserialized = self._deserialize("AzureADAdministrator", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _create_or_update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/administrators/{administratorName}"} # type: ignore - + _create_or_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/administrators/{administratorName}"} # type: ignore - @distributed_trace_async + @overload async def begin_create_or_update( self, resource_group_name: str, server_name: str, - administrator_name: Union[str, "_models.AdministratorName"], + administrator_name: Union[str, _models.AdministratorName], parameters: _models.AzureADAdministrator, + *, + content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.AzureADAdministrator]: """Creates or updates an existing Azure Active Directory administrator. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param administrator_name: The name of the Azure AD Administrator. + :param administrator_name: The name of the Azure AD Administrator. "ActiveDirectory" Required. :type administrator_name: str or ~azure.mgmt.rdbms.mysql_flexibleservers.models.AdministratorName :param parameters: The required parameters for creating or updating an aad administrator. + Required. :type parameters: ~azure.mgmt.rdbms.mysql_flexibleservers.models.AzureADAdministrator + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + 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 @@ -141,20 +170,99 @@ async def begin_create_or_update( of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql_flexibleservers.models.AzureADAdministrator] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + administrator_name: Union[str, _models.AdministratorName], + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.AzureADAdministrator]: + """Creates or updates an existing Azure Active Directory administrator. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param administrator_name: The name of the Azure AD Administrator. "ActiveDirectory" Required. + :type administrator_name: str or + ~azure.mgmt.rdbms.mysql_flexibleservers.models.AdministratorName + :param parameters: The required parameters for creating or updating an aad administrator. + Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :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 AzureADAdministrator or the result + of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql_flexibleservers.models.AzureADAdministrator] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + administrator_name: Union[str, _models.AdministratorName], + parameters: Union[_models.AzureADAdministrator, IO], + **kwargs: Any + ) -> AsyncLROPoller[_models.AzureADAdministrator]: + """Creates or updates an existing Azure Active Directory administrator. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param administrator_name: The name of the Azure AD Administrator. "ActiveDirectory" Required. + :type administrator_name: str or + ~azure.mgmt.rdbms.mysql_flexibleservers.models.AdministratorName + :param parameters: The required parameters for creating or updating an aad administrator. Is + either a model type or a IO type. Required. + :type parameters: ~azure.mgmt.rdbms.mysql_flexibleservers.models.AzureADAdministrator or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either AzureADAdministrator or the result + of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql_flexibleservers.models.AzureADAdministrator] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[_models.AzureADAdministrator] - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.AzureADAdministrator] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = await self._create_or_update_initial( # type: ignore resource_group_name=resource_group_name, @@ -163,66 +271,64 @@ async def begin_create_or_update( parameters=parameters, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize('AzureADAdministrator', pipeline_response) + deserialized = self._deserialize("AzureADAdministrator", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - if polling is True: - polling_method = cast(AsyncPollingMethod, AsyncARMPolling( - lro_delay, - - - **kwargs - )) # type: AsyncPollingMethod - elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: polling_method = polling + polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_create_or_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/administrators/{administratorName}"} # type: ignore + begin_create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/administrators/{administratorName}"} # type: ignore async def _delete_initial( # pylint: disable=inconsistent-return-statements self, resource_group_name: str, server_name: str, - administrator_name: Union[str, "_models.AdministratorName"], + administrator_name: Union[str, _models.AdministratorName], **kwargs: Any ) -> None: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] - - request = build_delete_request_initial( - subscription_id=self._config.subscription_id, + request = build_delete_request( resource_group_name=resource_group_name, server_name=server_name, administrator_name=administrator_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._delete_initial.metadata['url'], + template_url=self._delete_initial.metadata["url"], headers=_headers, params=_params, ) @@ -230,10 +336,9 @@ async def _delete_initial( # pylint: disable=inconsistent-return-statements request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: @@ -243,24 +348,24 @@ async def _delete_initial( # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - _delete_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/administrators/{administratorName}"} # type: ignore - + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/administrators/{administratorName}"} # type: ignore @distributed_trace_async - async def begin_delete( # pylint: disable=inconsistent-return-statements + async def begin_delete( self, resource_group_name: str, server_name: str, - administrator_name: Union[str, "_models.AdministratorName"], + administrator_name: Union[str, _models.AdministratorName], **kwargs: Any ) -> AsyncLROPoller[None]: """Deletes an Azure AD Administrator. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param administrator_name: The name of the Azure AD Administrator. + :param administrator_name: The name of the Azure AD Administrator. "ActiveDirectory" Required. :type administrator_name: str or ~azure.mgmt.rdbms.mysql_flexibleservers.models.AdministratorName :keyword callable cls: A custom type or function that will be passed the direct response @@ -273,98 +378,96 @@ async def begin_delete( # pylint: disable=inconsistent-return-statements Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = await self._delete_initial( # type: ignore resource_group_name=resource_group_name, server_name=server_name, administrator_name=administrator_name, api_version=api_version, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - if polling is True: - polling_method = cast(AsyncPollingMethod, AsyncARMPolling( - lro_delay, - lro_options={'final-state-via': 'location'}, - - **kwargs - )) # type: AsyncPollingMethod - elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: polling_method = polling + polling_method = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_delete.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/administrators/{administratorName}"} # type: ignore + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/administrators/{administratorName}"} # type: ignore @distributed_trace_async async def get( self, resource_group_name: str, server_name: str, - administrator_name: Union[str, "_models.AdministratorName"], + administrator_name: Union[str, _models.AdministratorName], **kwargs: Any ) -> _models.AzureADAdministrator: """Gets information about an azure ad administrator. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param administrator_name: The name of the Azure AD Administrator. + :param administrator_name: The name of the Azure AD Administrator. "ActiveDirectory" Required. :type administrator_name: str or ~azure.mgmt.rdbms.mysql_flexibleservers.models.AdministratorName :keyword callable cls: A custom type or function that will be passed the direct response - :return: AzureADAdministrator, or the result of cls(response) + :return: AzureADAdministrator or the result of cls(response) :rtype: ~azure.mgmt.rdbms.mysql_flexibleservers.models.AzureADAdministrator - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.AzureADAdministrator] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AzureADAdministrator] - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, administrator_name=administrator_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], headers=_headers, params=_params, ) @@ -372,65 +475,65 @@ async def get( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('AzureADAdministrator', pipeline_response) + deserialized = self._deserialize("AzureADAdministrator", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/administrators/{administratorName}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/administrators/{administratorName}"} # type: ignore @distributed_trace def list_by_server( - self, - resource_group_name: str, - server_name: str, - **kwargs: Any - ) -> AsyncIterable[_models.AdministratorListResult]: + self, resource_group_name: str, server_name: str, **kwargs: Any + ) -> AsyncIterable["_models.AzureADAdministrator"]: """List all the AAD administrators in a given server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either AdministratorListResult or the result of + :return: An iterator like instance of either AzureADAdministrator or the result of cls(response) :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql_flexibleservers.models.AdministratorListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql_flexibleservers.models.AzureADAdministrator] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.AdministratorListResult] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AdministratorListResult] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_server_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_server.metadata['url'], + template_url=self.list_by_server.metadata["url"], headers=_headers, params=_params, ) @@ -438,15 +541,17 @@ def prepare_request(next_link=None): request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_by_server_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - server_name=server_name, - api_version=api_version, - template_url=next_link, - 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() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore @@ -463,10 +568,8 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -476,8 +579,6 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list_by_server.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/administrators"} # type: ignore + list_by_server.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/administrators"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_backups_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_backups_operations.py index 54e6a143f835..29de51690b94 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_backups_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_backups_operations.py @@ -7,9 +7,17 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest @@ -21,9 +29,11 @@ from ... import models as _models from ..._vendor import _convert_request from ...operations._backups_operations import build_get_request, build_list_by_server_request, build_put_request -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class BackupsOperations: """ .. warning:: @@ -43,47 +53,45 @@ def __init__(self, *args, **kwargs) -> None: self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace_async async def put( - self, - resource_group_name: str, - server_name: str, - backup_name: str, - **kwargs: Any + self, resource_group_name: str, server_name: str, backup_name: str, **kwargs: Any ) -> _models.ServerBackup: """Create backup for a given server with specified backup name. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param backup_name: The name of the backup. + :param backup_name: The name of the backup. Required. :type backup_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: ServerBackup, or the result of cls(response) + :return: ServerBackup or the result of cls(response) :rtype: ~azure.mgmt.rdbms.mysql_flexibleservers.models.ServerBackup - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.ServerBackup] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ServerBackup] - request = build_put_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, backup_name=backup_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.put.metadata['url'], + template_url=self.put.metadata["url"], headers=_headers, params=_params, ) @@ -91,66 +99,63 @@ async def put( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('ServerBackup', pipeline_response) + deserialized = self._deserialize("ServerBackup", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - put.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/backups/{backupName}"} # type: ignore - + put.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/backups/{backupName}"} # type: ignore @distributed_trace_async async def get( - self, - resource_group_name: str, - server_name: str, - backup_name: str, - **kwargs: Any + self, resource_group_name: str, server_name: str, backup_name: str, **kwargs: Any ) -> _models.ServerBackup: """List all the backups for a given server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param backup_name: The name of the backup. + :param backup_name: The name of the backup. Required. :type backup_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: ServerBackup, or the result of cls(response) + :return: ServerBackup or the result of cls(response) :rtype: ~azure.mgmt.rdbms.mysql_flexibleservers.models.ServerBackup - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.ServerBackup] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ServerBackup] - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, backup_name=backup_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], headers=_headers, params=_params, ) @@ -158,65 +163,64 @@ async def get( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('ServerBackup', pipeline_response) + deserialized = self._deserialize("ServerBackup", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/backups/{backupName}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/backups/{backupName}"} # type: ignore @distributed_trace def list_by_server( - self, - resource_group_name: str, - server_name: str, - **kwargs: Any - ) -> AsyncIterable[_models.ServerBackupListResult]: + self, resource_group_name: str, server_name: str, **kwargs: Any + ) -> AsyncIterable["_models.ServerBackup"]: """List all the backups for a given server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ServerBackupListResult or the result of - cls(response) + :return: An iterator like instance of either ServerBackup or the result of cls(response) :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql_flexibleservers.models.ServerBackupListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql_flexibleservers.models.ServerBackup] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.ServerBackupListResult] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ServerBackupListResult] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_server_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_server.metadata['url'], + template_url=self.list_by_server.metadata["url"], headers=_headers, params=_params, ) @@ -224,15 +228,17 @@ def prepare_request(next_link=None): request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_by_server_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - server_name=server_name, - api_version=api_version, - template_url=next_link, - 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() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore @@ -249,10 +255,8 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -262,8 +266,6 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list_by_server.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/backups"} # type: ignore + list_by_server.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/backups"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_check_name_availability_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_check_name_availability_operations.py index 3d87a0be3213..03f58147fd25 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_check_name_availability_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_check_name_availability_operations.py @@ -6,9 +6,16 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Optional, TypeVar - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest @@ -19,9 +26,11 @@ from ... import models as _models from ..._vendor import _convert_request from ...operations._check_name_availability_operations import build_execute_request -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class CheckNameAvailabilityOperations: """ .. warning:: @@ -41,48 +50,108 @@ def __init__(self, *args, **kwargs) -> None: self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace_async + @overload async def execute( self, location_name: str, name_availability_request: _models.NameAvailabilityRequest, + *, + content_type: str = "application/json", **kwargs: Any ) -> _models.NameAvailability: """Check the availability of name for server. - :param location_name: The name of the location. + :param location_name: The name of the location. Required. :type location_name: str :param name_availability_request: The required parameters for checking if server name is - available. + available. Required. :type name_availability_request: ~azure.mgmt.rdbms.mysql_flexibleservers.models.NameAvailabilityRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: NameAvailability or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql_flexibleservers.models.NameAvailability + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def execute( + self, + location_name: str, + name_availability_request: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.NameAvailability: + """Check the availability of name for server. + + :param location_name: The name of the location. Required. + :type location_name: str + :param name_availability_request: The required parameters for checking if server name is + available. Required. + :type name_availability_request: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: NameAvailability, or the result of cls(response) + :return: NameAvailability or the result of cls(response) :rtype: ~azure.mgmt.rdbms.mysql_flexibleservers.models.NameAvailability - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def execute( + self, location_name: str, name_availability_request: Union[_models.NameAvailabilityRequest, IO], **kwargs: Any + ) -> _models.NameAvailability: + """Check the availability of name for server. + + :param location_name: The name of the location. Required. + :type location_name: str + :param name_availability_request: The required parameters for checking if server name is + available. Is either a model type or a IO type. Required. + :type name_availability_request: + ~azure.mgmt.rdbms.mysql_flexibleservers.models.NameAvailabilityRequest or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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: NameAvailability or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql_flexibleservers.models.NameAvailability + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[_models.NameAvailability] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.NameAvailability] - _json = self._serialize.body(name_availability_request, 'NameAvailabilityRequest') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(name_availability_request, (IO, bytes)): + _content = name_availability_request + else: + _json = self._serialize.body(name_availability_request, "NameAvailabilityRequest") request = build_execute_request( - subscription_id=self._config.subscription_id, location_name=location_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self.execute.metadata['url'], + content=_content, + template_url=self.execute.metadata["url"], headers=_headers, params=_params, ) @@ -90,22 +159,20 @@ async def execute( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('NameAvailability', pipeline_response) + deserialized = self._deserialize("NameAvailability", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - execute.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/locations/{locationName}/checkNameAvailability"} # type: ignore - + execute.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/locations/{locationName}/checkNameAvailability"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_check_name_availability_without_location_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_check_name_availability_without_location_operations.py index f7899ed3de4f..d6adec8227a0 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_check_name_availability_without_location_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_check_name_availability_without_location_operations.py @@ -6,9 +6,16 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Optional, TypeVar - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest @@ -19,9 +26,11 @@ from ... import models as _models from ..._vendor import _convert_request from ...operations._check_name_availability_without_location_operations import build_execute_request -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class CheckNameAvailabilityWithoutLocationOperations: """ .. warning:: @@ -41,44 +50,95 @@ def __init__(self, *args, **kwargs) -> None: self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace_async + @overload async def execute( self, name_availability_request: _models.NameAvailabilityRequest, + *, + content_type: str = "application/json", **kwargs: Any ) -> _models.NameAvailability: """Check the availability of name for server. :param name_availability_request: The required parameters for checking if server name is - available. + available. Required. :type name_availability_request: ~azure.mgmt.rdbms.mysql_flexibleservers.models.NameAvailabilityRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: NameAvailability or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql_flexibleservers.models.NameAvailability + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def execute( + self, name_availability_request: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.NameAvailability: + """Check the availability of name for server. + + :param name_availability_request: The required parameters for checking if server name is + available. Required. + :type name_availability_request: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: NameAvailability, or the result of cls(response) + :return: NameAvailability or the result of cls(response) :rtype: ~azure.mgmt.rdbms.mysql_flexibleservers.models.NameAvailability - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def execute( + self, name_availability_request: Union[_models.NameAvailabilityRequest, IO], **kwargs: Any + ) -> _models.NameAvailability: + """Check the availability of name for server. + + :param name_availability_request: The required parameters for checking if server name is + available. Is either a model type or a IO type. Required. + :type name_availability_request: + ~azure.mgmt.rdbms.mysql_flexibleservers.models.NameAvailabilityRequest or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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: NameAvailability or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql_flexibleservers.models.NameAvailability + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[_models.NameAvailability] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.NameAvailability] - _json = self._serialize.body(name_availability_request, 'NameAvailabilityRequest') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(name_availability_request, (IO, bytes)): + _content = name_availability_request + else: + _json = self._serialize.body(name_availability_request, "NameAvailabilityRequest") request = build_execute_request( subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self.execute.metadata['url'], + content=_content, + template_url=self.execute.metadata["url"], headers=_headers, params=_params, ) @@ -86,22 +146,20 @@ async def execute( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('NameAvailability', pipeline_response) + deserialized = self._deserialize("NameAvailability", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - execute.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/checkNameAvailability"} # type: ignore - + execute.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/checkNameAvailability"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_check_virtual_network_subnet_usage_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_check_virtual_network_subnet_usage_operations.py index a6e4d27f5efd..00b24d63af9f 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_check_virtual_network_subnet_usage_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_check_virtual_network_subnet_usage_operations.py @@ -6,9 +6,16 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Optional, TypeVar - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest @@ -19,9 +26,11 @@ from ... import models as _models from ..._vendor import _convert_request from ...operations._check_virtual_network_subnet_usage_operations import build_execute_request -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class CheckVirtualNetworkSubnetUsageOperations: """ .. warning:: @@ -41,47 +50,101 @@ def __init__(self, *args, **kwargs) -> None: self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace_async + @overload async def execute( self, location_name: str, parameters: _models.VirtualNetworkSubnetUsageParameter, + *, + content_type: str = "application/json", **kwargs: Any ) -> _models.VirtualNetworkSubnetUsageResult: """Get virtual network subnet usage for a given vNet resource id. - :param location_name: The name of the location. + :param location_name: The name of the location. Required. :type location_name: str - :param parameters: The required parameters for creating or updating a server. + :param parameters: The required parameters for creating or updating a server. Required. :type parameters: ~azure.mgmt.rdbms.mysql_flexibleservers.models.VirtualNetworkSubnetUsageParameter + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: VirtualNetworkSubnetUsageResult, or the result of cls(response) + :return: VirtualNetworkSubnetUsageResult or the result of cls(response) :rtype: ~azure.mgmt.rdbms.mysql_flexibleservers.models.VirtualNetworkSubnetUsageResult - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def execute( + self, location_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.VirtualNetworkSubnetUsageResult: + """Get virtual network subnet usage for a given vNet resource id. + + :param location_name: The name of the location. Required. + :type location_name: str + :param parameters: The required parameters for creating or updating a server. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: VirtualNetworkSubnetUsageResult or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql_flexibleservers.models.VirtualNetworkSubnetUsageResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def execute( + self, location_name: str, parameters: Union[_models.VirtualNetworkSubnetUsageParameter, IO], **kwargs: Any + ) -> _models.VirtualNetworkSubnetUsageResult: + """Get virtual network subnet usage for a given vNet resource id. + + :param location_name: The name of the location. Required. + :type location_name: str + :param parameters: The required parameters for creating or updating a server. Is either a model + type or a IO type. Required. + :type parameters: + ~azure.mgmt.rdbms.mysql_flexibleservers.models.VirtualNetworkSubnetUsageParameter or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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: VirtualNetworkSubnetUsageResult or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql_flexibleservers.models.VirtualNetworkSubnetUsageResult + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[_models.VirtualNetworkSubnetUsageResult] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.VirtualNetworkSubnetUsageResult] - _json = self._serialize.body(parameters, 'VirtualNetworkSubnetUsageParameter') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "VirtualNetworkSubnetUsageParameter") request = build_execute_request( - subscription_id=self._config.subscription_id, location_name=location_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self.execute.metadata['url'], + content=_content, + template_url=self.execute.metadata["url"], headers=_headers, params=_params, ) @@ -89,22 +152,20 @@ async def execute( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('VirtualNetworkSubnetUsageResult', pipeline_response) + deserialized = self._deserialize("VirtualNetworkSubnetUsageResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - execute.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/locations/{locationName}/checkVirtualNetworkSubnetUsage"} # type: ignore - + execute.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/locations/{locationName}/checkVirtualNetworkSubnetUsage"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_configurations_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_configurations_operations.py index d6d22ac46205..b72acae43438 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_configurations_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_configurations_operations.py @@ -6,10 +6,18 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar, Union, cast +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod @@ -22,10 +30,17 @@ from ... import models as _models from ..._vendor import _convert_request -from ...operations._configurations_operations import build_batch_update_request_initial, build_get_request, build_list_by_server_request, build_update_request_initial -T = TypeVar('T') +from ...operations._configurations_operations import ( + build_batch_update_request, + build_get_request, + build_list_by_server_request, + build_update_request, +) + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class ConfigurationsOperations: """ .. warning:: @@ -45,38 +60,47 @@ def __init__(self, *args, **kwargs) -> None: 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") - async def _update_initial( self, resource_group_name: str, server_name: str, configuration_name: str, - parameters: _models.Configuration, + parameters: Union[_models.Configuration, IO], **kwargs: Any ) -> Optional[_models.Configuration]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[Optional[_models.Configuration]] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.Configuration]] - _json = self._serialize.body(parameters, 'Configuration') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Configuration") - request = build_update_request_initial( - subscription_id=self._config.subscription_id, + request = build_update_request( resource_group_name=resource_group_name, server_name=server_name, configuration_name=configuration_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._update_initial.metadata['url'], + content=_content, + template_url=self._update_initial.metadata["url"], headers=_headers, params=_params, ) @@ -84,10 +108,9 @@ async def _update_initial( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202]: @@ -96,35 +119,119 @@ async def _update_initial( deserialized = None if response.status_code == 200: - deserialized = self._deserialize('Configuration', pipeline_response) + deserialized = self._deserialize("Configuration", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/configurations/{configurationName}"} # type: ignore - + _update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/configurations/{configurationName}"} # type: ignore - @distributed_trace_async + @overload async def begin_update( self, resource_group_name: str, server_name: str, configuration_name: str, parameters: _models.Configuration, + *, + content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.Configuration]: """Updates a configuration of a server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param configuration_name: The name of the server configuration. + :param configuration_name: The name of the server configuration. Required. :type configuration_name: str - :param parameters: The required parameters for updating a server configuration. + :param parameters: The required parameters for updating a server configuration. Required. :type parameters: ~azure.mgmt.rdbms.mysql_flexibleservers.models.Configuration + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + 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 Configuration or the result of + cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql_flexibleservers.models.Configuration] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_update( + self, + resource_group_name: str, + server_name: str, + configuration_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.Configuration]: + """Updates a configuration of a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param configuration_name: The name of the server configuration. Required. + :type configuration_name: str + :param parameters: The required parameters for updating a server configuration. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :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 Configuration or the result of + cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql_flexibleservers.models.Configuration] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_update( + self, + resource_group_name: str, + server_name: str, + configuration_name: str, + parameters: Union[_models.Configuration, IO], + **kwargs: Any + ) -> AsyncLROPoller[_models.Configuration]: + """Updates a configuration of a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param configuration_name: The name of the server configuration. Required. + :type configuration_name: str + :param parameters: The required parameters for updating a server configuration. Is either a + model type or a IO type. Required. + :type parameters: ~azure.mgmt.rdbms.mysql_flexibleservers.models.Configuration or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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 @@ -137,20 +244,17 @@ async def begin_update( cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql_flexibleservers.models.Configuration] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[_models.Configuration] - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Configuration] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = await self._update_initial( # type: ignore resource_group_name=resource_group_name, @@ -159,80 +263,75 @@ async def begin_update( parameters=parameters, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize('Configuration', pipeline_response) + deserialized = self._deserialize("Configuration", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - if polling is True: - polling_method = cast(AsyncPollingMethod, AsyncARMPolling( - lro_delay, - - - **kwargs - )) # type: AsyncPollingMethod - elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: polling_method = polling + polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/configurations/{configurationName}"} # type: ignore + begin_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/configurations/{configurationName}"} # type: ignore @distributed_trace_async async def get( - self, - resource_group_name: str, - server_name: str, - configuration_name: str, - **kwargs: Any + self, resource_group_name: str, server_name: str, configuration_name: str, **kwargs: Any ) -> _models.Configuration: """Gets information about a configuration of server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param configuration_name: The name of the server configuration. + :param configuration_name: The name of the server configuration. Required. :type configuration_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Configuration, or the result of cls(response) + :return: Configuration or the result of cls(response) :rtype: ~azure.mgmt.rdbms.mysql_flexibleservers.models.Configuration - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.Configuration] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.Configuration] - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, configuration_name=configuration_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], headers=_headers, params=_params, ) @@ -240,55 +339,63 @@ async def get( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('Configuration', pipeline_response) + deserialized = self._deserialize("Configuration", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/configurations/{configurationName}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/configurations/{configurationName}"} # type: ignore async def _batch_update_initial( self, resource_group_name: str, server_name: str, - parameters: _models.ConfigurationListForBatchUpdate, + parameters: Union[_models.ConfigurationListForBatchUpdate, IO], **kwargs: Any ) -> Optional[_models.ConfigurationListResult]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[Optional[_models.ConfigurationListResult]] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.ConfigurationListResult]] - _json = self._serialize.body(parameters, 'ConfigurationListForBatchUpdate') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ConfigurationListForBatchUpdate") - request = build_batch_update_request_initial( - subscription_id=self._config.subscription_id, + request = build_batch_update_request( resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._batch_update_initial.metadata['url'], + content=_content, + template_url=self._batch_update_initial.metadata["url"], headers=_headers, params=_params, ) @@ -296,10 +403,9 @@ async def _batch_update_initial( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202]: @@ -308,33 +414,75 @@ async def _batch_update_initial( deserialized = None if response.status_code == 200: - deserialized = self._deserialize('ConfigurationListResult', pipeline_response) + deserialized = self._deserialize("ConfigurationListResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _batch_update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/updateConfigurations"} # type: ignore + _batch_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/updateConfigurations"} # type: ignore - - @distributed_trace_async + @overload async def begin_batch_update( self, resource_group_name: str, server_name: str, parameters: _models.ConfigurationListForBatchUpdate, + *, + content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.ConfigurationListResult]: """Update a list of configurations in a given server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param parameters: The parameters for updating a list of server configuration. + :param parameters: The parameters for updating a list of server configuration. Required. :type parameters: ~azure.mgmt.rdbms.mysql_flexibleservers.models.ConfigurationListForBatchUpdate + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + 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 ConfigurationListResult or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql_flexibleservers.models.ConfigurationListResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_batch_update( + self, + resource_group_name: str, + server_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.ConfigurationListResult]: + """Update a list of configurations in a given server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param parameters: The parameters for updating a list of server configuration. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :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 @@ -347,20 +495,54 @@ async def begin_batch_update( result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql_flexibleservers.models.ConfigurationListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_batch_update( + self, + resource_group_name: str, + server_name: str, + parameters: Union[_models.ConfigurationListForBatchUpdate, IO], + **kwargs: Any + ) -> AsyncLROPoller[_models.ConfigurationListResult]: + """Update a list of configurations in a given server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param parameters: The parameters for updating a list of server configuration. Is either a + model type or a IO type. Required. + :type parameters: + ~azure.mgmt.rdbms.mysql_flexibleservers.models.ConfigurationListForBatchUpdate or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either ConfigurationListResult or the + result of cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql_flexibleservers.models.ConfigurationListResult] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[_models.ConfigurationListResult] - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ConfigurationListResult] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = await self._batch_update_initial( # type: ignore resource_group_name=resource_group_name, @@ -368,39 +550,38 @@ async def begin_batch_update( parameters=parameters, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize('ConfigurationListResult', pipeline_response) + deserialized = self._deserialize("ConfigurationListResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - if polling is True: - polling_method = cast(AsyncPollingMethod, AsyncARMPolling( - lro_delay, - lro_options={'final-state-via': 'azure-async-operation'}, - - **kwargs - )) # type: AsyncPollingMethod - elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: polling_method = polling + polling_method = cast( + AsyncPollingMethod, + AsyncARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs), + ) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_batch_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/updateConfigurations"} # type: ignore + begin_batch_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/updateConfigurations"} # type: ignore @distributed_trace def list_by_server( @@ -412,12 +593,13 @@ def list_by_server( page: Optional[int] = None, page_size: Optional[int] = None, **kwargs: Any - ) -> AsyncIterable[_models.ConfigurationListResult]: + ) -> AsyncIterable["_models.Configuration"]: """List all the configurations in a given server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str :param tags: The tags of the server configuration. Default value is None. :type tags: str @@ -428,35 +610,38 @@ def list_by_server( :param page_size: The pageSize of the server configuration. Default value is None. :type page_size: int :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ConfigurationListResult or the result of - cls(response) + :return: An iterator like instance of either Configuration or the result of cls(response) :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql_flexibleservers.models.ConfigurationListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql_flexibleservers.models.Configuration] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.ConfigurationListResult] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ConfigurationListResult] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_server_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, - api_version=api_version, + subscription_id=self._config.subscription_id, tags=tags, keyword=keyword, page=page, page_size=page_size, - template_url=self.list_by_server.metadata['url'], + api_version=api_version, + template_url=self.list_by_server.metadata["url"], headers=_headers, params=_params, ) @@ -464,19 +649,17 @@ def prepare_request(next_link=None): request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_by_server_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - server_name=server_name, - api_version=api_version, - tags=tags, - keyword=keyword, - page=page, - page_size=page_size, - template_url=next_link, - 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() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore @@ -493,10 +676,8 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -506,8 +687,6 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list_by_server.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/configurations"} # type: ignore + list_by_server.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/configurations"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_databases_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_databases_operations.py index 212ac94f2ffb..4851b19e1f74 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_databases_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_databases_operations.py @@ -6,10 +6,18 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar, Union, cast +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod @@ -22,10 +30,17 @@ from ... import models as _models from ..._vendor import _convert_request -from ...operations._databases_operations import build_create_or_update_request_initial, build_delete_request_initial, build_get_request, build_list_by_server_request -T = TypeVar('T') +from ...operations._databases_operations import ( + build_create_or_update_request, + build_delete_request, + build_get_request, + build_list_by_server_request, +) + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class DatabasesOperations: """ .. warning:: @@ -45,38 +60,47 @@ def __init__(self, *args, **kwargs) -> None: 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") - async def _create_or_update_initial( self, resource_group_name: str, server_name: str, database_name: str, - parameters: _models.Database, + parameters: Union[_models.Database, IO], **kwargs: Any ) -> Optional[_models.Database]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[Optional[_models.Database]] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.Database]] - _json = self._serialize.body(parameters, 'Database') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Database") - request = build_create_or_update_request_initial( - subscription_id=self._config.subscription_id, + request = build_create_or_update_request( resource_group_name=resource_group_name, server_name=server_name, database_name=database_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._create_or_update_initial.metadata['url'], + content=_content, + template_url=self._create_or_update_initial.metadata["url"], headers=_headers, params=_params, ) @@ -84,10 +108,9 @@ async def _create_or_update_initial( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 201, 202]: @@ -96,38 +119,83 @@ async def _create_or_update_initial( deserialized = None if response.status_code == 200: - deserialized = self._deserialize('Database', pipeline_response) + deserialized = self._deserialize("Database", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('Database', pipeline_response) + deserialized = self._deserialize("Database", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _create_or_update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/databases/{databaseName}"} # type: ignore - + _create_or_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/databases/{databaseName}"} # type: ignore - @distributed_trace_async + @overload async def begin_create_or_update( self, resource_group_name: str, server_name: str, database_name: str, parameters: _models.Database, + *, + content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.Database]: """Creates a new database or updates an existing database. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param database_name: The name of the database. + :param database_name: The name of the database. Required. :type database_name: str - :param parameters: The required parameters for creating or updating a database. + :param parameters: The required parameters for creating or updating a database. Required. :type parameters: ~azure.mgmt.rdbms.mysql_flexibleservers.models.Database + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + 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 Database or the result of + cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql_flexibleservers.models.Database] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + database_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.Database]: + """Creates a new database or updates an existing database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param database_name: The name of the database. Required. + :type database_name: str + :param parameters: The required parameters for creating or updating a database. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :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 @@ -140,20 +208,56 @@ async def begin_create_or_update( cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql_flexibleservers.models.Database] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + database_name: str, + parameters: Union[_models.Database, IO], + **kwargs: Any + ) -> AsyncLROPoller[_models.Database]: + """Creates a new database or updates an existing database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param database_name: The name of the database. Required. + :type database_name: str + :param parameters: The required parameters for creating or updating a database. Is either a + model type or a IO type. Required. + :type parameters: ~azure.mgmt.rdbms.mysql_flexibleservers.models.Database or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either Database or the result of + cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql_flexibleservers.models.Database] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[_models.Database] - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Database] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = await self._create_or_update_initial( # type: ignore resource_group_name=resource_group_name, @@ -162,66 +266,60 @@ async def begin_create_or_update( parameters=parameters, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize('Database', pipeline_response) + deserialized = self._deserialize("Database", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - if polling is True: - polling_method = cast(AsyncPollingMethod, AsyncARMPolling( - lro_delay, - - - **kwargs - )) # type: AsyncPollingMethod - elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: polling_method = polling + polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_create_or_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/databases/{databaseName}"} # type: ignore + begin_create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/databases/{databaseName}"} # type: ignore async def _delete_initial( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - server_name: str, - database_name: str, - **kwargs: Any + self, resource_group_name: str, server_name: str, database_name: str, **kwargs: Any ) -> None: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] - - request = build_delete_request_initial( - subscription_id=self._config.subscription_id, + request = build_delete_request( resource_group_name=resource_group_name, server_name=server_name, database_name=database_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._delete_initial.metadata['url'], + template_url=self._delete_initial.metadata["url"], headers=_headers, params=_params, ) @@ -229,10 +327,9 @@ async def _delete_initial( # pylint: disable=inconsistent-return-statements request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: @@ -242,24 +339,20 @@ async def _delete_initial( # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - _delete_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/databases/{databaseName}"} # type: ignore - + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/databases/{databaseName}"} # type: ignore @distributed_trace_async - async def begin_delete( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - server_name: str, - database_name: str, - **kwargs: Any + async def begin_delete( + self, resource_group_name: str, server_name: str, database_name: str, **kwargs: Any ) -> AsyncLROPoller[None]: """Deletes a database. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param database_name: The name of the database. + :param database_name: The name of the database. Required. :type database_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. @@ -271,97 +364,89 @@ async def begin_delete( # pylint: disable=inconsistent-return-statements Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = await self._delete_initial( # type: ignore resource_group_name=resource_group_name, server_name=server_name, database_name=database_name, api_version=api_version, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - if polling is True: - polling_method = cast(AsyncPollingMethod, AsyncARMPolling( - lro_delay, - - - **kwargs - )) # type: AsyncPollingMethod - elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: polling_method = polling + polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_delete.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/databases/{databaseName}"} # type: ignore + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/databases/{databaseName}"} # type: ignore @distributed_trace_async async def get( - self, - resource_group_name: str, - server_name: str, - database_name: str, - **kwargs: Any + self, resource_group_name: str, server_name: str, database_name: str, **kwargs: Any ) -> _models.Database: """Gets information about a database. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param database_name: The name of the database. + :param database_name: The name of the database. Required. :type database_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Database, or the result of cls(response) + :return: Database or the result of cls(response) :rtype: ~azure.mgmt.rdbms.mysql_flexibleservers.models.Database - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.Database] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.Database] - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, database_name=database_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], headers=_headers, params=_params, ) @@ -369,64 +454,64 @@ async def get( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('Database', pipeline_response) + deserialized = self._deserialize("Database", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/databases/{databaseName}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/databases/{databaseName}"} # type: ignore @distributed_trace def list_by_server( - self, - resource_group_name: str, - server_name: str, - **kwargs: Any - ) -> AsyncIterable[_models.DatabaseListResult]: + self, resource_group_name: str, server_name: str, **kwargs: Any + ) -> AsyncIterable["_models.Database"]: """List all the databases in a given server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either DatabaseListResult or the result of cls(response) + :return: An iterator like instance of either Database or the result of cls(response) :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql_flexibleservers.models.DatabaseListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql_flexibleservers.models.Database] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.DatabaseListResult] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.DatabaseListResult] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_server_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_server.metadata['url'], + template_url=self.list_by_server.metadata["url"], headers=_headers, params=_params, ) @@ -434,15 +519,17 @@ def prepare_request(next_link=None): request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_by_server_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - server_name=server_name, - api_version=api_version, - template_url=next_link, - 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() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore @@ -459,10 +546,8 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -472,8 +557,6 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list_by_server.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/databases"} # type: ignore + list_by_server.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/databases"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_firewall_rules_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_firewall_rules_operations.py index f678cb16fa6d..6acd74ab48da 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_firewall_rules_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_firewall_rules_operations.py @@ -6,10 +6,18 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar, Union, cast +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod @@ -22,10 +30,17 @@ from ... import models as _models from ..._vendor import _convert_request -from ...operations._firewall_rules_operations import build_create_or_update_request_initial, build_delete_request_initial, build_get_request, build_list_by_server_request -T = TypeVar('T') +from ...operations._firewall_rules_operations import ( + build_create_or_update_request, + build_delete_request, + build_get_request, + build_list_by_server_request, +) + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class FirewallRulesOperations: """ .. warning:: @@ -45,38 +60,47 @@ def __init__(self, *args, **kwargs) -> None: 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") - async def _create_or_update_initial( self, resource_group_name: str, server_name: str, firewall_rule_name: str, - parameters: _models.FirewallRule, + parameters: Union[_models.FirewallRule, IO], **kwargs: Any ) -> Optional[_models.FirewallRule]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[Optional[_models.FirewallRule]] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.FirewallRule]] - _json = self._serialize.body(parameters, 'FirewallRule') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "FirewallRule") - request = build_create_or_update_request_initial( - subscription_id=self._config.subscription_id, + request = build_create_or_update_request( resource_group_name=resource_group_name, server_name=server_name, firewall_rule_name=firewall_rule_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._create_or_update_initial.metadata['url'], + content=_content, + template_url=self._create_or_update_initial.metadata["url"], headers=_headers, params=_params, ) @@ -84,10 +108,9 @@ async def _create_or_update_initial( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 201, 202]: @@ -96,38 +119,122 @@ async def _create_or_update_initial( deserialized = None if response.status_code == 200: - deserialized = self._deserialize('FirewallRule', pipeline_response) + deserialized = self._deserialize("FirewallRule", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('FirewallRule', pipeline_response) + deserialized = self._deserialize("FirewallRule", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _create_or_update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/firewallRules/{firewallRuleName}"} # type: ignore - + _create_or_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/firewallRules/{firewallRuleName}"} # type: ignore - @distributed_trace_async + @overload async def begin_create_or_update( self, resource_group_name: str, server_name: str, firewall_rule_name: str, parameters: _models.FirewallRule, + *, + content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.FirewallRule]: """Creates a new firewall rule or updates an existing firewall rule. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param firewall_rule_name: The name of the server firewall rule. + :param firewall_rule_name: The name of the server firewall rule. Required. :type firewall_rule_name: str - :param parameters: The required parameters for creating or updating a firewall rule. + :param parameters: The required parameters for creating or updating a firewall rule. Required. :type parameters: ~azure.mgmt.rdbms.mysql_flexibleservers.models.FirewallRule + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + 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 FirewallRule or the result of + cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql_flexibleservers.models.FirewallRule] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + firewall_rule_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.FirewallRule]: + """Creates a new firewall rule or updates an existing firewall rule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param firewall_rule_name: The name of the server firewall rule. Required. + :type firewall_rule_name: str + :param parameters: The required parameters for creating or updating a firewall rule. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :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 FirewallRule or the result of + cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql_flexibleservers.models.FirewallRule] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + firewall_rule_name: str, + parameters: Union[_models.FirewallRule, IO], + **kwargs: Any + ) -> AsyncLROPoller[_models.FirewallRule]: + """Creates a new firewall rule or updates an existing firewall rule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param firewall_rule_name: The name of the server firewall rule. Required. + :type firewall_rule_name: str + :param parameters: The required parameters for creating or updating a firewall rule. Is either + a model type or a IO type. Required. + :type parameters: ~azure.mgmt.rdbms.mysql_flexibleservers.models.FirewallRule or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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 @@ -140,20 +247,17 @@ async def begin_create_or_update( cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql_flexibleservers.models.FirewallRule] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[_models.FirewallRule] - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.FirewallRule] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = await self._create_or_update_initial( # type: ignore resource_group_name=resource_group_name, @@ -162,66 +266,60 @@ async def begin_create_or_update( parameters=parameters, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize('FirewallRule', pipeline_response) + deserialized = self._deserialize("FirewallRule", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - if polling is True: - polling_method = cast(AsyncPollingMethod, AsyncARMPolling( - lro_delay, - - - **kwargs - )) # type: AsyncPollingMethod - elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: polling_method = polling + polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_create_or_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/firewallRules/{firewallRuleName}"} # type: ignore + begin_create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/firewallRules/{firewallRuleName}"} # type: ignore async def _delete_initial( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - server_name: str, - firewall_rule_name: str, - **kwargs: Any + self, resource_group_name: str, server_name: str, firewall_rule_name: str, **kwargs: Any ) -> None: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] - - request = build_delete_request_initial( - subscription_id=self._config.subscription_id, + request = build_delete_request( resource_group_name=resource_group_name, server_name=server_name, firewall_rule_name=firewall_rule_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._delete_initial.metadata['url'], + template_url=self._delete_initial.metadata["url"], headers=_headers, params=_params, ) @@ -229,10 +327,9 @@ async def _delete_initial( # pylint: disable=inconsistent-return-statements request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: @@ -242,24 +339,20 @@ async def _delete_initial( # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - _delete_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/firewallRules/{firewallRuleName}"} # type: ignore - + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/firewallRules/{firewallRuleName}"} # type: ignore @distributed_trace_async - async def begin_delete( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - server_name: str, - firewall_rule_name: str, - **kwargs: Any + async def begin_delete( + self, resource_group_name: str, server_name: str, firewall_rule_name: str, **kwargs: Any ) -> AsyncLROPoller[None]: """Deletes a firewall rule. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param firewall_rule_name: The name of the server firewall rule. + :param firewall_rule_name: The name of the server firewall rule. Required. :type firewall_rule_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. @@ -271,97 +364,89 @@ async def begin_delete( # pylint: disable=inconsistent-return-statements Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = await self._delete_initial( # type: ignore resource_group_name=resource_group_name, server_name=server_name, firewall_rule_name=firewall_rule_name, api_version=api_version, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - if polling is True: - polling_method = cast(AsyncPollingMethod, AsyncARMPolling( - lro_delay, - - - **kwargs - )) # type: AsyncPollingMethod - elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: polling_method = polling + polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_delete.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/firewallRules/{firewallRuleName}"} # type: ignore + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/firewallRules/{firewallRuleName}"} # type: ignore @distributed_trace_async async def get( - self, - resource_group_name: str, - server_name: str, - firewall_rule_name: str, - **kwargs: Any + self, resource_group_name: str, server_name: str, firewall_rule_name: str, **kwargs: Any ) -> _models.FirewallRule: """Gets information about a server firewall rule. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param firewall_rule_name: The name of the server firewall rule. + :param firewall_rule_name: The name of the server firewall rule. Required. :type firewall_rule_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: FirewallRule, or the result of cls(response) + :return: FirewallRule or the result of cls(response) :rtype: ~azure.mgmt.rdbms.mysql_flexibleservers.models.FirewallRule - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.FirewallRule] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.FirewallRule] - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, firewall_rule_name=firewall_rule_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], headers=_headers, params=_params, ) @@ -369,65 +454,64 @@ async def get( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('FirewallRule', pipeline_response) + deserialized = self._deserialize("FirewallRule", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/firewallRules/{firewallRuleName}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/firewallRules/{firewallRuleName}"} # type: ignore @distributed_trace def list_by_server( - self, - resource_group_name: str, - server_name: str, - **kwargs: Any - ) -> AsyncIterable[_models.FirewallRuleListResult]: + self, resource_group_name: str, server_name: str, **kwargs: Any + ) -> AsyncIterable["_models.FirewallRule"]: """List all the firewall rules in a given server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either FirewallRuleListResult or the result of - cls(response) + :return: An iterator like instance of either FirewallRule or the result of cls(response) :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql_flexibleservers.models.FirewallRuleListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql_flexibleservers.models.FirewallRule] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.FirewallRuleListResult] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.FirewallRuleListResult] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_server_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_server.metadata['url'], + template_url=self.list_by_server.metadata["url"], headers=_headers, params=_params, ) @@ -435,15 +519,17 @@ def prepare_request(next_link=None): request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_by_server_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - server_name=server_name, - api_version=api_version, - template_url=next_link, - 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() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore @@ -460,10 +546,8 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -473,8 +557,6 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list_by_server.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/firewallRules"} # type: ignore + list_by_server.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/firewallRules"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_get_private_dns_zone_suffix_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_get_private_dns_zone_suffix_operations.py index e36735b8e3a3..1d9de61a3e84 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_get_private_dns_zone_suffix_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_get_private_dns_zone_suffix_operations.py @@ -8,7 +8,14 @@ # -------------------------------------------------------------------------- from typing import Any, Callable, Dict, Optional, TypeVar -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest @@ -19,9 +26,11 @@ from ... import models as _models from ..._vendor import _convert_request from ...operations._get_private_dns_zone_suffix_operations import build_execute_request -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class GetPrivateDnsZoneSuffixOperations: """ .. warning:: @@ -41,34 +50,32 @@ def __init__(self, *args, **kwargs) -> None: self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace_async - async def execute( - self, - **kwargs: Any - ) -> _models.GetPrivateDnsZoneSuffixResponse: + async def execute(self, **kwargs: Any) -> _models.GetPrivateDnsZoneSuffixResponse: """Get private DNS zone suffix in the cloud. :keyword callable cls: A custom type or function that will be passed the direct response - :return: GetPrivateDnsZoneSuffixResponse, or the result of cls(response) + :return: GetPrivateDnsZoneSuffixResponse or the result of cls(response) :rtype: ~azure.mgmt.rdbms.mysql_flexibleservers.models.GetPrivateDnsZoneSuffixResponse - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.GetPrivateDnsZoneSuffixResponse] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.GetPrivateDnsZoneSuffixResponse] - request = build_execute_request( api_version=api_version, - template_url=self.execute.metadata['url'], + template_url=self.execute.metadata["url"], headers=_headers, params=_params, ) @@ -76,22 +83,20 @@ async def execute( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('GetPrivateDnsZoneSuffixResponse', pipeline_response) + deserialized = self._deserialize("GetPrivateDnsZoneSuffixResponse", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - execute.metadata = {'url': "/providers/Microsoft.DBforMySQL/getPrivateDnsZoneSuffix"} # type: ignore - + execute.metadata = {"url": "/providers/Microsoft.DBforMySQL/getPrivateDnsZoneSuffix"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_location_based_capabilities_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_location_based_capabilities_operations.py index abd5639d05ac..0e1a12b84945 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_location_based_capabilities_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_location_based_capabilities_operations.py @@ -7,9 +7,17 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest @@ -20,9 +28,11 @@ from ... import models as _models from ..._vendor import _convert_request from ...operations._location_based_capabilities_operations import build_list_request -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class LocationBasedCapabilitiesOperations: """ .. warning:: @@ -42,42 +52,41 @@ def __init__(self, *args, **kwargs) -> None: self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace - def list( - self, - location_name: str, - **kwargs: Any - ) -> AsyncIterable[_models.CapabilitiesListResult]: + def list(self, location_name: str, **kwargs: Any) -> AsyncIterable["_models.CapabilityProperties"]: """Get capabilities at specified location in a given subscription. - :param location_name: The name of the location. + :param location_name: The name of the location. Required. :type location_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either CapabilitiesListResult or the result of + :return: An iterator like instance of either CapabilityProperties or the result of cls(response) :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql_flexibleservers.models.CapabilitiesListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql_flexibleservers.models.CapabilityProperties] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.CapabilitiesListResult] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.CapabilitiesListResult] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( - subscription_id=self._config.subscription_id, location_name=location_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list.metadata['url'], + template_url=self.list.metadata["url"], headers=_headers, params=_params, ) @@ -85,14 +94,17 @@ def prepare_request(next_link=None): request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_request( - subscription_id=self._config.subscription_id, - location_name=location_name, - api_version=api_version, - template_url=next_link, - 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() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore @@ -109,10 +121,8 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -122,8 +132,6 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/locations/{locationName}/capabilities"} # type: ignore + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/locations/{locationName}/capabilities"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_log_files_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_log_files_operations.py index 223aa80553e4..079546b36dfc 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_log_files_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_log_files_operations.py @@ -7,9 +7,17 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest @@ -20,9 +28,11 @@ from ... import models as _models from ..._vendor import _convert_request from ...operations._log_files_operations import build_list_by_server_request -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class LogFilesOperations: """ .. warning:: @@ -42,45 +52,46 @@ def __init__(self, *args, **kwargs) -> None: self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace def list_by_server( - self, - resource_group_name: str, - server_name: str, - **kwargs: Any - ) -> AsyncIterable[_models.LogFileListResult]: + self, resource_group_name: str, server_name: str, **kwargs: Any + ) -> AsyncIterable["_models.LogFile"]: """List all the server log files in a given server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either LogFileListResult or the result of cls(response) + :return: An iterator like instance of either LogFile or the result of cls(response) :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql_flexibleservers.models.LogFileListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql_flexibleservers.models.LogFile] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.LogFileListResult] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.LogFileListResult] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_server_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_server.metadata['url'], + template_url=self.list_by_server.metadata["url"], headers=_headers, params=_params, ) @@ -88,15 +99,17 @@ def prepare_request(next_link=None): request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_by_server_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - server_name=server_name, - api_version=api_version, - template_url=next_link, - 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() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore @@ -113,10 +126,8 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -126,8 +137,6 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list_by_server.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/logFiles"} # type: ignore + list_by_server.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/logFiles"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_operations.py index e47aa9e4108e..8ce3d7d0c56e 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_operations.py @@ -7,9 +7,17 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest @@ -20,9 +28,11 @@ from ... import models as _models from ..._vendor import _convert_request from ...operations._operations import build_list_request -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class Operations: """ .. warning:: @@ -42,36 +52,36 @@ def __init__(self, *args, **kwargs) -> None: self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace - def list( - self, - **kwargs: Any - ) -> AsyncIterable[_models.OperationListResult]: + def list(self, **kwargs: Any) -> AsyncIterable["_models.Operation"]: """Lists all of the available REST API operations. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either OperationListResult or the result of cls(response) + :return: An iterator like instance of either Operation or the result of cls(response) :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql_flexibleservers.models.OperationListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql_flexibleservers.models.Operation] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.OperationListResult] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.OperationListResult] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( api_version=api_version, - template_url=self.list.metadata['url'], + template_url=self.list.metadata["url"], headers=_headers, params=_params, ) @@ -79,12 +89,17 @@ def prepare_request(next_link=None): request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_request( - api_version=api_version, - template_url=next_link, - 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() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore @@ -101,10 +116,8 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -114,8 +127,6 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/providers/Microsoft.DBforMySQL/operations"} # type: ignore + list.metadata = {"url": "/providers/Microsoft.DBforMySQL/operations"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_patch.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_patch.py index 0ad201a8c586..f7dd32510333 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_patch.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_patch.py @@ -10,6 +10,7 @@ __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. diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_replicas_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_replicas_operations.py index 21b6d6c4e620..471eeaaf7ce1 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_replicas_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_replicas_operations.py @@ -7,9 +7,17 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest @@ -20,9 +28,11 @@ from ... import models as _models from ..._vendor import _convert_request from ...operations._replicas_operations import build_list_by_server_request -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class ReplicasOperations: """ .. warning:: @@ -42,45 +52,46 @@ def __init__(self, *args, **kwargs) -> None: self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace def list_by_server( - self, - resource_group_name: str, - server_name: str, - **kwargs: Any - ) -> AsyncIterable[_models.ServerListResult]: + self, resource_group_name: str, server_name: str, **kwargs: Any + ) -> AsyncIterable["_models.Server"]: """List all the replicas for a given server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ServerListResult or the result of cls(response) + :return: An iterator like instance of either Server or the result of cls(response) :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql_flexibleservers.models.ServerListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql_flexibleservers.models.Server] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.ServerListResult] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ServerListResult] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_server_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_server.metadata['url'], + template_url=self.list_by_server.metadata["url"], headers=_headers, params=_params, ) @@ -88,15 +99,17 @@ def prepare_request(next_link=None): request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_by_server_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - server_name=server_name, - api_version=api_version, - template_url=next_link, - 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() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore @@ -113,10 +126,8 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -126,8 +137,6 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list_by_server.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/replicas"} # type: ignore + list_by_server.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/replicas"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_servers_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_servers_operations.py index d5381b136471..328d80738dcd 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_servers_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/aio/operations/_servers_operations.py @@ -6,10 +6,18 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar, Union, cast +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod @@ -22,10 +30,23 @@ from ... import models as _models from ..._vendor import _convert_request -from ...operations._servers_operations import build_create_request_initial, build_delete_request_initial, build_failover_request_initial, build_get_request, build_list_by_resource_group_request, build_list_request, build_restart_request_initial, build_start_request_initial, build_stop_request_initial, build_update_request_initial -T = TypeVar('T') +from ...operations._servers_operations import ( + build_create_request, + build_delete_request, + build_failover_request, + build_get_request, + build_list_by_resource_group_request, + build_list_request, + build_restart_request, + build_start_request, + build_stop_request, + build_update_request, +) + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class ServersOperations: """ .. warning:: @@ -45,36 +66,41 @@ def __init__(self, *args, **kwargs) -> None: 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") - async def _create_initial( - self, - resource_group_name: str, - server_name: str, - parameters: _models.Server, - **kwargs: Any + self, resource_group_name: str, server_name: str, parameters: Union[_models.Server, IO], **kwargs: Any ) -> Optional[_models.Server]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[Optional[_models.Server]] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.Server]] - _json = self._serialize.body(parameters, 'Server') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Server") - request = build_create_request_initial( - subscription_id=self._config.subscription_id, + request = build_create_request( resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._create_initial.metadata['url'], + content=_content, + template_url=self._create_initial.metadata["url"], headers=_headers, params=_params, ) @@ -82,10 +108,9 @@ async def _create_initial( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 201, 202]: @@ -94,36 +119,112 @@ async def _create_initial( deserialized = None if response.status_code == 200: - deserialized = self._deserialize('Server', pipeline_response) + deserialized = self._deserialize("Server", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('Server', pipeline_response) + deserialized = self._deserialize("Server", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _create_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}"} # type: ignore - + _create_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}"} # type: ignore - @distributed_trace_async + @overload async def begin_create( self, resource_group_name: str, server_name: str, parameters: _models.Server, + *, + content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.Server]: """Creates a new server or updates an existing server. The update action will overwrite the existing server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param parameters: The required parameters for creating or updating a server. + :param parameters: The required parameters for creating or updating a server. Required. :type parameters: ~azure.mgmt.rdbms.mysql_flexibleservers.models.Server + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + 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 Server or the result of + cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql_flexibleservers.models.Server] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create( + self, + resource_group_name: str, + server_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.Server]: + """Creates a new server or updates an existing server. The update action will overwrite the + existing server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param parameters: The required parameters for creating or updating a server. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :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 Server or the result of + cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql_flexibleservers.models.Server] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create( + self, resource_group_name: str, server_name: str, parameters: Union[_models.Server, IO], **kwargs: Any + ) -> AsyncLROPoller[_models.Server]: + """Creates a new server or updates an existing server. The update action will overwrite the + existing server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param parameters: The required parameters for creating or updating a server. Is either a model + type or a IO type. Required. + :type parameters: ~azure.mgmt.rdbms.mysql_flexibleservers.models.Server or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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 @@ -136,20 +237,17 @@ async def begin_create( cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql_flexibleservers.models.Server] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[_models.Server] - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Server] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = await self._create_initial( # type: ignore resource_group_name=resource_group_name, @@ -157,69 +255,71 @@ async def begin_create( parameters=parameters, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize('Server', pipeline_response) + deserialized = self._deserialize("Server", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - if polling is True: - polling_method = cast(AsyncPollingMethod, AsyncARMPolling( - lro_delay, - - - **kwargs - )) # type: AsyncPollingMethod - elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: polling_method = polling + polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_create.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}"} # type: ignore + begin_create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}"} # type: ignore async def _update_initial( - self, - resource_group_name: str, - server_name: str, - parameters: _models.ServerForUpdate, - **kwargs: Any + self, resource_group_name: str, server_name: str, parameters: Union[_models.ServerForUpdate, IO], **kwargs: Any ) -> Optional[_models.Server]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[Optional[_models.Server]] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.Server]] - _json = self._serialize.body(parameters, 'ServerForUpdate') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ServerForUpdate") - request = build_update_request_initial( - subscription_id=self._config.subscription_id, + request = build_update_request( resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._update_initial.metadata['url'], + content=_content, + template_url=self._update_initial.metadata["url"], headers=_headers, params=_params, ) @@ -227,10 +327,9 @@ async def _update_initial( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202]: @@ -239,33 +338,76 @@ async def _update_initial( deserialized = None if response.status_code == 200: - deserialized = self._deserialize('Server', pipeline_response) + deserialized = self._deserialize("Server", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}"} # type: ignore + _update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}"} # type: ignore - - @distributed_trace_async + @overload async def begin_update( self, resource_group_name: str, server_name: str, parameters: _models.ServerForUpdate, + *, + content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.Server]: """Updates an existing server. The request body can contain one to many of the properties present in the normal server definition. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param parameters: The required parameters for updating a server. + :param parameters: The required parameters for updating a server. Required. :type parameters: ~azure.mgmt.rdbms.mysql_flexibleservers.models.ServerForUpdate + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + 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 Server or the result of + cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql_flexibleservers.models.Server] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_update( + self, + resource_group_name: str, + server_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.Server]: + """Updates an existing server. The request body can contain one to many of the properties present + in the normal server definition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param parameters: The required parameters for updating a server. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :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 @@ -278,20 +420,50 @@ async def begin_update( cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql_flexibleservers.models.Server] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_update( + self, resource_group_name: str, server_name: str, parameters: Union[_models.ServerForUpdate, IO], **kwargs: Any + ) -> AsyncLROPoller[_models.Server]: + """Updates an existing server. The request body can contain one to many of the properties present + in the normal server definition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param parameters: The required parameters for updating a server. Is either a model type or a + IO type. Required. + :type parameters: ~azure.mgmt.rdbms.mysql_flexibleservers.models.ServerForUpdate or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either Server or the result of + cls(response) + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.mgmt.rdbms.mysql_flexibleservers.models.Server] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[_models.Server] - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Server] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = await self._update_initial( # type: ignore resource_group_name=resource_group_name, @@ -299,64 +471,59 @@ async def begin_update( parameters=parameters, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize('Server', pipeline_response) + deserialized = self._deserialize("Server", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - if polling is True: - polling_method = cast(AsyncPollingMethod, AsyncARMPolling( - lro_delay, - - - **kwargs - )) # type: AsyncPollingMethod - elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: polling_method = polling + polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}"} # type: ignore + begin_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}"} # type: ignore async def _delete_initial( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - server_name: str, - **kwargs: Any + self, resource_group_name: str, server_name: str, **kwargs: Any ) -> None: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] - - request = build_delete_request_initial( - subscription_id=self._config.subscription_id, + request = build_delete_request( resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._delete_initial.metadata['url'], + template_url=self._delete_initial.metadata["url"], headers=_headers, params=_params, ) @@ -364,10 +531,9 @@ async def _delete_initial( # pylint: disable=inconsistent-return-statements request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: @@ -377,21 +543,16 @@ async def _delete_initial( # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - _delete_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}"} # type: ignore - + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}"} # type: ignore @distributed_trace_async - async def begin_delete( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - server_name: str, - **kwargs: Any - ) -> AsyncLROPoller[None]: + async def begin_delete(self, resource_group_name: str, server_name: str, **kwargs: Any) -> AsyncLROPoller[None]: """Deletes a server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_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. @@ -403,92 +564,83 @@ async def begin_delete( # pylint: disable=inconsistent-return-statements Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = await self._delete_initial( # type: ignore resource_group_name=resource_group_name, server_name=server_name, api_version=api_version, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - if polling is True: - polling_method = cast(AsyncPollingMethod, AsyncARMPolling( - lro_delay, - - - **kwargs - )) # type: AsyncPollingMethod - elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: polling_method = polling + polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_delete.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}"} # type: ignore + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}"} # type: ignore @distributed_trace_async - async def get( - self, - resource_group_name: str, - server_name: str, - **kwargs: Any - ) -> _models.Server: + async def get(self, resource_group_name: str, server_name: str, **kwargs: Any) -> _models.Server: """Gets information about a server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Server, or the result of cls(response) + :return: Server or the result of cls(response) :rtype: ~azure.mgmt.rdbms.mysql_flexibleservers.models.Server - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.Server] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.Server] - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], headers=_headers, params=_params, ) @@ -496,60 +648,59 @@ async def get( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('Server', pipeline_response) + deserialized = self._deserialize("Server", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}"} # type: ignore @distributed_trace - def list_by_resource_group( - self, - resource_group_name: str, - **kwargs: Any - ) -> AsyncIterable[_models.ServerListResult]: + def list_by_resource_group(self, resource_group_name: str, **kwargs: Any) -> AsyncIterable["_models.Server"]: """List all the servers in a given 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 ServerListResult or the result of cls(response) + :return: An iterator like instance of either Server or the result of cls(response) :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql_flexibleservers.models.ServerListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql_flexibleservers.models.Server] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.ServerListResult] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ServerListResult] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_resource_group_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata['url'], + template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) @@ -557,14 +708,17 @@ def prepare_request(next_link=None): request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_by_resource_group_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - api_version=api_version, - template_url=next_link, - 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() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore @@ -581,10 +735,8 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -594,42 +746,41 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list_by_resource_group.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers"} # type: ignore + list_by_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers"} # type: ignore @distributed_trace - def list( - self, - **kwargs: Any - ) -> AsyncIterable[_models.ServerListResult]: + def list(self, **kwargs: Any) -> AsyncIterable["_models.Server"]: """List all the servers in a given subscription. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ServerListResult or the result of cls(response) + :return: An iterator like instance of either Server or the result of cls(response) :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql_flexibleservers.models.ServerListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.rdbms.mysql_flexibleservers.models.Server] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.ServerListResult] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ServerListResult] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list.metadata['url'], + template_url=self.list.metadata["url"], headers=_headers, params=_params, ) @@ -637,13 +788,17 @@ def prepare_request(next_link=None): request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_request( - subscription_id=self._config.subscription_id, - api_version=api_version, - template_url=next_link, - 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() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore @@ -660,10 +815,8 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -673,36 +826,33 @@ async def get_next(next_link=None): return pipeline_response + return AsyncItemPaged(get_next, extract_data) - return AsyncItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/flexibleServers"} # type: ignore + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/flexibleServers"} # type: ignore async def _failover_initial( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - server_name: str, - **kwargs: Any + self, resource_group_name: str, server_name: str, **kwargs: Any ) -> None: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] - - request = build_failover_request_initial( - subscription_id=self._config.subscription_id, + request = build_failover_request( resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._failover_initial.metadata['url'], + template_url=self._failover_initial.metadata["url"], headers=_headers, params=_params, ) @@ -710,10 +860,9 @@ async def _failover_initial( # pylint: disable=inconsistent-return-statements request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202]: @@ -723,21 +872,16 @@ async def _failover_initial( # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - _failover_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/failover"} # type: ignore - + _failover_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/failover"} # type: ignore @distributed_trace_async - async def begin_failover( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - server_name: str, - **kwargs: Any - ) -> AsyncLROPoller[None]: + async def begin_failover(self, resource_group_name: str, server_name: str, **kwargs: Any) -> AsyncLROPoller[None]: """Manual failover a server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_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. @@ -749,85 +893,88 @@ async def begin_failover( # pylint: disable=inconsistent-return-statements Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = await self._failover_initial( # type: ignore resource_group_name=resource_group_name, server_name=server_name, api_version=api_version, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - if polling is True: - polling_method = cast(AsyncPollingMethod, AsyncARMPolling( - lro_delay, - - - **kwargs - )) # type: AsyncPollingMethod - elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: polling_method = polling + polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_failover.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/failover"} # type: ignore + begin_failover.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/failover"} # type: ignore async def _restart_initial( # pylint: disable=inconsistent-return-statements self, resource_group_name: str, server_name: str, - parameters: _models.ServerRestartParameter, + parameters: Union[_models.ServerRestartParameter, IO], **kwargs: Any ) -> None: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[None] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[None] - _json = self._serialize.body(parameters, 'ServerRestartParameter') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ServerRestartParameter") - request = build_restart_request_initial( - subscription_id=self._config.subscription_id, + request = build_restart_request( resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._restart_initial.metadata['url'], + content=_content, + template_url=self._restart_initial.metadata["url"], headers=_headers, params=_params, ) @@ -835,10 +982,9 @@ async def _restart_initial( # pylint: disable=inconsistent-return-statements request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202]: @@ -848,25 +994,99 @@ async def _restart_initial( # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - _restart_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/restart"} # type: ignore + _restart_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/restart"} # type: ignore - - @distributed_trace_async - async def begin_restart( # pylint: disable=inconsistent-return-statements + @overload + async def begin_restart( self, resource_group_name: str, server_name: str, parameters: _models.ServerRestartParameter, + *, + content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[None]: """Restarts a server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param parameters: The required parameters for restarting a server. + :param parameters: The required parameters for restarting a server. Required. :type parameters: ~azure.mgmt.rdbms.mysql_flexibleservers.models.ServerRestartParameter + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + 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 None or the result of cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_restart( + self, + resource_group_name: str, + server_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Restarts a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param parameters: The required parameters for restarting a server. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :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: + """ + + @distributed_trace_async + async def begin_restart( + self, + resource_group_name: str, + server_name: str, + parameters: Union[_models.ServerRestartParameter, IO], + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Restarts a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param parameters: The required parameters for restarting a server. Is either a model type or a + IO type. Required. + :type parameters: ~azure.mgmt.rdbms.mysql_flexibleservers.models.ServerRestartParameter or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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 @@ -877,20 +1097,17 @@ async def begin_restart( # pylint: disable=inconsistent-return-statements Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[None] - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = await self._restart_initial( # type: ignore resource_group_name=resource_group_name, @@ -898,62 +1115,57 @@ async def begin_restart( # pylint: disable=inconsistent-return-statements parameters=parameters, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - if polling is True: - polling_method = cast(AsyncPollingMethod, AsyncARMPolling( - lro_delay, - - - **kwargs - )) # type: AsyncPollingMethod - elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: polling_method = polling + polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_restart.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/restart"} # type: ignore + begin_restart.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/restart"} # type: ignore async def _start_initial( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - server_name: str, - **kwargs: Any + self, resource_group_name: str, server_name: str, **kwargs: Any ) -> None: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] - - request = build_start_request_initial( - subscription_id=self._config.subscription_id, + request = build_start_request( resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._start_initial.metadata['url'], + template_url=self._start_initial.metadata["url"], headers=_headers, params=_params, ) @@ -961,10 +1173,9 @@ async def _start_initial( # pylint: disable=inconsistent-return-statements request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202]: @@ -974,21 +1185,16 @@ async def _start_initial( # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - _start_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/start"} # type: ignore - + _start_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/start"} # type: ignore @distributed_trace_async - async def begin_start( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - server_name: str, - **kwargs: Any - ) -> AsyncLROPoller[None]: + async def begin_start(self, resource_group_name: str, server_name: str, **kwargs: Any) -> AsyncLROPoller[None]: """Starts a server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_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. @@ -1000,80 +1206,72 @@ async def begin_start( # pylint: disable=inconsistent-return-statements Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = await self._start_initial( # type: ignore resource_group_name=resource_group_name, server_name=server_name, api_version=api_version, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - if polling is True: - polling_method = cast(AsyncPollingMethod, AsyncARMPolling( - lro_delay, - - - **kwargs - )) # type: AsyncPollingMethod - elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: polling_method = polling + polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_start.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/start"} # type: ignore + begin_start.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/start"} # type: ignore async def _stop_initial( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - server_name: str, - **kwargs: Any + self, resource_group_name: str, server_name: str, **kwargs: Any ) -> None: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] - - request = build_stop_request_initial( - subscription_id=self._config.subscription_id, + request = build_stop_request( resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._stop_initial.metadata['url'], + template_url=self._stop_initial.metadata["url"], headers=_headers, params=_params, ) @@ -1081,10 +1279,9 @@ async def _stop_initial( # pylint: disable=inconsistent-return-statements request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202]: @@ -1094,21 +1291,16 @@ async def _stop_initial( # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - _stop_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/stop"} # type: ignore - + _stop_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/stop"} # type: ignore @distributed_trace_async - async def begin_stop( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - server_name: str, - **kwargs: Any - ) -> AsyncLROPoller[None]: + async def begin_stop(self, resource_group_name: str, server_name: str, **kwargs: Any) -> AsyncLROPoller[None]: """Stops a server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_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. @@ -1120,52 +1312,45 @@ async def begin_stop( # pylint: disable=inconsistent-return-statements Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = await self._stop_initial( # type: ignore resource_group_name=resource_group_name, server_name=server_name, api_version=api_version, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - if polling is True: - polling_method = cast(AsyncPollingMethod, AsyncARMPolling( - lro_delay, - - - **kwargs - )) # type: AsyncPollingMethod - elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: polling_method = polling + polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_stop.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/stop"} # type: ignore + begin_stop.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/stop"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/models/__init__.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/models/__init__.py index 4aaaec63be05..b09f1d52a398 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/models/__init__.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/models/__init__.py @@ -55,95 +55,93 @@ from ._models_py3 import VirtualNetworkSubnetUsageParameter from ._models_py3 import VirtualNetworkSubnetUsageResult - -from ._my_sql_management_client_enums import ( - AdministratorName, - AdministratorType, - ConfigurationSource, - CreateMode, - CreatedByType, - DataEncryptionType, - EnableStatusEnum, - HighAvailabilityMode, - HighAvailabilityState, - IsConfigPendingRestart, - IsDynamicConfig, - IsReadOnly, - ReplicationRole, - ResetAllToDefault, - ServerState, - ServerVersion, - SkuTier, -) +from ._my_sql_management_client_enums import AdministratorName +from ._my_sql_management_client_enums import AdministratorType +from ._my_sql_management_client_enums import ConfigurationSource +from ._my_sql_management_client_enums import CreateMode +from ._my_sql_management_client_enums import CreatedByType +from ._my_sql_management_client_enums import DataEncryptionType +from ._my_sql_management_client_enums import EnableStatusEnum +from ._my_sql_management_client_enums import HighAvailabilityMode +from ._my_sql_management_client_enums import HighAvailabilityState +from ._my_sql_management_client_enums import IsConfigPendingRestart +from ._my_sql_management_client_enums import IsDynamicConfig +from ._my_sql_management_client_enums import IsReadOnly +from ._my_sql_management_client_enums import ReplicationRole +from ._my_sql_management_client_enums import ResetAllToDefault +from ._my_sql_management_client_enums import ServerState +from ._my_sql_management_client_enums import ServerVersion +from ._my_sql_management_client_enums import SkuTier from ._patch import __all__ as _patch_all from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import from ._patch import patch_sdk as _patch_sdk + __all__ = [ - 'AdministratorListResult', - 'AzureADAdministrator', - 'Backup', - 'CapabilitiesListResult', - 'CapabilityProperties', - 'Configuration', - 'ConfigurationForBatchUpdate', - 'ConfigurationListForBatchUpdate', - 'ConfigurationListResult', - 'DataEncryption', - 'Database', - 'DatabaseListResult', - 'DelegatedSubnetUsage', - 'ErrorAdditionalInfo', - 'ErrorResponse', - 'FirewallRule', - 'FirewallRuleListResult', - 'GetPrivateDnsZoneSuffixResponse', - 'HighAvailability', - 'Identity', - 'LogFile', - 'LogFileListResult', - 'MaintenanceWindow', - 'NameAvailability', - 'NameAvailabilityRequest', - 'Network', - 'Operation', - 'OperationDisplay', - 'OperationListResult', - 'ProxyResource', - 'Resource', - 'Server', - 'ServerBackup', - 'ServerBackupListResult', - 'ServerEditionCapability', - 'ServerForUpdate', - 'ServerListResult', - 'ServerRestartParameter', - 'ServerVersionCapability', - 'Sku', - 'SkuCapability', - 'Storage', - 'StorageEditionCapability', - 'SystemData', - 'TrackedResource', - 'UserAssignedIdentity', - 'VirtualNetworkSubnetUsageParameter', - 'VirtualNetworkSubnetUsageResult', - 'AdministratorName', - 'AdministratorType', - 'ConfigurationSource', - 'CreateMode', - 'CreatedByType', - 'DataEncryptionType', - 'EnableStatusEnum', - 'HighAvailabilityMode', - 'HighAvailabilityState', - 'IsConfigPendingRestart', - 'IsDynamicConfig', - 'IsReadOnly', - 'ReplicationRole', - 'ResetAllToDefault', - 'ServerState', - 'ServerVersion', - 'SkuTier', + "AdministratorListResult", + "AzureADAdministrator", + "Backup", + "CapabilitiesListResult", + "CapabilityProperties", + "Configuration", + "ConfigurationForBatchUpdate", + "ConfigurationListForBatchUpdate", + "ConfigurationListResult", + "DataEncryption", + "Database", + "DatabaseListResult", + "DelegatedSubnetUsage", + "ErrorAdditionalInfo", + "ErrorResponse", + "FirewallRule", + "FirewallRuleListResult", + "GetPrivateDnsZoneSuffixResponse", + "HighAvailability", + "Identity", + "LogFile", + "LogFileListResult", + "MaintenanceWindow", + "NameAvailability", + "NameAvailabilityRequest", + "Network", + "Operation", + "OperationDisplay", + "OperationListResult", + "ProxyResource", + "Resource", + "Server", + "ServerBackup", + "ServerBackupListResult", + "ServerEditionCapability", + "ServerForUpdate", + "ServerListResult", + "ServerRestartParameter", + "ServerVersionCapability", + "Sku", + "SkuCapability", + "Storage", + "StorageEditionCapability", + "SystemData", + "TrackedResource", + "UserAssignedIdentity", + "VirtualNetworkSubnetUsageParameter", + "VirtualNetworkSubnetUsageResult", + "AdministratorName", + "AdministratorType", + "ConfigurationSource", + "CreateMode", + "CreatedByType", + "DataEncryptionType", + "EnableStatusEnum", + "HighAvailabilityMode", + "HighAvailabilityState", + "IsConfigPendingRestart", + "IsDynamicConfig", + "IsReadOnly", + "ReplicationRole", + "ResetAllToDefault", + "ServerState", + "ServerVersion", + "SkuTier", ] __all__.extend([p for p in _patch_all if p not in __all__]) -_patch_sdk() \ No newline at end of file +_patch_sdk() diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/models/_models_py3.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/models/_models_py3.py index cc2cb6e6b1ae..292ebe13c3dd 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/models/_models_py3.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/models/_models_py3.py @@ -1,4 +1,5 @@ # coding=utf-8 +# pylint: disable=too-many-lines # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. @@ -7,16 +8,22 @@ # -------------------------------------------------------------------------- import datetime +import sys from typing import Any, Dict, List, Optional, TYPE_CHECKING, Union -import msrest.serialization +from .. import _serialization if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports - import __init__ as _models + from .. import models as _models +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object -class AdministratorListResult(msrest.serialization.Model): +class AdministratorListResult(_serialization.Model): """A List of azure ad administrators. :ivar value: The list of azure ad administrator of a server. @@ -26,16 +33,12 @@ class AdministratorListResult(msrest.serialization.Model): """ _attribute_map = { - 'value': {'key': 'value', 'type': '[AzureADAdministrator]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[AzureADAdministrator]"}, + "next_link": {"key": "nextLink", "type": "str"}, } def __init__( - self, - *, - value: Optional[List["_models.AzureADAdministrator"]] = None, - next_link: Optional[str] = None, - **kwargs + self, *, value: Optional[List["_models.AzureADAdministrator"]] = None, next_link: Optional[str] = None, **kwargs ): """ :keyword value: The list of azure ad administrator of a server. @@ -43,12 +46,12 @@ def __init__( :keyword next_link: The link used to get the next page of operations. :paramtype next_link: str """ - super(AdministratorListResult, self).__init__(**kwargs) + super().__init__(**kwargs) self.value = value self.next_link = next_link -class Resource(msrest.serialization.Model): +class Resource(_serialization.Model): """Common fields that are returned in the response for all Azure Resource Manager resources. Variables are only populated by the server, and will be ignored when sending a request. @@ -64,24 +67,20 @@ class Resource(msrest.serialization.Model): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(Resource, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.id = None self.name = None self.type = None @@ -103,24 +102,20 @@ class ProxyResource(Resource): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(ProxyResource, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) class AzureADAdministrator(ProxyResource): @@ -138,7 +133,7 @@ class AzureADAdministrator(ProxyResource): :vartype type: str :ivar system_data: The system metadata relating to this resource. :vartype system_data: ~azure.mgmt.rdbms.mysql_flexibleservers.models.SystemData - :ivar administrator_type: Type of the sever administrator. Known values are: "ActiveDirectory". + :ivar administrator_type: Type of the sever administrator. "ActiveDirectory" :vartype administrator_type: str or ~azure.mgmt.rdbms.mysql_flexibleservers.models.AdministratorType :ivar login: Login name of the server administrator. @@ -152,22 +147,22 @@ class AzureADAdministrator(ProxyResource): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'system_data': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "system_data": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'system_data': {'key': 'systemData', 'type': 'SystemData'}, - 'administrator_type': {'key': 'properties.administratorType', 'type': 'str'}, - 'login': {'key': 'properties.login', 'type': 'str'}, - 'sid': {'key': 'properties.sid', 'type': 'str'}, - 'tenant_id': {'key': 'properties.tenantId', 'type': 'str'}, - 'identity_resource_id': {'key': 'properties.identityResourceId', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + "administrator_type": {"key": "properties.administratorType", "type": "str"}, + "login": {"key": "properties.login", "type": "str"}, + "sid": {"key": "properties.sid", "type": "str"}, + "tenant_id": {"key": "properties.tenantId", "type": "str"}, + "identity_resource_id": {"key": "properties.identityResourceId", "type": "str"}, } def __init__( @@ -181,8 +176,7 @@ def __init__( **kwargs ): """ - :keyword administrator_type: Type of the sever administrator. Known values are: - "ActiveDirectory". + :keyword administrator_type: Type of the sever administrator. "ActiveDirectory" :paramtype administrator_type: str or ~azure.mgmt.rdbms.mysql_flexibleservers.models.AdministratorType :keyword login: Login name of the server administrator. @@ -194,7 +188,7 @@ def __init__( :keyword identity_resource_id: The resource id of the identity used for AAD Authentication. :paramtype identity_resource_id: str """ - super(AzureADAdministrator, self).__init__(**kwargs) + super().__init__(**kwargs) self.system_data = None self.administrator_type = administrator_type self.login = login @@ -203,7 +197,7 @@ def __init__( self.identity_resource_id = identity_resource_id -class Backup(msrest.serialization.Model): +class Backup(_serialization.Model): """Storage Profile properties of a server. Variables are only populated by the server, and will be ignored when sending a request. @@ -211,7 +205,7 @@ class Backup(msrest.serialization.Model): :ivar backup_retention_days: Backup retention days for the server. :vartype backup_retention_days: int :ivar geo_redundant_backup: Whether or not geo redundant backup is enabled. Known values are: - "Enabled", "Disabled". + "Enabled" and "Disabled". :vartype geo_redundant_backup: str or ~azure.mgmt.rdbms.mysql_flexibleservers.models.EnableStatusEnum :ivar earliest_restore_date: Earliest restore point creation time (ISO8601 format). @@ -219,13 +213,13 @@ class Backup(msrest.serialization.Model): """ _validation = { - 'earliest_restore_date': {'readonly': True}, + "earliest_restore_date": {"readonly": True}, } _attribute_map = { - 'backup_retention_days': {'key': 'backupRetentionDays', 'type': 'int'}, - 'geo_redundant_backup': {'key': 'geoRedundantBackup', 'type': 'str'}, - 'earliest_restore_date': {'key': 'earliestRestoreDate', 'type': 'iso-8601'}, + "backup_retention_days": {"key": "backupRetentionDays", "type": "int"}, + "geo_redundant_backup": {"key": "geoRedundantBackup", "type": "str"}, + "earliest_restore_date": {"key": "earliestRestoreDate", "type": "iso-8601"}, } def __init__( @@ -239,17 +233,17 @@ def __init__( :keyword backup_retention_days: Backup retention days for the server. :paramtype backup_retention_days: int :keyword geo_redundant_backup: Whether or not geo redundant backup is enabled. Known values - are: "Enabled", "Disabled". + are: "Enabled" and "Disabled". :paramtype geo_redundant_backup: str or ~azure.mgmt.rdbms.mysql_flexibleservers.models.EnableStatusEnum """ - super(Backup, self).__init__(**kwargs) + super().__init__(**kwargs) self.backup_retention_days = backup_retention_days self.geo_redundant_backup = geo_redundant_backup self.earliest_restore_date = None -class CapabilitiesListResult(msrest.serialization.Model): +class CapabilitiesListResult(_serialization.Model): """location capability. Variables are only populated by the server, and will be ignored when sending a request. @@ -261,27 +255,23 @@ class CapabilitiesListResult(msrest.serialization.Model): """ _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, + "value": {"readonly": True}, + "next_link": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[CapabilityProperties]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[CapabilityProperties]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(CapabilitiesListResult, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.value = None self.next_link = None -class CapabilityProperties(msrest.serialization.Model): +class CapabilityProperties(_serialization.Model): """Location capabilities. Variables are only populated by the server, and will be ignored when sending a request. @@ -298,33 +288,32 @@ class CapabilityProperties(msrest.serialization.Model): """ _validation = { - 'zone': {'readonly': True}, - 'supported_ha_mode': {'readonly': True}, - 'supported_geo_backup_regions': {'readonly': True}, - 'supported_flexible_server_editions': {'readonly': True}, + "zone": {"readonly": True}, + "supported_ha_mode": {"readonly": True}, + "supported_geo_backup_regions": {"readonly": True}, + "supported_flexible_server_editions": {"readonly": True}, } _attribute_map = { - 'zone': {'key': 'zone', 'type': 'str'}, - 'supported_ha_mode': {'key': 'supportedHAMode', 'type': '[str]'}, - 'supported_geo_backup_regions': {'key': 'supportedGeoBackupRegions', 'type': '[str]'}, - 'supported_flexible_server_editions': {'key': 'supportedFlexibleServerEditions', 'type': '[ServerEditionCapability]'}, - } - - def __init__( - self, - **kwargs - ): - """ - """ - super(CapabilityProperties, self).__init__(**kwargs) + "zone": {"key": "zone", "type": "str"}, + "supported_ha_mode": {"key": "supportedHAMode", "type": "[str]"}, + "supported_geo_backup_regions": {"key": "supportedGeoBackupRegions", "type": "[str]"}, + "supported_flexible_server_editions": { + "key": "supportedFlexibleServerEditions", + "type": "[ServerEditionCapability]", + }, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.zone = None self.supported_ha_mode = None self.supported_geo_backup_regions = None self.supported_flexible_server_editions = None -class Configuration(ProxyResource): +class Configuration(ProxyResource): # pylint: disable=too-many-instance-attributes """Represents a Configuration. Variables are only populated by the server, and will be ignored when sending a request. @@ -349,47 +338,48 @@ class Configuration(ProxyResource): :vartype data_type: str :ivar allowed_values: Allowed values of the configuration. :vartype allowed_values: str - :ivar source: Source of the configuration. Known values are: "system-default", "user-override". + :ivar source: Source of the configuration. Known values are: "system-default" and + "user-override". :vartype source: str or ~azure.mgmt.rdbms.mysql_flexibleservers.models.ConfigurationSource - :ivar is_read_only: If is the configuration read only. Known values are: "True", "False". + :ivar is_read_only: If is the configuration read only. Known values are: "True" and "False". :vartype is_read_only: str or ~azure.mgmt.rdbms.mysql_flexibleservers.models.IsReadOnly :ivar is_config_pending_restart: If is the configuration pending restart or not. Known values - are: "True", "False". + are: "True" and "False". :vartype is_config_pending_restart: str or ~azure.mgmt.rdbms.mysql_flexibleservers.models.IsConfigPendingRestart - :ivar is_dynamic_config: If is the configuration dynamic. Known values are: "True", "False". + :ivar is_dynamic_config: If is the configuration dynamic. Known values are: "True" and "False". :vartype is_dynamic_config: str or ~azure.mgmt.rdbms.mysql_flexibleservers.models.IsDynamicConfig """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'system_data': {'readonly': True}, - 'description': {'readonly': True}, - 'default_value': {'readonly': True}, - 'data_type': {'readonly': True}, - 'allowed_values': {'readonly': True}, - 'is_read_only': {'readonly': True}, - 'is_config_pending_restart': {'readonly': True}, - 'is_dynamic_config': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "system_data": {"readonly": True}, + "description": {"readonly": True}, + "default_value": {"readonly": True}, + "data_type": {"readonly": True}, + "allowed_values": {"readonly": True}, + "is_read_only": {"readonly": True}, + "is_config_pending_restart": {"readonly": True}, + "is_dynamic_config": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'system_data': {'key': 'systemData', 'type': 'SystemData'}, - 'value': {'key': 'properties.value', 'type': 'str'}, - 'description': {'key': 'properties.description', 'type': 'str'}, - 'default_value': {'key': 'properties.defaultValue', 'type': 'str'}, - 'data_type': {'key': 'properties.dataType', 'type': 'str'}, - 'allowed_values': {'key': 'properties.allowedValues', 'type': 'str'}, - 'source': {'key': 'properties.source', 'type': 'str'}, - 'is_read_only': {'key': 'properties.isReadOnly', 'type': 'str'}, - 'is_config_pending_restart': {'key': 'properties.isConfigPendingRestart', 'type': 'str'}, - 'is_dynamic_config': {'key': 'properties.isDynamicConfig', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + "value": {"key": "properties.value", "type": "str"}, + "description": {"key": "properties.description", "type": "str"}, + "default_value": {"key": "properties.defaultValue", "type": "str"}, + "data_type": {"key": "properties.dataType", "type": "str"}, + "allowed_values": {"key": "properties.allowedValues", "type": "str"}, + "source": {"key": "properties.source", "type": "str"}, + "is_read_only": {"key": "properties.isReadOnly", "type": "str"}, + "is_config_pending_restart": {"key": "properties.isConfigPendingRestart", "type": "str"}, + "is_dynamic_config": {"key": "properties.isDynamicConfig", "type": "str"}, } def __init__( @@ -402,11 +392,11 @@ def __init__( """ :keyword value: Value of the configuration. :paramtype value: str - :keyword source: Source of the configuration. Known values are: "system-default", + :keyword source: Source of the configuration. Known values are: "system-default" and "user-override". :paramtype source: str or ~azure.mgmt.rdbms.mysql_flexibleservers.models.ConfigurationSource """ - super(Configuration, self).__init__(**kwargs) + super().__init__(**kwargs) self.system_data = None self.value = value self.description = None @@ -419,7 +409,7 @@ def __init__( self.is_dynamic_config = None -class ConfigurationForBatchUpdate(msrest.serialization.Model): +class ConfigurationForBatchUpdate(_serialization.Model): """Represents a Configuration. :ivar name: Name of the configuration. @@ -431,18 +421,13 @@ class ConfigurationForBatchUpdate(msrest.serialization.Model): """ _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'value': {'key': 'properties.value', 'type': 'str'}, - 'source': {'key': 'properties.source', 'type': 'str'}, + "name": {"key": "name", "type": "str"}, + "value": {"key": "properties.value", "type": "str"}, + "source": {"key": "properties.source", "type": "str"}, } def __init__( - self, - *, - name: Optional[str] = None, - value: Optional[str] = None, - source: Optional[str] = None, - **kwargs + self, *, name: Optional[str] = None, value: Optional[str] = None, source: Optional[str] = None, **kwargs ): """ :keyword name: Name of the configuration. @@ -452,27 +437,27 @@ def __init__( :keyword source: Source of the configuration. :paramtype source: str """ - super(ConfigurationForBatchUpdate, self).__init__(**kwargs) + super().__init__(**kwargs) self.name = name self.value = value self.source = source -class ConfigurationListForBatchUpdate(msrest.serialization.Model): +class ConfigurationListForBatchUpdate(_serialization.Model): """A list of server configurations to update. :ivar value: The list of server configurations. :vartype value: list[~azure.mgmt.rdbms.mysql_flexibleservers.models.ConfigurationForBatchUpdate] :ivar reset_all_to_default: Whether to reset all server parameters to default. Known values - are: "True", "False". + are: "True" and "False". :vartype reset_all_to_default: str or ~azure.mgmt.rdbms.mysql_flexibleservers.models.ResetAllToDefault """ _attribute_map = { - 'value': {'key': 'value', 'type': '[ConfigurationForBatchUpdate]'}, - 'reset_all_to_default': {'key': 'resetAllToDefault', 'type': 'str'}, + "value": {"key": "value", "type": "[ConfigurationForBatchUpdate]"}, + "reset_all_to_default": {"key": "resetAllToDefault", "type": "str"}, } def __init__( @@ -487,16 +472,16 @@ def __init__( :paramtype value: list[~azure.mgmt.rdbms.mysql_flexibleservers.models.ConfigurationForBatchUpdate] :keyword reset_all_to_default: Whether to reset all server parameters to default. Known values - are: "True", "False". + are: "True" and "False". :paramtype reset_all_to_default: str or ~azure.mgmt.rdbms.mysql_flexibleservers.models.ResetAllToDefault """ - super(ConfigurationListForBatchUpdate, self).__init__(**kwargs) + super().__init__(**kwargs) self.value = value self.reset_all_to_default = reset_all_to_default -class ConfigurationListResult(msrest.serialization.Model): +class ConfigurationListResult(_serialization.Model): """A list of server configurations. :ivar value: The list of server configurations. @@ -506,16 +491,12 @@ class ConfigurationListResult(msrest.serialization.Model): """ _attribute_map = { - 'value': {'key': 'value', 'type': '[Configuration]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[Configuration]"}, + "next_link": {"key": "nextLink", "type": "str"}, } def __init__( - self, - *, - value: Optional[List["_models.Configuration"]] = None, - next_link: Optional[str] = None, - **kwargs + self, *, value: Optional[List["_models.Configuration"]] = None, next_link: Optional[str] = None, **kwargs ): """ :keyword value: The list of server configurations. @@ -523,7 +504,7 @@ def __init__( :keyword next_link: The link used to get the next page of operations. :paramtype next_link: str """ - super(ConfigurationListResult, self).__init__(**kwargs) + super().__init__(**kwargs) self.value = value self.next_link = next_link @@ -550,41 +531,35 @@ class Database(ProxyResource): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'system_data': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "system_data": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'system_data': {'key': 'systemData', 'type': 'SystemData'}, - 'charset': {'key': 'properties.charset', 'type': 'str'}, - 'collation': {'key': 'properties.collation', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + "charset": {"key": "properties.charset", "type": "str"}, + "collation": {"key": "properties.collation", "type": "str"}, } - def __init__( - self, - *, - charset: Optional[str] = None, - collation: Optional[str] = None, - **kwargs - ): + def __init__(self, *, charset: Optional[str] = None, collation: Optional[str] = None, **kwargs): """ :keyword charset: The charset of the database. :paramtype charset: str :keyword collation: The collation of the database. :paramtype collation: str """ - super(Database, self).__init__(**kwargs) + super().__init__(**kwargs) self.system_data = None self.charset = charset self.collation = collation -class DatabaseListResult(msrest.serialization.Model): +class DatabaseListResult(_serialization.Model): """A List of databases. :ivar value: The list of databases housed in a server. @@ -594,29 +569,23 @@ class DatabaseListResult(msrest.serialization.Model): """ _attribute_map = { - 'value': {'key': 'value', 'type': '[Database]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[Database]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - *, - value: Optional[List["_models.Database"]] = None, - next_link: Optional[str] = None, - **kwargs - ): + def __init__(self, *, value: Optional[List["_models.Database"]] = None, next_link: Optional[str] = None, **kwargs): """ :keyword value: The list of databases housed in a server. :paramtype value: list[~azure.mgmt.rdbms.mysql_flexibleservers.models.Database] :keyword next_link: The link used to get the next page of operations. :paramtype next_link: str """ - super(DatabaseListResult, self).__init__(**kwargs) + super().__init__(**kwargs) self.value = value self.next_link = next_link -class DataEncryption(msrest.serialization.Model): +class DataEncryption(_serialization.Model): """The date encryption for cmk. :ivar primary_user_assigned_identity_id: Primary user identity resource id. @@ -630,16 +599,16 @@ class DataEncryption(msrest.serialization.Model): region as geo backup. :vartype geo_backup_key_uri: str :ivar type: The key type, AzureKeyVault for enable cmk, SystemManaged for disable cmk. Known - values are: "AzureKeyVault", "SystemManaged". + values are: "AzureKeyVault" and "SystemManaged". :vartype type: str or ~azure.mgmt.rdbms.mysql_flexibleservers.models.DataEncryptionType """ _attribute_map = { - 'primary_user_assigned_identity_id': {'key': 'primaryUserAssignedIdentityId', 'type': 'str'}, - 'primary_key_uri': {'key': 'primaryKeyURI', 'type': 'str'}, - 'geo_backup_user_assigned_identity_id': {'key': 'geoBackupUserAssignedIdentityId', 'type': 'str'}, - 'geo_backup_key_uri': {'key': 'geoBackupKeyURI', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, + "primary_user_assigned_identity_id": {"key": "primaryUserAssignedIdentityId", "type": "str"}, + "primary_key_uri": {"key": "primaryKeyURI", "type": "str"}, + "geo_backup_user_assigned_identity_id": {"key": "geoBackupUserAssignedIdentityId", "type": "str"}, + "geo_backup_key_uri": {"key": "geoBackupKeyURI", "type": "str"}, + "type": {"key": "type", "type": "str"}, } def __init__( @@ -664,10 +633,10 @@ def __init__( same region as geo backup. :paramtype geo_backup_key_uri: str :keyword type: The key type, AzureKeyVault for enable cmk, SystemManaged for disable cmk. Known - values are: "AzureKeyVault", "SystemManaged". + values are: "AzureKeyVault" and "SystemManaged". :paramtype type: str or ~azure.mgmt.rdbms.mysql_flexibleservers.models.DataEncryptionType """ - super(DataEncryption, self).__init__(**kwargs) + super().__init__(**kwargs) self.primary_user_assigned_identity_id = primary_user_assigned_identity_id self.primary_key_uri = primary_key_uri self.geo_backup_user_assigned_identity_id = geo_backup_user_assigned_identity_id @@ -675,7 +644,7 @@ def __init__( self.type = type -class DelegatedSubnetUsage(msrest.serialization.Model): +class DelegatedSubnetUsage(_serialization.Model): """Delegated subnet usage data. Variables are only populated by the server, and will be ignored when sending a request. @@ -683,31 +652,27 @@ class DelegatedSubnetUsage(msrest.serialization.Model): :ivar subnet_name: name of the subnet. :vartype subnet_name: str :ivar usage: Number of used delegated subnets. - :vartype usage: long + :vartype usage: int """ _validation = { - 'subnet_name': {'readonly': True}, - 'usage': {'readonly': True}, + "subnet_name": {"readonly": True}, + "usage": {"readonly": True}, } _attribute_map = { - 'subnet_name': {'key': 'subnetName', 'type': 'str'}, - 'usage': {'key': 'usage', 'type': 'long'}, + "subnet_name": {"key": "subnetName", "type": "str"}, + "usage": {"key": "usage", "type": "int"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(DelegatedSubnetUsage, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.subnet_name = None self.usage = None -class ErrorAdditionalInfo(msrest.serialization.Model): +class ErrorAdditionalInfo(_serialization.Model): """The resource management error additional info. Variables are only populated by the server, and will be ignored when sending a request. @@ -715,31 +680,27 @@ class ErrorAdditionalInfo(msrest.serialization.Model): :ivar type: The additional info type. :vartype type: str :ivar info: The additional info. - :vartype info: any + :vartype info: JSON """ _validation = { - 'type': {'readonly': True}, - 'info': {'readonly': True}, + "type": {"readonly": True}, + "info": {"readonly": True}, } _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'info': {'key': 'info', 'type': 'object'}, + "type": {"key": "type", "type": "str"}, + "info": {"key": "info", "type": "object"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(ErrorAdditionalInfo, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.type = None self.info = None -class ErrorResponse(msrest.serialization.Model): +class ErrorResponse(_serialization.Model): """Common error response for all Azure Resource Manager APIs to return error details for failed operations. (This also follows the OData error response format.). Variables are only populated by the server, and will be ignored when sending a request. @@ -758,28 +719,24 @@ class ErrorResponse(msrest.serialization.Model): """ _validation = { - 'code': {'readonly': True}, - 'message': {'readonly': True}, - 'target': {'readonly': True}, - 'details': {'readonly': True}, - 'additional_info': {'readonly': True}, + "code": {"readonly": True}, + "message": {"readonly": True}, + "target": {"readonly": True}, + "details": {"readonly": True}, + "additional_info": {"readonly": True}, } _attribute_map = { - 'code': {'key': 'code', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, - 'target': {'key': 'target', 'type': 'str'}, - 'details': {'key': 'details', 'type': '[ErrorResponse]'}, - 'additional_info': {'key': 'additionalInfo', 'type': '[ErrorAdditionalInfo]'}, + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, + "target": {"key": "target", "type": "str"}, + "details": {"key": "details", "type": "[ErrorResponse]"}, + "additional_info": {"key": "additionalInfo", "type": "[ErrorAdditionalInfo]"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(ErrorResponse, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.code = None self.message = None self.target = None @@ -804,54 +761,54 @@ class FirewallRule(ProxyResource): :vartype type: str :ivar system_data: The system metadata relating to this resource. :vartype system_data: ~azure.mgmt.rdbms.mysql_flexibleservers.models.SystemData - :ivar start_ip_address: Required. The start IP address of the server firewall rule. Must be - IPv4 format. + :ivar start_ip_address: The start IP address of the server firewall rule. Must be IPv4 format. + Required. :vartype start_ip_address: str - :ivar end_ip_address: Required. The end IP address of the server firewall rule. Must be IPv4 - format. + :ivar end_ip_address: The end IP address of the server firewall rule. Must be IPv4 format. + Required. :vartype end_ip_address: str """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'system_data': {'readonly': True}, - 'start_ip_address': {'required': True, 'pattern': r'^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$'}, - 'end_ip_address': {'required': True, 'pattern': r'^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$'}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "system_data": {"readonly": True}, + "start_ip_address": { + "required": True, + "pattern": r"^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$", + }, + "end_ip_address": { + "required": True, + "pattern": r"^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$", + }, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'system_data': {'key': 'systemData', 'type': 'SystemData'}, - 'start_ip_address': {'key': 'properties.startIpAddress', 'type': 'str'}, - 'end_ip_address': {'key': 'properties.endIpAddress', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + "start_ip_address": {"key": "properties.startIpAddress", "type": "str"}, + "end_ip_address": {"key": "properties.endIpAddress", "type": "str"}, } - def __init__( - self, - *, - start_ip_address: str, - end_ip_address: str, - **kwargs - ): + def __init__(self, *, start_ip_address: str, end_ip_address: str, **kwargs): """ - :keyword start_ip_address: Required. The start IP address of the server firewall rule. Must be - IPv4 format. + :keyword start_ip_address: The start IP address of the server firewall rule. Must be IPv4 + format. Required. :paramtype start_ip_address: str - :keyword end_ip_address: Required. The end IP address of the server firewall rule. Must be IPv4 - format. + :keyword end_ip_address: The end IP address of the server firewall rule. Must be IPv4 format. + Required. :paramtype end_ip_address: str """ - super(FirewallRule, self).__init__(**kwargs) + super().__init__(**kwargs) self.system_data = None self.start_ip_address = start_ip_address self.end_ip_address = end_ip_address -class FirewallRuleListResult(msrest.serialization.Model): +class FirewallRuleListResult(_serialization.Model): """A list of firewall rules. :ivar value: The list of firewall rules in a server. @@ -861,16 +818,12 @@ class FirewallRuleListResult(msrest.serialization.Model): """ _attribute_map = { - 'value': {'key': 'value', 'type': '[FirewallRule]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[FirewallRule]"}, + "next_link": {"key": "nextLink", "type": "str"}, } def __init__( - self, - *, - value: Optional[List["_models.FirewallRule"]] = None, - next_link: Optional[str] = None, - **kwargs + self, *, value: Optional[List["_models.FirewallRule"]] = None, next_link: Optional[str] = None, **kwargs ): """ :keyword value: The list of firewall rules in a server. @@ -878,12 +831,12 @@ def __init__( :keyword next_link: The link used to get the next page of operations. :paramtype next_link: str """ - super(FirewallRuleListResult, self).__init__(**kwargs) + super().__init__(**kwargs) self.value = value self.next_link = next_link -class GetPrivateDnsZoneSuffixResponse(msrest.serialization.Model): +class GetPrivateDnsZoneSuffixResponse(_serialization.Model): """The response of get private dns zone suffix. :ivar private_dns_zone_suffix: Represents the private DNS zone suffix. @@ -891,46 +844,41 @@ class GetPrivateDnsZoneSuffixResponse(msrest.serialization.Model): """ _attribute_map = { - 'private_dns_zone_suffix': {'key': 'privateDnsZoneSuffix', 'type': 'str'}, + "private_dns_zone_suffix": {"key": "privateDnsZoneSuffix", "type": "str"}, } - def __init__( - self, - *, - private_dns_zone_suffix: Optional[str] = None, - **kwargs - ): + def __init__(self, *, private_dns_zone_suffix: Optional[str] = None, **kwargs): """ :keyword private_dns_zone_suffix: Represents the private DNS zone suffix. :paramtype private_dns_zone_suffix: str """ - super(GetPrivateDnsZoneSuffixResponse, self).__init__(**kwargs) + super().__init__(**kwargs) self.private_dns_zone_suffix = private_dns_zone_suffix -class HighAvailability(msrest.serialization.Model): +class HighAvailability(_serialization.Model): """Network related properties of a server. Variables are only populated by the server, and will be ignored when sending a request. :ivar mode: High availability mode for a server. Known values are: "Disabled", "ZoneRedundant", - "SameZone". + and "SameZone". :vartype mode: str or ~azure.mgmt.rdbms.mysql_flexibleservers.models.HighAvailabilityMode :ivar state: The state of server high availability. Known values are: "NotEnabled", - "CreatingStandby", "Healthy", "FailingOver", "RemovingStandby". + "CreatingStandby", "Healthy", "FailingOver", and "RemovingStandby". :vartype state: str or ~azure.mgmt.rdbms.mysql_flexibleservers.models.HighAvailabilityState :ivar standby_availability_zone: Availability zone of the standby server. :vartype standby_availability_zone: str """ _validation = { - 'state': {'readonly': True}, + "state": {"readonly": True}, } _attribute_map = { - 'mode': {'key': 'mode', 'type': 'str'}, - 'state': {'key': 'state', 'type': 'str'}, - 'standby_availability_zone': {'key': 'standbyAvailabilityZone', 'type': 'str'}, + "mode": {"key": "mode", "type": "str"}, + "state": {"key": "state", "type": "str"}, + "standby_availability_zone": {"key": "standbyAvailabilityZone", "type": "str"}, } def __init__( @@ -942,18 +890,18 @@ def __init__( ): """ :keyword mode: High availability mode for a server. Known values are: "Disabled", - "ZoneRedundant", "SameZone". + "ZoneRedundant", and "SameZone". :paramtype mode: str or ~azure.mgmt.rdbms.mysql_flexibleservers.models.HighAvailabilityMode :keyword standby_availability_zone: Availability zone of the standby server. :paramtype standby_availability_zone: str """ - super(HighAvailability, self).__init__(**kwargs) + super().__init__(**kwargs) self.mode = mode self.state = None self.standby_availability_zone = standby_availability_zone -class Identity(msrest.serialization.Model): +class Identity(_serialization.Model): """Properties to configure Identity for Bring your Own Keys. Variables are only populated by the server, and will be ignored when sending a request. @@ -962,40 +910,34 @@ class Identity(msrest.serialization.Model): :vartype principal_id: str :ivar tenant_id: TenantId from the KeyVault. :vartype tenant_id: str - :ivar type: Type of managed service identity. The only acceptable values to pass in are None - and "UserAssigned". The default value is None. + :ivar type: Type of managed service identity. Default value is "UserAssigned". :vartype type: str :ivar user_assigned_identities: Metadata of user assigned identity. - :vartype user_assigned_identities: dict[str, any] + :vartype user_assigned_identities: dict[str, JSON] """ _validation = { - 'principal_id': {'readonly': True}, - 'tenant_id': {'readonly': True}, + "principal_id": {"readonly": True}, + "tenant_id": {"readonly": 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': '{object}'}, + "principal_id": {"key": "principalId", "type": "str"}, + "tenant_id": {"key": "tenantId", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "user_assigned_identities": {"key": "userAssignedIdentities", "type": "{object}"}, } def __init__( - self, - *, - type: Optional[str] = None, - user_assigned_identities: Optional[Dict[str, Any]] = None, - **kwargs + self, *, type: Optional[str] = None, user_assigned_identities: Optional[Dict[str, JSON]] = None, **kwargs ): """ - :keyword type: Type of managed service identity. The only acceptable values to pass in are None - and "UserAssigned". The default value is None. + :keyword type: Type of managed service identity. Default value is "UserAssigned". :paramtype type: str :keyword user_assigned_identities: Metadata of user assigned identity. - :paramtype user_assigned_identities: dict[str, any] + :paramtype user_assigned_identities: dict[str, JSON] """ - super(Identity, self).__init__(**kwargs) + super().__init__(**kwargs) self.principal_id = None self.tenant_id = None self.type = type @@ -1018,7 +960,7 @@ class LogFile(ProxyResource): :ivar system_data: The system metadata relating to this resource. :vartype system_data: ~azure.mgmt.rdbms.mysql_flexibleservers.models.SystemData :ivar size_in_kb: The size in kb of the logFile. - :vartype size_in_kb: long + :vartype size_in_kb: int :ivar created_time: Creation timestamp of the log file. :vartype created_time: ~datetime.datetime :ivar type_properties_type: Type of the log file. @@ -1030,22 +972,22 @@ class LogFile(ProxyResource): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'system_data': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "system_data": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'system_data': {'key': 'systemData', 'type': 'SystemData'}, - 'size_in_kb': {'key': 'properties.sizeInKB', 'type': 'long'}, - 'created_time': {'key': 'properties.createdTime', 'type': 'iso-8601'}, - 'type_properties_type': {'key': 'properties.type', 'type': 'str'}, - 'last_modified_time': {'key': 'properties.lastModifiedTime', 'type': 'iso-8601'}, - 'url': {'key': 'properties.url', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + "size_in_kb": {"key": "properties.sizeInKB", "type": "int"}, + "created_time": {"key": "properties.createdTime", "type": "iso-8601"}, + "type_properties_type": {"key": "properties.type", "type": "str"}, + "last_modified_time": {"key": "properties.lastModifiedTime", "type": "iso-8601"}, + "url": {"key": "properties.url", "type": "str"}, } def __init__( @@ -1060,7 +1002,7 @@ def __init__( ): """ :keyword size_in_kb: The size in kb of the logFile. - :paramtype size_in_kb: long + :paramtype size_in_kb: int :keyword created_time: Creation timestamp of the log file. :paramtype created_time: ~datetime.datetime :keyword type_properties_type: Type of the log file. @@ -1070,7 +1012,7 @@ def __init__( :keyword url: The url to download the log file from. :paramtype url: str """ - super(LogFile, self).__init__(**kwargs) + super().__init__(**kwargs) self.system_data = None self.size_in_kb = size_in_kb self.created_time = created_time @@ -1079,7 +1021,7 @@ def __init__( self.url = url -class LogFileListResult(msrest.serialization.Model): +class LogFileListResult(_serialization.Model): """A List of logFiles. :ivar value: The list of logFiles in a server. @@ -1089,29 +1031,23 @@ class LogFileListResult(msrest.serialization.Model): """ _attribute_map = { - 'value': {'key': 'value', 'type': '[LogFile]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[LogFile]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - *, - value: Optional[List["_models.LogFile"]] = None, - next_link: Optional[str] = None, - **kwargs - ): + def __init__(self, *, value: Optional[List["_models.LogFile"]] = None, next_link: Optional[str] = None, **kwargs): """ :keyword value: The list of logFiles in a server. :paramtype value: list[~azure.mgmt.rdbms.mysql_flexibleservers.models.LogFile] :keyword next_link: The link used to get the next page of operations. :paramtype next_link: str """ - super(LogFileListResult, self).__init__(**kwargs) + super().__init__(**kwargs) self.value = value self.next_link = next_link -class MaintenanceWindow(msrest.serialization.Model): +class MaintenanceWindow(_serialization.Model): """Maintenance window of a server. :ivar custom_window: indicates whether custom window is enabled or disabled. @@ -1125,10 +1061,10 @@ class MaintenanceWindow(msrest.serialization.Model): """ _attribute_map = { - 'custom_window': {'key': 'customWindow', 'type': 'str'}, - 'start_hour': {'key': 'startHour', 'type': 'int'}, - 'start_minute': {'key': 'startMinute', 'type': 'int'}, - 'day_of_week': {'key': 'dayOfWeek', 'type': 'int'}, + "custom_window": {"key": "customWindow", "type": "str"}, + "start_hour": {"key": "startHour", "type": "int"}, + "start_minute": {"key": "startMinute", "type": "int"}, + "day_of_week": {"key": "dayOfWeek", "type": "int"}, } def __init__( @@ -1150,14 +1086,14 @@ def __init__( :keyword day_of_week: day of week for maintenance window. :paramtype day_of_week: int """ - super(MaintenanceWindow, self).__init__(**kwargs) + super().__init__(**kwargs) self.custom_window = custom_window self.start_hour = start_hour self.start_minute = start_minute self.day_of_week = day_of_week -class NameAvailability(msrest.serialization.Model): +class NameAvailability(_serialization.Model): """Represents a resource name availability. :ivar message: Error Message. @@ -1169,9 +1105,9 @@ class NameAvailability(msrest.serialization.Model): """ _attribute_map = { - 'message': {'key': 'message', 'type': 'str'}, - 'name_available': {'key': 'nameAvailable', 'type': 'bool'}, - 'reason': {'key': 'reason', 'type': 'str'}, + "message": {"key": "message", "type": "str"}, + "name_available": {"key": "nameAvailable", "type": "bool"}, + "reason": {"key": "reason", "type": "str"}, } def __init__( @@ -1190,57 +1126,52 @@ def __init__( :keyword reason: Reason for name being unavailable. :paramtype reason: str """ - super(NameAvailability, self).__init__(**kwargs) + super().__init__(**kwargs) self.message = message self.name_available = name_available self.reason = reason -class NameAvailabilityRequest(msrest.serialization.Model): +class NameAvailabilityRequest(_serialization.Model): """Request from client to check resource name availability. All required parameters must be populated in order to send to Azure. - :ivar name: Required. Resource name to verify. + :ivar name: Resource name to verify. Required. :vartype name: str :ivar type: Resource type used for verification. :vartype type: str """ _validation = { - 'name': {'required': True}, + "name": {"required": True}, } _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, } - def __init__( - self, - *, - name: str, - type: Optional[str] = None, - **kwargs - ): + def __init__(self, *, name: str, type: Optional[str] = None, **kwargs): """ - :keyword name: Required. Resource name to verify. + :keyword name: Resource name to verify. Required. :paramtype name: str :keyword type: Resource type used for verification. :paramtype type: str """ - super(NameAvailabilityRequest, self).__init__(**kwargs) + super().__init__(**kwargs) self.name = name self.type = type -class Network(msrest.serialization.Model): +class Network(_serialization.Model): """Network related properties of a server. Variables are only populated by the server, and will be ignored when sending a request. :ivar public_network_access: Whether or not public network access is allowed for this server. - Value is 'Disabled' when server has VNet integration. Known values are: "Enabled", "Disabled". + Value is 'Disabled' when server has VNet integration. Known values are: "Enabled" and + "Disabled". :vartype public_network_access: str or ~azure.mgmt.rdbms.mysql_flexibleservers.models.EnableStatusEnum :ivar delegated_subnet_resource_id: Delegated subnet resource id used to setup vnet for a @@ -1251,13 +1182,13 @@ class Network(msrest.serialization.Model): """ _validation = { - 'public_network_access': {'readonly': True}, + "public_network_access": {"readonly": True}, } _attribute_map = { - 'public_network_access': {'key': 'publicNetworkAccess', 'type': 'str'}, - 'delegated_subnet_resource_id': {'key': 'delegatedSubnetResourceId', 'type': 'str'}, - 'private_dns_zone_resource_id': {'key': 'privateDnsZoneResourceId', 'type': 'str'}, + "public_network_access": {"key": "publicNetworkAccess", "type": "str"}, + "delegated_subnet_resource_id": {"key": "delegatedSubnetResourceId", "type": "str"}, + "private_dns_zone_resource_id": {"key": "privateDnsZoneResourceId", "type": "str"}, } def __init__( @@ -1274,13 +1205,13 @@ def __init__( :keyword private_dns_zone_resource_id: Private DNS zone resource id. :paramtype private_dns_zone_resource_id: str """ - super(Network, self).__init__(**kwargs) + super().__init__(**kwargs) self.public_network_access = None self.delegated_subnet_resource_id = delegated_subnet_resource_id self.private_dns_zone_resource_id = private_dns_zone_resource_id -class Operation(msrest.serialization.Model): +class Operation(_serialization.Model): """REST API operation definition. :ivar name: The name of the operation being performed on this particular object. @@ -1290,14 +1221,14 @@ class Operation(msrest.serialization.Model): :ivar origin: The intended executor of the operation. :vartype origin: str :ivar properties: Additional descriptions for the operation. - :vartype properties: dict[str, any] + :vartype properties: dict[str, JSON] """ _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'display': {'key': 'display', 'type': 'OperationDisplay'}, - 'origin': {'key': 'origin', 'type': 'str'}, - 'properties': {'key': 'properties', 'type': '{object}'}, + "name": {"key": "name", "type": "str"}, + "display": {"key": "display", "type": "OperationDisplay"}, + "origin": {"key": "origin", "type": "str"}, + "properties": {"key": "properties", "type": "{object}"}, } def __init__( @@ -1306,7 +1237,7 @@ def __init__( name: Optional[str] = None, display: Optional["_models.OperationDisplay"] = None, origin: Optional[str] = None, - properties: Optional[Dict[str, Any]] = None, + properties: Optional[Dict[str, JSON]] = None, **kwargs ): """ @@ -1317,16 +1248,16 @@ def __init__( :keyword origin: The intended executor of the operation. :paramtype origin: str :keyword properties: Additional descriptions for the operation. - :paramtype properties: dict[str, any] + :paramtype properties: dict[str, JSON] """ - super(Operation, self).__init__(**kwargs) + super().__init__(**kwargs) self.name = name self.display = display self.origin = origin self.properties = properties -class OperationDisplay(msrest.serialization.Model): +class OperationDisplay(_serialization.Model): """Display metadata associated with the operation. :ivar provider: Operation resource provider name. @@ -1340,10 +1271,10 @@ class OperationDisplay(msrest.serialization.Model): """ _attribute_map = { - 'provider': {'key': 'provider', 'type': 'str'}, - 'resource': {'key': 'resource', 'type': 'str'}, - 'operation': {'key': 'operation', 'type': 'str'}, - 'description': {'key': 'description', 'type': 'str'}, + "provider": {"key": "provider", "type": "str"}, + "resource": {"key": "resource", "type": "str"}, + "operation": {"key": "operation", "type": "str"}, + "description": {"key": "description", "type": "str"}, } def __init__( @@ -1365,14 +1296,14 @@ def __init__( :keyword description: Operation description. :paramtype description: str """ - super(OperationDisplay, self).__init__(**kwargs) + super().__init__(**kwargs) self.provider = provider self.resource = resource self.operation = operation self.description = description -class OperationListResult(msrest.serialization.Model): +class OperationListResult(_serialization.Model): """A list of resource provider operations. :ivar value: Collection of available operation details. @@ -1382,24 +1313,18 @@ class OperationListResult(msrest.serialization.Model): """ _attribute_map = { - 'value': {'key': 'value', 'type': '[Operation]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[Operation]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - *, - value: Optional[List["_models.Operation"]] = None, - next_link: Optional[str] = None, - **kwargs - ): + def __init__(self, *, value: Optional[List["_models.Operation"]] = None, next_link: Optional[str] = None, **kwargs): """ :keyword value: Collection of available operation details. :paramtype value: list[~azure.mgmt.rdbms.mysql_flexibleservers.models.Operation] :keyword next_link: URL client should use to fetch the next page (per server side paging). :paramtype next_link: str """ - super(OperationListResult, self).__init__(**kwargs) + super().__init__(**kwargs) self.value = value self.next_link = next_link @@ -1419,46 +1344,40 @@ class TrackedResource(Resource): :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts". :vartype type: str - :ivar tags: A set of tags. Resource tags. + :ivar tags: Resource tags. :vartype tags: dict[str, str] - :ivar location: Required. The geo-location where the resource lives. + :ivar location: The geo-location where the resource lives. Required. :vartype location: str """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'location': {'required': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "location": {"required": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - 'location': {'key': 'location', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "location": {"key": "location", "type": "str"}, } - def __init__( - self, - *, - location: str, - tags: Optional[Dict[str, str]] = None, - **kwargs - ): + def __init__(self, *, location: str, tags: Optional[Dict[str, str]] = None, **kwargs): """ - :keyword tags: A set of tags. Resource tags. + :keyword tags: Resource tags. :paramtype tags: dict[str, str] - :keyword location: Required. The geo-location where the resource lives. + :keyword location: The geo-location where the resource lives. Required. :paramtype location: str """ - super(TrackedResource, self).__init__(**kwargs) + super().__init__(**kwargs) self.tags = tags self.location = location -class Server(TrackedResource): +class Server(TrackedResource): # pylint: disable=too-many-instance-attributes """Represents a server. Variables are only populated by the server, and will be ignored when sending a request. @@ -1473,9 +1392,9 @@ class Server(TrackedResource): :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts". :vartype type: str - :ivar tags: A set of tags. Resource tags. + :ivar tags: Resource tags. :vartype tags: dict[str, str] - :ivar location: Required. The geo-location where the resource lives. + :ivar location: The geo-location where the resource lives. Required. :vartype location: str :ivar identity: The cmk identity for the server. :vartype identity: ~azure.mgmt.rdbms.mysql_flexibleservers.models.Identity @@ -1489,19 +1408,20 @@ class Server(TrackedResource): :ivar administrator_login_password: The password of the administrator login (required for server creation). :vartype administrator_login_password: str - :ivar version: Server version. Known values are: "5.7", "8.0.21". + :ivar version: Server version. Known values are: "5.7" and "8.0.21". :vartype version: str or ~azure.mgmt.rdbms.mysql_flexibleservers.models.ServerVersion :ivar availability_zone: availability Zone information of the server. :vartype availability_zone: str :ivar create_mode: The mode to create a new MySQL server. Known values are: "Default", - "PointInTimeRestore", "Replica", "GeoRestore". + "PointInTimeRestore", "Replica", and "GeoRestore". :vartype create_mode: str or ~azure.mgmt.rdbms.mysql_flexibleservers.models.CreateMode :ivar source_server_resource_id: The source MySQL server id. :vartype source_server_resource_id: str :ivar restore_point_in_time: Restore point creation time (ISO8601 format), specifying the time to restore from. :vartype restore_point_in_time: ~datetime.datetime - :ivar replication_role: The replication role. Known values are: "None", "Source", "Replica". + :ivar replication_role: The replication role. Known values are: "None", "Source", and + "Replica". :vartype replication_role: str or ~azure.mgmt.rdbms.mysql_flexibleservers.models.ReplicationRole :ivar replica_capacity: The maximum number of replicas that a primary server can have. @@ -1509,7 +1429,7 @@ class Server(TrackedResource): :ivar data_encryption: The Data Encryption for CMK. :vartype data_encryption: ~azure.mgmt.rdbms.mysql_flexibleservers.models.DataEncryption :ivar state: The state of a server. Known values are: "Ready", "Dropping", "Disabled", - "Starting", "Stopping", "Stopped", "Updating". + "Starting", "Stopping", "Stopped", and "Updating". :vartype state: str or ~azure.mgmt.rdbms.mysql_flexibleservers.models.ServerState :ivar fully_qualified_domain_name: The fully qualified domain name of a server. :vartype fully_qualified_domain_name: str @@ -1526,45 +1446,45 @@ class Server(TrackedResource): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'location': {'required': True}, - 'system_data': {'readonly': True}, - 'replica_capacity': {'readonly': True, 'minimum': 0}, - 'state': {'readonly': True}, - 'fully_qualified_domain_name': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "location": {"required": True}, + "system_data": {"readonly": True}, + "replica_capacity": {"readonly": True, "minimum": 0}, + "state": {"readonly": True}, + "fully_qualified_domain_name": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - 'location': {'key': 'location', 'type': 'str'}, - 'identity': {'key': 'identity', 'type': 'Identity'}, - 'sku': {'key': 'sku', 'type': 'Sku'}, - 'system_data': {'key': 'systemData', 'type': 'SystemData'}, - 'administrator_login': {'key': 'properties.administratorLogin', 'type': 'str'}, - 'administrator_login_password': {'key': 'properties.administratorLoginPassword', 'type': 'str'}, - 'version': {'key': 'properties.version', 'type': 'str'}, - 'availability_zone': {'key': 'properties.availabilityZone', 'type': 'str'}, - 'create_mode': {'key': 'properties.createMode', 'type': 'str'}, - 'source_server_resource_id': {'key': 'properties.sourceServerResourceId', 'type': 'str'}, - 'restore_point_in_time': {'key': 'properties.restorePointInTime', 'type': 'iso-8601'}, - 'replication_role': {'key': 'properties.replicationRole', 'type': 'str'}, - 'replica_capacity': {'key': 'properties.replicaCapacity', 'type': 'int'}, - 'data_encryption': {'key': 'properties.dataEncryption', 'type': 'DataEncryption'}, - 'state': {'key': 'properties.state', 'type': 'str'}, - 'fully_qualified_domain_name': {'key': 'properties.fullyQualifiedDomainName', 'type': 'str'}, - 'storage': {'key': 'properties.storage', 'type': 'Storage'}, - 'backup': {'key': 'properties.backup', 'type': 'Backup'}, - 'high_availability': {'key': 'properties.highAvailability', 'type': 'HighAvailability'}, - 'network': {'key': 'properties.network', 'type': 'Network'}, - 'maintenance_window': {'key': 'properties.maintenanceWindow', 'type': 'MaintenanceWindow'}, - } - - def __init__( + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "location": {"key": "location", "type": "str"}, + "identity": {"key": "identity", "type": "Identity"}, + "sku": {"key": "sku", "type": "Sku"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + "administrator_login": {"key": "properties.administratorLogin", "type": "str"}, + "administrator_login_password": {"key": "properties.administratorLoginPassword", "type": "str"}, + "version": {"key": "properties.version", "type": "str"}, + "availability_zone": {"key": "properties.availabilityZone", "type": "str"}, + "create_mode": {"key": "properties.createMode", "type": "str"}, + "source_server_resource_id": {"key": "properties.sourceServerResourceId", "type": "str"}, + "restore_point_in_time": {"key": "properties.restorePointInTime", "type": "iso-8601"}, + "replication_role": {"key": "properties.replicationRole", "type": "str"}, + "replica_capacity": {"key": "properties.replicaCapacity", "type": "int"}, + "data_encryption": {"key": "properties.dataEncryption", "type": "DataEncryption"}, + "state": {"key": "properties.state", "type": "str"}, + "fully_qualified_domain_name": {"key": "properties.fullyQualifiedDomainName", "type": "str"}, + "storage": {"key": "properties.storage", "type": "Storage"}, + "backup": {"key": "properties.backup", "type": "Backup"}, + "high_availability": {"key": "properties.highAvailability", "type": "HighAvailability"}, + "network": {"key": "properties.network", "type": "Network"}, + "maintenance_window": {"key": "properties.maintenanceWindow", "type": "MaintenanceWindow"}, + } + + def __init__( # pylint: disable=too-many-locals self, *, location: str, @@ -1588,9 +1508,9 @@ def __init__( **kwargs ): """ - :keyword tags: A set of tags. Resource tags. + :keyword tags: Resource tags. :paramtype tags: dict[str, str] - :keyword location: Required. The geo-location where the resource lives. + :keyword location: The geo-location where the resource lives. Required. :paramtype location: str :keyword identity: The cmk identity for the server. :paramtype identity: ~azure.mgmt.rdbms.mysql_flexibleservers.models.Identity @@ -1602,19 +1522,20 @@ def __init__( :keyword administrator_login_password: The password of the administrator login (required for server creation). :paramtype administrator_login_password: str - :keyword version: Server version. Known values are: "5.7", "8.0.21". + :keyword version: Server version. Known values are: "5.7" and "8.0.21". :paramtype version: str or ~azure.mgmt.rdbms.mysql_flexibleservers.models.ServerVersion :keyword availability_zone: availability Zone information of the server. :paramtype availability_zone: str :keyword create_mode: The mode to create a new MySQL server. Known values are: "Default", - "PointInTimeRestore", "Replica", "GeoRestore". + "PointInTimeRestore", "Replica", and "GeoRestore". :paramtype create_mode: str or ~azure.mgmt.rdbms.mysql_flexibleservers.models.CreateMode :keyword source_server_resource_id: The source MySQL server id. :paramtype source_server_resource_id: str :keyword restore_point_in_time: Restore point creation time (ISO8601 format), specifying the time to restore from. :paramtype restore_point_in_time: ~datetime.datetime - :keyword replication_role: The replication role. Known values are: "None", "Source", "Replica". + :keyword replication_role: The replication role. Known values are: "None", "Source", and + "Replica". :paramtype replication_role: str or ~azure.mgmt.rdbms.mysql_flexibleservers.models.ReplicationRole :keyword data_encryption: The Data Encryption for CMK. @@ -1630,7 +1551,7 @@ def __init__( :keyword maintenance_window: Maintenance window of a server. :paramtype maintenance_window: ~azure.mgmt.rdbms.mysql_flexibleservers.models.MaintenanceWindow """ - super(Server, self).__init__(tags=tags, location=location, **kwargs) + super().__init__(tags=tags, location=location, **kwargs) self.identity = identity self.sku = sku self.system_data = None @@ -1677,20 +1598,20 @@ class ServerBackup(ProxyResource): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'system_data': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "system_data": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'system_data': {'key': 'systemData', 'type': 'SystemData'}, - 'backup_type': {'key': 'properties.backupType', 'type': 'str'}, - 'completed_time': {'key': 'properties.completedTime', 'type': 'iso-8601'}, - 'source': {'key': 'properties.source', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + "backup_type": {"key": "properties.backupType", "type": "str"}, + "completed_time": {"key": "properties.completedTime", "type": "iso-8601"}, + "source": {"key": "properties.source", "type": "str"}, } def __init__( @@ -1709,14 +1630,14 @@ def __init__( :keyword source: Backup source. :paramtype source: str """ - super(ServerBackup, self).__init__(**kwargs) + super().__init__(**kwargs) self.system_data = None self.backup_type = backup_type self.completed_time = completed_time self.source = source -class ServerBackupListResult(msrest.serialization.Model): +class ServerBackupListResult(_serialization.Model): """A list of server backups. :ivar value: The list of backups of a server. @@ -1726,16 +1647,12 @@ class ServerBackupListResult(msrest.serialization.Model): """ _attribute_map = { - 'value': {'key': 'value', 'type': '[ServerBackup]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[ServerBackup]"}, + "next_link": {"key": "nextLink", "type": "str"}, } def __init__( - self, - *, - value: Optional[List["_models.ServerBackup"]] = None, - next_link: Optional[str] = None, - **kwargs + self, *, value: Optional[List["_models.ServerBackup"]] = None, next_link: Optional[str] = None, **kwargs ): """ :keyword value: The list of backups of a server. @@ -1743,12 +1660,12 @@ def __init__( :keyword next_link: The link used to get the next page of operations. :paramtype next_link: str """ - super(ServerBackupListResult, self).__init__(**kwargs) + super().__init__(**kwargs) self.value = value self.next_link = next_link -class ServerEditionCapability(msrest.serialization.Model): +class ServerEditionCapability(_serialization.Model): """Server edition capabilities. Variables are only populated by the server, and will be ignored when sending a request. @@ -1764,41 +1681,37 @@ class ServerEditionCapability(msrest.serialization.Model): """ _validation = { - 'name': {'readonly': True}, - 'supported_storage_editions': {'readonly': True}, - 'supported_server_versions': {'readonly': True}, + "name": {"readonly": True}, + "supported_storage_editions": {"readonly": True}, + "supported_server_versions": {"readonly": True}, } _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'supported_storage_editions': {'key': 'supportedStorageEditions', 'type': '[StorageEditionCapability]'}, - 'supported_server_versions': {'key': 'supportedServerVersions', 'type': '[ServerVersionCapability]'}, + "name": {"key": "name", "type": "str"}, + "supported_storage_editions": {"key": "supportedStorageEditions", "type": "[StorageEditionCapability]"}, + "supported_server_versions": {"key": "supportedServerVersions", "type": "[ServerVersionCapability]"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(ServerEditionCapability, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.name = None self.supported_storage_editions = None self.supported_server_versions = None -class ServerForUpdate(msrest.serialization.Model): +class ServerForUpdate(_serialization.Model): # pylint: disable=too-many-instance-attributes """Parameters allowed to update for a server. :ivar identity: The cmk identity for the server. :vartype identity: ~azure.mgmt.rdbms.mysql_flexibleservers.models.Identity :ivar sku: The SKU (pricing tier) of the server. :vartype sku: ~azure.mgmt.rdbms.mysql_flexibleservers.models.Sku - :ivar tags: A set of tags. Application-specific metadata in the form of key-value pairs. + :ivar tags: Application-specific metadata in the form of key-value pairs. :vartype tags: dict[str, str] :ivar administrator_login_password: The password of the administrator login. :vartype administrator_login_password: str - :ivar version: Server version. Known values are: "5.7", "8.0.21". + :ivar version: Server version. Known values are: "5.7" and "8.0.21". :vartype version: str or ~azure.mgmt.rdbms.mysql_flexibleservers.models.ServerVersion :ivar storage: Storage related properties of a server. :vartype storage: ~azure.mgmt.rdbms.mysql_flexibleservers.models.Storage @@ -1809,7 +1722,7 @@ class ServerForUpdate(msrest.serialization.Model): :ivar maintenance_window: Maintenance window of a server. :vartype maintenance_window: ~azure.mgmt.rdbms.mysql_flexibleservers.models.MaintenanceWindow :ivar replication_role: The replication role of the server. Known values are: "None", "Source", - "Replica". + and "Replica". :vartype replication_role: str or ~azure.mgmt.rdbms.mysql_flexibleservers.models.ReplicationRole :ivar data_encryption: The Data Encryption for CMK. @@ -1817,17 +1730,17 @@ class ServerForUpdate(msrest.serialization.Model): """ _attribute_map = { - 'identity': {'key': 'identity', 'type': 'Identity'}, - 'sku': {'key': 'sku', 'type': 'Sku'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - 'administrator_login_password': {'key': 'properties.administratorLoginPassword', 'type': 'str'}, - 'version': {'key': 'properties.version', 'type': 'str'}, - 'storage': {'key': 'properties.storage', 'type': 'Storage'}, - 'backup': {'key': 'properties.backup', 'type': 'Backup'}, - 'high_availability': {'key': 'properties.highAvailability', 'type': 'HighAvailability'}, - 'maintenance_window': {'key': 'properties.maintenanceWindow', 'type': 'MaintenanceWindow'}, - 'replication_role': {'key': 'properties.replicationRole', 'type': 'str'}, - 'data_encryption': {'key': 'properties.dataEncryption', 'type': 'DataEncryption'}, + "identity": {"key": "identity", "type": "Identity"}, + "sku": {"key": "sku", "type": "Sku"}, + "tags": {"key": "tags", "type": "{str}"}, + "administrator_login_password": {"key": "properties.administratorLoginPassword", "type": "str"}, + "version": {"key": "properties.version", "type": "str"}, + "storage": {"key": "properties.storage", "type": "Storage"}, + "backup": {"key": "properties.backup", "type": "Backup"}, + "high_availability": {"key": "properties.highAvailability", "type": "HighAvailability"}, + "maintenance_window": {"key": "properties.maintenanceWindow", "type": "MaintenanceWindow"}, + "replication_role": {"key": "properties.replicationRole", "type": "str"}, + "data_encryption": {"key": "properties.dataEncryption", "type": "DataEncryption"}, } def __init__( @@ -1851,11 +1764,11 @@ def __init__( :paramtype identity: ~azure.mgmt.rdbms.mysql_flexibleservers.models.Identity :keyword sku: The SKU (pricing tier) of the server. :paramtype sku: ~azure.mgmt.rdbms.mysql_flexibleservers.models.Sku - :keyword tags: A set of tags. Application-specific metadata in the form of key-value pairs. + :keyword tags: Application-specific metadata in the form of key-value pairs. :paramtype tags: dict[str, str] :keyword administrator_login_password: The password of the administrator login. :paramtype administrator_login_password: str - :keyword version: Server version. Known values are: "5.7", "8.0.21". + :keyword version: Server version. Known values are: "5.7" and "8.0.21". :paramtype version: str or ~azure.mgmt.rdbms.mysql_flexibleservers.models.ServerVersion :keyword storage: Storage related properties of a server. :paramtype storage: ~azure.mgmt.rdbms.mysql_flexibleservers.models.Storage @@ -1866,13 +1779,13 @@ def __init__( :keyword maintenance_window: Maintenance window of a server. :paramtype maintenance_window: ~azure.mgmt.rdbms.mysql_flexibleservers.models.MaintenanceWindow :keyword replication_role: The replication role of the server. Known values are: "None", - "Source", "Replica". + "Source", and "Replica". :paramtype replication_role: str or ~azure.mgmt.rdbms.mysql_flexibleservers.models.ReplicationRole :keyword data_encryption: The Data Encryption for CMK. :paramtype data_encryption: ~azure.mgmt.rdbms.mysql_flexibleservers.models.DataEncryption """ - super(ServerForUpdate, self).__init__(**kwargs) + super().__init__(**kwargs) self.identity = identity self.sku = sku self.tags = tags @@ -1886,7 +1799,7 @@ def __init__( self.data_encryption = data_encryption -class ServerListResult(msrest.serialization.Model): +class ServerListResult(_serialization.Model): """A list of servers. :ivar value: The list of servers. @@ -1896,33 +1809,27 @@ class ServerListResult(msrest.serialization.Model): """ _attribute_map = { - 'value': {'key': 'value', 'type': '[Server]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[Server]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - *, - value: Optional[List["_models.Server"]] = None, - next_link: Optional[str] = None, - **kwargs - ): + def __init__(self, *, value: Optional[List["_models.Server"]] = None, next_link: Optional[str] = None, **kwargs): """ :keyword value: The list of servers. :paramtype value: list[~azure.mgmt.rdbms.mysql_flexibleservers.models.Server] :keyword next_link: The link used to get the next page of operations. :paramtype next_link: str """ - super(ServerListResult, self).__init__(**kwargs) + super().__init__(**kwargs) self.value = value self.next_link = next_link -class ServerRestartParameter(msrest.serialization.Model): +class ServerRestartParameter(_serialization.Model): """Server restart parameters. :ivar restart_with_failover: Whether or not failover to standby server when restarting a server - with high availability enabled. Known values are: "Enabled", "Disabled". + with high availability enabled. Known values are: "Enabled" and "Disabled". :vartype restart_with_failover: str or ~azure.mgmt.rdbms.mysql_flexibleservers.models.EnableStatusEnum :ivar max_failover_seconds: The maximum allowed failover time in seconds. @@ -1930,8 +1837,8 @@ class ServerRestartParameter(msrest.serialization.Model): """ _attribute_map = { - 'restart_with_failover': {'key': 'restartWithFailover', 'type': 'str'}, - 'max_failover_seconds': {'key': 'maxFailoverSeconds', 'type': 'int'}, + "restart_with_failover": {"key": "restartWithFailover", "type": "str"}, + "max_failover_seconds": {"key": "maxFailoverSeconds", "type": "int"}, } def __init__( @@ -1943,18 +1850,18 @@ def __init__( ): """ :keyword restart_with_failover: Whether or not failover to standby server when restarting a - server with high availability enabled. Known values are: "Enabled", "Disabled". + server with high availability enabled. Known values are: "Enabled" and "Disabled". :paramtype restart_with_failover: str or ~azure.mgmt.rdbms.mysql_flexibleservers.models.EnableStatusEnum :keyword max_failover_seconds: The maximum allowed failover time in seconds. :paramtype max_failover_seconds: int """ - super(ServerRestartParameter, self).__init__(**kwargs) + super().__init__(**kwargs) self.restart_with_failover = restart_with_failover self.max_failover_seconds = max_failover_seconds -class ServerVersionCapability(msrest.serialization.Model): +class ServerVersionCapability(_serialization.Model): """Server version capabilities. Variables are only populated by the server, and will be ignored when sending a request. @@ -1966,68 +1873,58 @@ class ServerVersionCapability(msrest.serialization.Model): """ _validation = { - 'name': {'readonly': True}, - 'supported_skus': {'readonly': True}, + "name": {"readonly": True}, + "supported_skus": {"readonly": True}, } _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'supported_skus': {'key': 'supportedSkus', 'type': '[SkuCapability]'}, + "name": {"key": "name", "type": "str"}, + "supported_skus": {"key": "supportedSkus", "type": "[SkuCapability]"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(ServerVersionCapability, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.name = None self.supported_skus = None -class Sku(msrest.serialization.Model): +class Sku(_serialization.Model): """Billing information related properties of a server. All required parameters must be populated in order to send to Azure. - :ivar name: Required. The name of the sku, e.g. Standard_D32s_v3. + :ivar name: The name of the sku, e.g. Standard_D32s_v3. Required. :vartype name: str - :ivar tier: Required. The tier of the particular SKU, e.g. GeneralPurpose. Known values are: - "Burstable", "GeneralPurpose", "MemoryOptimized". + :ivar tier: The tier of the particular SKU, e.g. GeneralPurpose. Required. Known values are: + "Burstable", "GeneralPurpose", and "MemoryOptimized". :vartype tier: str or ~azure.mgmt.rdbms.mysql_flexibleservers.models.SkuTier """ _validation = { - 'name': {'required': True}, - 'tier': {'required': True}, + "name": {"required": True}, + "tier": {"required": True}, } _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'tier': {'key': 'tier', 'type': 'str'}, + "name": {"key": "name", "type": "str"}, + "tier": {"key": "tier", "type": "str"}, } - def __init__( - self, - *, - name: str, - tier: Union[str, "_models.SkuTier"], - **kwargs - ): + def __init__(self, *, name: str, tier: Union[str, "_models.SkuTier"], **kwargs): """ - :keyword name: Required. The name of the sku, e.g. Standard_D32s_v3. + :keyword name: The name of the sku, e.g. Standard_D32s_v3. Required. :paramtype name: str - :keyword tier: Required. The tier of the particular SKU, e.g. GeneralPurpose. Known values are: - "Burstable", "GeneralPurpose", "MemoryOptimized". + :keyword tier: The tier of the particular SKU, e.g. GeneralPurpose. Required. Known values are: + "Burstable", "GeneralPurpose", and "MemoryOptimized". :paramtype tier: str or ~azure.mgmt.rdbms.mysql_flexibleservers.models.SkuTier """ - super(Sku, self).__init__(**kwargs) + super().__init__(**kwargs) self.name = name self.tier = tier -class SkuCapability(msrest.serialization.Model): +class SkuCapability(_serialization.Model): """Sku capability. Variables are only populated by the server, and will be ignored when sending a request. @@ -2035,41 +1932,37 @@ class SkuCapability(msrest.serialization.Model): :ivar name: vCore name. :vartype name: str :ivar v_cores: supported vCores. - :vartype v_cores: long + :vartype v_cores: int :ivar supported_iops: supported IOPS. - :vartype supported_iops: long + :vartype supported_iops: int :ivar supported_memory_per_v_core_mb: supported memory per vCore in MB. - :vartype supported_memory_per_v_core_mb: long + :vartype supported_memory_per_v_core_mb: int """ _validation = { - 'name': {'readonly': True}, - 'v_cores': {'readonly': True}, - 'supported_iops': {'readonly': True}, - 'supported_memory_per_v_core_mb': {'readonly': True}, + "name": {"readonly": True}, + "v_cores": {"readonly": True}, + "supported_iops": {"readonly": True}, + "supported_memory_per_v_core_mb": {"readonly": True}, } _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'v_cores': {'key': 'vCores', 'type': 'long'}, - 'supported_iops': {'key': 'supportedIops', 'type': 'long'}, - 'supported_memory_per_v_core_mb': {'key': 'supportedMemoryPerVCoreMB', 'type': 'long'}, + "name": {"key": "name", "type": "str"}, + "v_cores": {"key": "vCores", "type": "int"}, + "supported_iops": {"key": "supportedIops", "type": "int"}, + "supported_memory_per_v_core_mb": {"key": "supportedMemoryPerVCoreMB", "type": "int"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(SkuCapability, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.name = None self.v_cores = None self.supported_iops = None self.supported_memory_per_v_core_mb = None -class Storage(msrest.serialization.Model): +class Storage(_serialization.Model): """Storage Profile properties of a server. Variables are only populated by the server, and will be ignored when sending a request. @@ -2078,21 +1971,26 @@ class Storage(msrest.serialization.Model): :vartype storage_size_gb: int :ivar iops: Storage IOPS for a server. :vartype iops: int - :ivar auto_grow: Enable Storage Auto Grow or not. Known values are: "Enabled", "Disabled". + :ivar auto_grow: Enable Storage Auto Grow or not. Known values are: "Enabled" and "Disabled". :vartype auto_grow: str or ~azure.mgmt.rdbms.mysql_flexibleservers.models.EnableStatusEnum :ivar storage_sku: The sku name of the server storage. :vartype storage_sku: str + :ivar auto_io_scaling: Enable IO Auto Scaling or not. Known values are: "Enabled" and + "Disabled". + :vartype auto_io_scaling: str or + ~azure.mgmt.rdbms.mysql_flexibleservers.models.EnableStatusEnum """ _validation = { - 'storage_sku': {'readonly': True}, + "storage_sku": {"readonly": True}, } _attribute_map = { - 'storage_size_gb': {'key': 'storageSizeGB', 'type': 'int'}, - 'iops': {'key': 'iops', 'type': 'int'}, - 'auto_grow': {'key': 'autoGrow', 'type': 'str'}, - 'storage_sku': {'key': 'storageSku', 'type': 'str'}, + "storage_size_gb": {"key": "storageSizeGB", "type": "int"}, + "iops": {"key": "iops", "type": "int"}, + "auto_grow": {"key": "autoGrow", "type": "str"}, + "storage_sku": {"key": "storageSku", "type": "str"}, + "auto_io_scaling": {"key": "autoIoScaling", "type": "str"}, } def __init__( @@ -2101,6 +1999,7 @@ def __init__( storage_size_gb: Optional[int] = None, iops: Optional[int] = None, auto_grow: Optional[Union[str, "_models.EnableStatusEnum"]] = None, + auto_io_scaling: Optional[Union[str, "_models.EnableStatusEnum"]] = None, **kwargs ): """ @@ -2108,17 +2007,23 @@ def __init__( :paramtype storage_size_gb: int :keyword iops: Storage IOPS for a server. :paramtype iops: int - :keyword auto_grow: Enable Storage Auto Grow or not. Known values are: "Enabled", "Disabled". + :keyword auto_grow: Enable Storage Auto Grow or not. Known values are: "Enabled" and + "Disabled". :paramtype auto_grow: str or ~azure.mgmt.rdbms.mysql_flexibleservers.models.EnableStatusEnum + :keyword auto_io_scaling: Enable IO Auto Scaling or not. Known values are: "Enabled" and + "Disabled". + :paramtype auto_io_scaling: str or + ~azure.mgmt.rdbms.mysql_flexibleservers.models.EnableStatusEnum """ - super(Storage, self).__init__(**kwargs) + super().__init__(**kwargs) self.storage_size_gb = storage_size_gb self.iops = iops self.auto_grow = auto_grow self.storage_sku = None + self.auto_io_scaling = auto_io_scaling -class StorageEditionCapability(msrest.serialization.Model): +class StorageEditionCapability(_serialization.Model): """storage edition capability. Variables are only populated by the server, and will be ignored when sending a request. @@ -2126,38 +2031,34 @@ class StorageEditionCapability(msrest.serialization.Model): :ivar name: storage edition name. :vartype name: str :ivar min_storage_size: The minimal supported storage size. - :vartype min_storage_size: long + :vartype min_storage_size: int :ivar max_storage_size: The maximum supported storage size. - :vartype max_storage_size: long + :vartype max_storage_size: int :ivar min_backup_retention_days: Minimal backup retention days. - :vartype min_backup_retention_days: long + :vartype min_backup_retention_days: int :ivar max_backup_retention_days: Maximum backup retention days. - :vartype max_backup_retention_days: long + :vartype max_backup_retention_days: int """ _validation = { - 'name': {'readonly': True}, - 'min_storage_size': {'readonly': True}, - 'max_storage_size': {'readonly': True}, - 'min_backup_retention_days': {'readonly': True}, - 'max_backup_retention_days': {'readonly': True}, + "name": {"readonly": True}, + "min_storage_size": {"readonly": True}, + "max_storage_size": {"readonly": True}, + "min_backup_retention_days": {"readonly": True}, + "max_backup_retention_days": {"readonly": True}, } _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'min_storage_size': {'key': 'minStorageSize', 'type': 'long'}, - 'max_storage_size': {'key': 'maxStorageSize', 'type': 'long'}, - 'min_backup_retention_days': {'key': 'minBackupRetentionDays', 'type': 'long'}, - 'max_backup_retention_days': {'key': 'maxBackupRetentionDays', 'type': 'long'}, + "name": {"key": "name", "type": "str"}, + "min_storage_size": {"key": "minStorageSize", "type": "int"}, + "max_storage_size": {"key": "maxStorageSize", "type": "int"}, + "min_backup_retention_days": {"key": "minBackupRetentionDays", "type": "int"}, + "max_backup_retention_days": {"key": "maxBackupRetentionDays", "type": "int"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(StorageEditionCapability, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.name = None self.min_storage_size = None self.max_storage_size = None @@ -2165,20 +2066,20 @@ def __init__( self.max_backup_retention_days = None -class SystemData(msrest.serialization.Model): +class SystemData(_serialization.Model): """Metadata pertaining to creation and last modification of the resource. :ivar created_by: The identity that created the resource. :vartype created_by: str :ivar created_by_type: The type of identity that created the resource. Known values are: - "User", "Application", "ManagedIdentity", "Key". + "User", "Application", "ManagedIdentity", and "Key". :vartype created_by_type: str or ~azure.mgmt.rdbms.mysql_flexibleservers.models.CreatedByType :ivar created_at: The timestamp of resource creation (UTC). :vartype created_at: ~datetime.datetime :ivar last_modified_by: The identity that last modified the resource. :vartype last_modified_by: str :ivar last_modified_by_type: The type of identity that last modified the resource. Known values - are: "User", "Application", "ManagedIdentity", "Key". + are: "User", "Application", "ManagedIdentity", and "Key". :vartype last_modified_by_type: str or ~azure.mgmt.rdbms.mysql_flexibleservers.models.CreatedByType :ivar last_modified_at: The timestamp of resource last modification (UTC). @@ -2186,12 +2087,12 @@ class SystemData(msrest.serialization.Model): """ _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'}, + "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__( @@ -2209,20 +2110,20 @@ def __init__( :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", "Key". + "User", "Application", "ManagedIdentity", and "Key". :paramtype created_by_type: str or ~azure.mgmt.rdbms.mysql_flexibleservers.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", "Key". + values are: "User", "Application", "ManagedIdentity", and "Key". :paramtype last_modified_by_type: str or ~azure.mgmt.rdbms.mysql_flexibleservers.models.CreatedByType :keyword last_modified_at: The timestamp of resource last modification (UTC). :paramtype last_modified_at: ~datetime.datetime """ - super(SystemData, self).__init__(**kwargs) + super().__init__(**kwargs) self.created_by = created_by self.created_by_type = created_by_type self.created_at = created_at @@ -2231,7 +2132,7 @@ def __init__( self.last_modified_at = last_modified_at -class UserAssignedIdentity(msrest.serialization.Model): +class UserAssignedIdentity(_serialization.Model): """Metadata of user assigned identity. Variables are only populated by the server, and will be ignored when sending a request. @@ -2243,27 +2144,23 @@ class UserAssignedIdentity(msrest.serialization.Model): """ _validation = { - 'principal_id': {'readonly': True}, - 'client_id': {'readonly': True}, + "principal_id": {"readonly": True}, + "client_id": {"readonly": True}, } _attribute_map = { - 'principal_id': {'key': 'principalId', 'type': 'str'}, - 'client_id': {'key': 'clientId', 'type': 'str'}, + "principal_id": {"key": "principalId", "type": "str"}, + "client_id": {"key": "clientId", "type": "str"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(UserAssignedIdentity, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.principal_id = None self.client_id = None -class VirtualNetworkSubnetUsageParameter(msrest.serialization.Model): +class VirtualNetworkSubnetUsageParameter(_serialization.Model): """Virtual network subnet usage parameter. :ivar virtual_network_resource_id: Virtual network resource id. @@ -2271,24 +2168,19 @@ class VirtualNetworkSubnetUsageParameter(msrest.serialization.Model): """ _attribute_map = { - 'virtual_network_resource_id': {'key': 'virtualNetworkResourceId', 'type': 'str'}, + "virtual_network_resource_id": {"key": "virtualNetworkResourceId", "type": "str"}, } - def __init__( - self, - *, - virtual_network_resource_id: Optional[str] = None, - **kwargs - ): + def __init__(self, *, virtual_network_resource_id: Optional[str] = None, **kwargs): """ :keyword virtual_network_resource_id: Virtual network resource id. :paramtype virtual_network_resource_id: str """ - super(VirtualNetworkSubnetUsageParameter, self).__init__(**kwargs) + super().__init__(**kwargs) self.virtual_network_resource_id = virtual_network_resource_id -class VirtualNetworkSubnetUsageResult(msrest.serialization.Model): +class VirtualNetworkSubnetUsageResult(_serialization.Model): """Virtual network subnet usage data. Variables are only populated by the server, and will be ignored when sending a request. @@ -2303,24 +2195,20 @@ class VirtualNetworkSubnetUsageResult(msrest.serialization.Model): """ _validation = { - 'location': {'readonly': True}, - 'subscription_id': {'readonly': True}, - 'delegated_subnets_usage': {'readonly': True}, + "location": {"readonly": True}, + "subscription_id": {"readonly": True}, + "delegated_subnets_usage": {"readonly": True}, } _attribute_map = { - 'location': {'key': 'location', 'type': 'str'}, - 'subscription_id': {'key': 'subscriptionId', 'type': 'str'}, - 'delegated_subnets_usage': {'key': 'delegatedSubnetsUsage', 'type': '[DelegatedSubnetUsage]'}, + "location": {"key": "location", "type": "str"}, + "subscription_id": {"key": "subscriptionId", "type": "str"}, + "delegated_subnets_usage": {"key": "delegatedSubnetsUsage", "type": "[DelegatedSubnetUsage]"}, } - def __init__( - self, - **kwargs - ): - """ - """ - super(VirtualNetworkSubnetUsageResult, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.location = None self.subscription_id = None self.delegated_subnets_usage = None diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/models/_my_sql_management_client_enums.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/models/_my_sql_management_client_enums.py index fcd51b19361b..7770c58b0838 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/models/_my_sql_management_client_enums.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/models/_my_sql_management_client_enums.py @@ -11,65 +11,66 @@ class AdministratorName(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """AdministratorName.""" ACTIVE_DIRECTORY = "ActiveDirectory" + class AdministratorType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Type of the sever administrator. - """ + """Type of the sever administrator.""" ACTIVE_DIRECTORY = "ActiveDirectory" + class ConfigurationSource(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Source of the configuration. - """ + """Source of the configuration.""" SYSTEM_DEFAULT = "system-default" USER_OVERRIDE = "user-override" + class CreatedByType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The type of identity that created the resource. - """ + """The type of identity that created the resource.""" USER = "User" APPLICATION = "Application" MANAGED_IDENTITY = "ManagedIdentity" KEY = "Key" + class CreateMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The mode to create a new MySQL server. - """ + """The mode to create a new MySQL server.""" DEFAULT = "Default" POINT_IN_TIME_RESTORE = "PointInTimeRestore" REPLICA = "Replica" GEO_RESTORE = "GeoRestore" + class DataEncryptionType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The key type, AzureKeyVault for enable cmk, SystemManaged for disable cmk. - """ + """The key type, AzureKeyVault for enable cmk, SystemManaged for disable cmk.""" AZURE_KEY_VAULT = "AzureKeyVault" SYSTEM_MANAGED = "SystemManaged" + class EnableStatusEnum(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Enum to indicate whether value is 'Enabled' or 'Disabled' - """ + """Enum to indicate whether value is 'Enabled' or 'Disabled'.""" ENABLED = "Enabled" DISABLED = "Disabled" + class HighAvailabilityMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """High availability mode for a server. - """ + """High availability mode for a server.""" DISABLED = "Disabled" ZONE_REDUNDANT = "ZoneRedundant" SAME_ZONE = "SameZone" + class HighAvailabilityState(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The state of server high availability. - """ + """The state of server high availability.""" NOT_ENABLED = "NotEnabled" CREATING_STANDBY = "CreatingStandby" @@ -77,45 +78,45 @@ class HighAvailabilityState(str, Enum, metaclass=CaseInsensitiveEnumMeta): FAILING_OVER = "FailingOver" REMOVING_STANDBY = "RemovingStandby" + class IsConfigPendingRestart(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """If is the configuration pending restart or not. - """ + """If is the configuration pending restart or not.""" TRUE = "True" FALSE = "False" + class IsDynamicConfig(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """If is the configuration dynamic. - """ + """If is the configuration dynamic.""" TRUE = "True" FALSE = "False" + class IsReadOnly(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """If is the configuration read only. - """ + """If is the configuration read only.""" TRUE = "True" FALSE = "False" + class ReplicationRole(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The replication role. - """ + """The replication role.""" NONE = "None" SOURCE = "Source" REPLICA = "Replica" + class ResetAllToDefault(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Whether to reset all server parameters to default. - """ + """Whether to reset all server parameters to default.""" TRUE = "True" FALSE = "False" + class ServerState(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The state of a server. - """ + """The state of a server.""" READY = "Ready" DROPPING = "Dropping" @@ -125,16 +126,16 @@ class ServerState(str, Enum, metaclass=CaseInsensitiveEnumMeta): STOPPED = "Stopped" UPDATING = "Updating" + class ServerVersion(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The version of a server. - """ + """The version of a server.""" FIVE7 = "5.7" EIGHT0_21 = "8.0.21" + class SkuTier(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The tier of the particular SKU, e.g. GeneralPurpose. - """ + """The tier of the particular SKU, e.g. GeneralPurpose.""" BURSTABLE = "Burstable" GENERAL_PURPOSE = "GeneralPurpose" diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/models/_patch.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/models/_patch.py index 0ad201a8c586..f7dd32510333 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/models/_patch.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/models/_patch.py @@ -10,6 +10,7 @@ __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. diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/operations/__init__.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/operations/__init__.py index fe672c1663f0..ee84bcc56466 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/operations/__init__.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/operations/__init__.py @@ -24,21 +24,22 @@ from ._patch import __all__ as _patch_all from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import from ._patch import patch_sdk as _patch_sdk + __all__ = [ - 'BackupsOperations', - 'ConfigurationsOperations', - 'DatabasesOperations', - 'FirewallRulesOperations', - 'ServersOperations', - 'ReplicasOperations', - 'LogFilesOperations', - 'LocationBasedCapabilitiesOperations', - 'CheckVirtualNetworkSubnetUsageOperations', - 'CheckNameAvailabilityOperations', - 'CheckNameAvailabilityWithoutLocationOperations', - 'GetPrivateDnsZoneSuffixOperations', - 'Operations', - 'AzureADAdministratorsOperations', + "BackupsOperations", + "ConfigurationsOperations", + "DatabasesOperations", + "FirewallRulesOperations", + "ServersOperations", + "ReplicasOperations", + "LogFilesOperations", + "LocationBasedCapabilitiesOperations", + "CheckVirtualNetworkSubnetUsageOperations", + "CheckNameAvailabilityOperations", + "CheckNameAvailabilityWithoutLocationOperations", + "GetPrivateDnsZoneSuffixOperations", + "Operations", + "AzureADAdministratorsOperations", ] __all__.extend([p for p in _patch_all if p not in __all__]) -_patch_sdk() \ No newline at end of file +_patch_sdk() diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/operations/_azure_ad_administrators_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/operations/_azure_ad_administrators_operations.py index 1a8e198be00c..eff2b5ba26a3 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/operations/_azure_ad_administrators_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/operations/_azure_ad_administrators_operations.py @@ -6,11 +6,17 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Iterable, Optional, TypeVar, Union, cast - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse @@ -22,173 +28,165 @@ from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_create_or_update_request_initial( - subscription_id: str, + +def build_create_or_update_request( resource_group_name: str, server_name: str, - administrator_name: Union[str, "_models.AdministratorName"], - *, - json: Optional[_models.AzureADAdministrator] = None, - content: Any = None, + administrator_name: Union[str, _models.AdministratorName], + subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', None)) # type: Optional[str] - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/administrators/{administratorName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/administrators/{administratorName}", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), - "administratorName": _SERIALIZER.url("administrator_name", administrator_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), + "administratorName": _SERIALIZER.url("administrator_name", administrator_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _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') + _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, - json=json, - content=content, - **kwargs - ) + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) -def build_delete_request_initial( - subscription_id: str, +def build_delete_request( resource_group_name: str, server_name: str, - administrator_name: Union[str, "_models.AdministratorName"], + administrator_name: Union[str, _models.AdministratorName], + subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/administrators/{administratorName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/administrators/{administratorName}", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), - "administratorName": _SERIALIZER.url("administrator_name", administrator_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), + "administratorName": _SERIALIZER.url("administrator_name", administrator_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="DELETE", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) def build_get_request( - subscription_id: str, resource_group_name: str, server_name: str, - administrator_name: Union[str, "_models.AdministratorName"], + administrator_name: Union[str, _models.AdministratorName], + subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/administrators/{administratorName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/administrators/{administratorName}", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), - "administratorName": _SERIALIZER.url("administrator_name", administrator_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), + "administratorName": _SERIALIZER.url("administrator_name", administrator_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_list_by_server_request( - subscription_id: str, - resource_group_name: str, - server_name: str, - **kwargs: Any + resource_group_name: str, server_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/administrators") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/administrators", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) class AzureADAdministratorsOperations: """ @@ -209,38 +207,47 @@ def __init__(self, *args, **kwargs): 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") - def _create_or_update_initial( self, resource_group_name: str, server_name: str, - administrator_name: Union[str, "_models.AdministratorName"], - parameters: _models.AzureADAdministrator, + administrator_name: Union[str, _models.AdministratorName], + parameters: Union[_models.AzureADAdministrator, IO], **kwargs: Any ) -> Optional[_models.AzureADAdministrator]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[Optional[_models.AzureADAdministrator]] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.AzureADAdministrator]] - _json = self._serialize.body(parameters, 'AzureADAdministrator') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "AzureADAdministrator") - request = build_create_or_update_request_initial( - subscription_id=self._config.subscription_id, + request = build_create_or_update_request( resource_group_name=resource_group_name, server_name=server_name, administrator_name=administrator_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._create_or_update_initial.metadata['url'], + content=_content, + template_url=self._create_or_update_initial.metadata["url"], headers=_headers, params=_params, ) @@ -248,10 +255,9 @@ def _create_or_update_initial( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 201, 202]: @@ -260,39 +266,87 @@ def _create_or_update_initial( deserialized = None if response.status_code == 200: - deserialized = self._deserialize('AzureADAdministrator', pipeline_response) + deserialized = self._deserialize("AzureADAdministrator", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('AzureADAdministrator', pipeline_response) + deserialized = self._deserialize("AzureADAdministrator", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _create_or_update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/administrators/{administratorName}"} # type: ignore - + _create_or_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/administrators/{administratorName}"} # type: ignore - @distributed_trace + @overload def begin_create_or_update( self, resource_group_name: str, server_name: str, - administrator_name: Union[str, "_models.AdministratorName"], + administrator_name: Union[str, _models.AdministratorName], parameters: _models.AzureADAdministrator, + *, + content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.AzureADAdministrator]: """Creates or updates an existing Azure Active Directory administrator. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param administrator_name: The name of the Azure AD Administrator. + :param administrator_name: The name of the Azure AD Administrator. "ActiveDirectory" Required. :type administrator_name: str or ~azure.mgmt.rdbms.mysql_flexibleservers.models.AdministratorName :param parameters: The required parameters for creating or updating an aad administrator. + Required. :type parameters: ~azure.mgmt.rdbms.mysql_flexibleservers.models.AzureADAdministrator + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + 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 AzureADAdministrator or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql_flexibleservers.models.AzureADAdministrator] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + administrator_name: Union[str, _models.AdministratorName], + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.AzureADAdministrator]: + """Creates or updates an existing Azure Active Directory administrator. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param administrator_name: The name of the Azure AD Administrator. "ActiveDirectory" Required. + :type administrator_name: str or + ~azure.mgmt.rdbms.mysql_flexibleservers.models.AdministratorName + :param parameters: The required parameters for creating or updating an aad administrator. + Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :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 @@ -305,20 +359,57 @@ def begin_create_or_update( cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql_flexibleservers.models.AzureADAdministrator] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + administrator_name: Union[str, _models.AdministratorName], + parameters: Union[_models.AzureADAdministrator, IO], + **kwargs: Any + ) -> LROPoller[_models.AzureADAdministrator]: + """Creates or updates an existing Azure Active Directory administrator. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param administrator_name: The name of the Azure AD Administrator. "ActiveDirectory" Required. + :type administrator_name: str or + ~azure.mgmt.rdbms.mysql_flexibleservers.models.AdministratorName + :param parameters: The required parameters for creating or updating an aad administrator. Is + either a model type or a IO type. Required. + :type parameters: ~azure.mgmt.rdbms.mysql_flexibleservers.models.AzureADAdministrator or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either AzureADAdministrator or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql_flexibleservers.models.AzureADAdministrator] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[_models.AzureADAdministrator] - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.AzureADAdministrator] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = self._create_or_update_initial( # type: ignore resource_group_name=resource_group_name, @@ -327,66 +418,64 @@ def begin_create_or_update( parameters=parameters, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize('AzureADAdministrator', pipeline_response) + deserialized = self._deserialize("AzureADAdministrator", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - if polling is True: - polling_method = cast(PollingMethod, ARMPolling( - lro_delay, - - - **kwargs - )) # type: PollingMethod - elif polling is False: polling_method = cast(PollingMethod, NoPolling()) - else: polling_method = polling + polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_create_or_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/administrators/{administratorName}"} # type: ignore + begin_create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/administrators/{administratorName}"} # type: ignore def _delete_initial( # pylint: disable=inconsistent-return-statements self, resource_group_name: str, server_name: str, - administrator_name: Union[str, "_models.AdministratorName"], + administrator_name: Union[str, _models.AdministratorName], **kwargs: Any ) -> None: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] - - request = build_delete_request_initial( - subscription_id=self._config.subscription_id, + request = build_delete_request( resource_group_name=resource_group_name, server_name=server_name, administrator_name=administrator_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._delete_initial.metadata['url'], + template_url=self._delete_initial.metadata["url"], headers=_headers, params=_params, ) @@ -394,10 +483,9 @@ def _delete_initial( # pylint: disable=inconsistent-return-statements request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: @@ -407,24 +495,24 @@ def _delete_initial( # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - _delete_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/administrators/{administratorName}"} # type: ignore - + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/administrators/{administratorName}"} # type: ignore @distributed_trace - def begin_delete( # pylint: disable=inconsistent-return-statements + def begin_delete( self, resource_group_name: str, server_name: str, - administrator_name: Union[str, "_models.AdministratorName"], + administrator_name: Union[str, _models.AdministratorName], **kwargs: Any ) -> LROPoller[None]: """Deletes an Azure AD Administrator. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param administrator_name: The name of the Azure AD Administrator. + :param administrator_name: The name of the Azure AD Administrator. "ActiveDirectory" Required. :type administrator_name: str or ~azure.mgmt.rdbms.mysql_flexibleservers.models.AdministratorName :keyword callable cls: A custom type or function that will be passed the direct response @@ -437,98 +525,96 @@ def begin_delete( # pylint: disable=inconsistent-return-statements Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = self._delete_initial( # type: ignore resource_group_name=resource_group_name, server_name=server_name, administrator_name=administrator_name, api_version=api_version, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - if polling is True: - polling_method = cast(PollingMethod, ARMPolling( - lro_delay, - lro_options={'final-state-via': 'location'}, - - **kwargs - )) # type: PollingMethod - elif polling is False: polling_method = cast(PollingMethod, NoPolling()) - else: polling_method = polling + polling_method = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_delete.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/administrators/{administratorName}"} # type: ignore + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/administrators/{administratorName}"} # type: ignore @distributed_trace def get( self, resource_group_name: str, server_name: str, - administrator_name: Union[str, "_models.AdministratorName"], + administrator_name: Union[str, _models.AdministratorName], **kwargs: Any ) -> _models.AzureADAdministrator: """Gets information about an azure ad administrator. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param administrator_name: The name of the Azure AD Administrator. + :param administrator_name: The name of the Azure AD Administrator. "ActiveDirectory" Required. :type administrator_name: str or ~azure.mgmt.rdbms.mysql_flexibleservers.models.AdministratorName :keyword callable cls: A custom type or function that will be passed the direct response - :return: AzureADAdministrator, or the result of cls(response) + :return: AzureADAdministrator or the result of cls(response) :rtype: ~azure.mgmt.rdbms.mysql_flexibleservers.models.AzureADAdministrator - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.AzureADAdministrator] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AzureADAdministrator] - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, administrator_name=administrator_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], headers=_headers, params=_params, ) @@ -536,65 +622,65 @@ def get( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('AzureADAdministrator', pipeline_response) + deserialized = self._deserialize("AzureADAdministrator", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/administrators/{administratorName}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/administrators/{administratorName}"} # type: ignore @distributed_trace def list_by_server( - self, - resource_group_name: str, - server_name: str, - **kwargs: Any - ) -> Iterable[_models.AdministratorListResult]: + self, resource_group_name: str, server_name: str, **kwargs: Any + ) -> Iterable["_models.AzureADAdministrator"]: """List all the AAD administrators in a given server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either AdministratorListResult or the result of + :return: An iterator like instance of either AzureADAdministrator or the result of cls(response) :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql_flexibleservers.models.AdministratorListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql_flexibleservers.models.AzureADAdministrator] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.AdministratorListResult] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AdministratorListResult] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_server_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_server.metadata['url'], + template_url=self.list_by_server.metadata["url"], headers=_headers, params=_params, ) @@ -602,15 +688,17 @@ def prepare_request(next_link=None): request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_by_server_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - server_name=server_name, - api_version=api_version, - template_url=next_link, - 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() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore @@ -627,10 +715,8 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -640,8 +726,6 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list_by_server.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/administrators"} # type: ignore + list_by_server.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/administrators"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/operations/_backups_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/operations/_backups_operations.py index b99afbe7f39a..89887eddd38f 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/operations/_backups_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/operations/_backups_operations.py @@ -7,10 +7,16 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from typing import Any, Callable, Dict, Iterable, Optional, TypeVar - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse @@ -20,126 +26,116 @@ from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False + def build_put_request( - subscription_id: str, - resource_group_name: str, - server_name: str, - backup_name: str, - **kwargs: Any + resource_group_name: str, server_name: str, backup_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/backups/{backupName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/backups/{backupName}", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), - "backupName": _SERIALIZER.url("backup_name", backup_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), + "backupName": _SERIALIZER.url("backup_name", backup_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="PUT", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) def build_get_request( - subscription_id: str, - resource_group_name: str, - server_name: str, - backup_name: str, - **kwargs: Any + resource_group_name: str, server_name: str, backup_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/backups/{backupName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/backups/{backupName}", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), - "backupName": _SERIALIZER.url("backup_name", backup_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), + "backupName": _SERIALIZER.url("backup_name", backup_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_list_by_server_request( - subscription_id: str, - resource_group_name: str, - server_name: str, - **kwargs: Any + resource_group_name: str, server_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/backups") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/backups", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) class BackupsOperations: """ @@ -160,47 +156,43 @@ def __init__(self, *args, **kwargs): self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace - def put( - self, - resource_group_name: str, - server_name: str, - backup_name: str, - **kwargs: Any - ) -> _models.ServerBackup: + def put(self, resource_group_name: str, server_name: str, backup_name: str, **kwargs: Any) -> _models.ServerBackup: """Create backup for a given server with specified backup name. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param backup_name: The name of the backup. + :param backup_name: The name of the backup. Required. :type backup_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: ServerBackup, or the result of cls(response) + :return: ServerBackup or the result of cls(response) :rtype: ~azure.mgmt.rdbms.mysql_flexibleservers.models.ServerBackup - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.ServerBackup] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ServerBackup] - request = build_put_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, backup_name=backup_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.put.metadata['url'], + template_url=self.put.metadata["url"], headers=_headers, params=_params, ) @@ -208,66 +200,61 @@ def put( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('ServerBackup', pipeline_response) + deserialized = self._deserialize("ServerBackup", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - put.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/backups/{backupName}"} # type: ignore - + put.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/backups/{backupName}"} # type: ignore @distributed_trace - def get( - self, - resource_group_name: str, - server_name: str, - backup_name: str, - **kwargs: Any - ) -> _models.ServerBackup: + def get(self, resource_group_name: str, server_name: str, backup_name: str, **kwargs: Any) -> _models.ServerBackup: """List all the backups for a given server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param backup_name: The name of the backup. + :param backup_name: The name of the backup. Required. :type backup_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: ServerBackup, or the result of cls(response) + :return: ServerBackup or the result of cls(response) :rtype: ~azure.mgmt.rdbms.mysql_flexibleservers.models.ServerBackup - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.ServerBackup] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ServerBackup] - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, backup_name=backup_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], headers=_headers, params=_params, ) @@ -275,65 +262,64 @@ def get( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('ServerBackup', pipeline_response) + deserialized = self._deserialize("ServerBackup", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/backups/{backupName}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/backups/{backupName}"} # type: ignore @distributed_trace def list_by_server( - self, - resource_group_name: str, - server_name: str, - **kwargs: Any - ) -> Iterable[_models.ServerBackupListResult]: + self, resource_group_name: str, server_name: str, **kwargs: Any + ) -> Iterable["_models.ServerBackup"]: """List all the backups for a given server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ServerBackupListResult or the result of - cls(response) + :return: An iterator like instance of either ServerBackup or the result of cls(response) :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql_flexibleservers.models.ServerBackupListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql_flexibleservers.models.ServerBackup] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.ServerBackupListResult] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ServerBackupListResult] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_server_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_server.metadata['url'], + template_url=self.list_by_server.metadata["url"], headers=_headers, params=_params, ) @@ -341,15 +327,17 @@ def prepare_request(next_link=None): request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_by_server_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - server_name=server_name, - api_version=api_version, - template_url=next_link, - 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() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore @@ -366,10 +354,8 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -379,8 +365,6 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list_by_server.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/backups"} # type: ignore + list_by_server.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/backups"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/operations/_check_name_availability_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/operations/_check_name_availability_operations.py index 5914a1937b05..976e3916e9e5 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/operations/_check_name_availability_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/operations/_check_name_availability_operations.py @@ -6,11 +6,16 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Optional, TypeVar - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest @@ -19,54 +24,46 @@ from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_execute_request( - subscription_id: str, - location_name: str, - *, - json: Optional[_models.NameAvailabilityRequest] = None, - content: Any = None, - **kwargs: Any -) -> HttpRequest: + +def build_execute_request(location_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', None)) # type: Optional[str] - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/locations/{locationName}/checkNameAvailability") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/locations/{locationName}/checkNameAvailability", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), - "locationName": _SERIALIZER.url("location_name", location_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "locationName": _SERIALIZER.url("location_name", location_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if content_type is not None: - _headers['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="POST", - url=_url, - params=_params, - headers=_headers, - json=json, - content=content, - **kwargs - ) + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + class CheckNameAvailabilityOperations: """ @@ -87,48 +84,108 @@ def __init__(self, *args, **kwargs): self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace + @overload def execute( self, location_name: str, name_availability_request: _models.NameAvailabilityRequest, + *, + content_type: str = "application/json", **kwargs: Any ) -> _models.NameAvailability: """Check the availability of name for server. - :param location_name: The name of the location. + :param location_name: The name of the location. Required. :type location_name: str :param name_availability_request: The required parameters for checking if server name is - available. + available. Required. :type name_availability_request: ~azure.mgmt.rdbms.mysql_flexibleservers.models.NameAvailabilityRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: NameAvailability, or the result of cls(response) + :return: NameAvailability or the result of cls(response) :rtype: ~azure.mgmt.rdbms.mysql_flexibleservers.models.NameAvailability - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def execute( + self, + location_name: str, + name_availability_request: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.NameAvailability: + """Check the availability of name for server. + + :param location_name: The name of the location. Required. + :type location_name: str + :param name_availability_request: The required parameters for checking if server name is + available. Required. + :type name_availability_request: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: NameAvailability or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql_flexibleservers.models.NameAvailability + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def execute( + self, location_name: str, name_availability_request: Union[_models.NameAvailabilityRequest, IO], **kwargs: Any + ) -> _models.NameAvailability: + """Check the availability of name for server. + + :param location_name: The name of the location. Required. + :type location_name: str + :param name_availability_request: The required parameters for checking if server name is + available. Is either a model type or a IO type. Required. + :type name_availability_request: + ~azure.mgmt.rdbms.mysql_flexibleservers.models.NameAvailabilityRequest or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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: NameAvailability or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql_flexibleservers.models.NameAvailability + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[_models.NameAvailability] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.NameAvailability] - _json = self._serialize.body(name_availability_request, 'NameAvailabilityRequest') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(name_availability_request, (IO, bytes)): + _content = name_availability_request + else: + _json = self._serialize.body(name_availability_request, "NameAvailabilityRequest") request = build_execute_request( - subscription_id=self._config.subscription_id, location_name=location_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self.execute.metadata['url'], + content=_content, + template_url=self.execute.metadata["url"], headers=_headers, params=_params, ) @@ -136,22 +193,20 @@ def execute( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('NameAvailability', pipeline_response) + deserialized = self._deserialize("NameAvailability", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - execute.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/locations/{locationName}/checkNameAvailability"} # type: ignore - + execute.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/locations/{locationName}/checkNameAvailability"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/operations/_check_name_availability_without_location_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/operations/_check_name_availability_without_location_operations.py index 3cd64fdbaff8..e455b1bc57ed 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/operations/_check_name_availability_without_location_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/operations/_check_name_availability_without_location_operations.py @@ -6,11 +6,16 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Optional, TypeVar - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest @@ -19,52 +24,44 @@ from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_execute_request( - subscription_id: str, - *, - json: Optional[_models.NameAvailabilityRequest] = None, - content: Any = None, - **kwargs: Any -) -> HttpRequest: + +def build_execute_request(subscription_id: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', None)) # type: Optional[str] - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/checkNameAvailability") + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/checkNameAvailability" + ) path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if content_type is not None: - _headers['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="POST", - url=_url, - params=_params, - headers=_headers, - json=json, - content=content, - **kwargs - ) + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + class CheckNameAvailabilityWithoutLocationOperations: """ @@ -85,44 +82,95 @@ def __init__(self, *args, **kwargs): self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace + @overload def execute( self, name_availability_request: _models.NameAvailabilityRequest, + *, + content_type: str = "application/json", **kwargs: Any ) -> _models.NameAvailability: """Check the availability of name for server. :param name_availability_request: The required parameters for checking if server name is - available. + available. Required. :type name_availability_request: ~azure.mgmt.rdbms.mysql_flexibleservers.models.NameAvailabilityRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: NameAvailability or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql_flexibleservers.models.NameAvailability + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def execute( + self, name_availability_request: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.NameAvailability: + """Check the availability of name for server. + + :param name_availability_request: The required parameters for checking if server name is + available. Required. + :type name_availability_request: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: NameAvailability or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql_flexibleservers.models.NameAvailability + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def execute( + self, name_availability_request: Union[_models.NameAvailabilityRequest, IO], **kwargs: Any + ) -> _models.NameAvailability: + """Check the availability of name for server. + + :param name_availability_request: The required parameters for checking if server name is + available. Is either a model type or a IO type. Required. + :type name_availability_request: + ~azure.mgmt.rdbms.mysql_flexibleservers.models.NameAvailabilityRequest or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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: NameAvailability, or the result of cls(response) + :return: NameAvailability or the result of cls(response) :rtype: ~azure.mgmt.rdbms.mysql_flexibleservers.models.NameAvailability - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[_models.NameAvailability] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.NameAvailability] - _json = self._serialize.body(name_availability_request, 'NameAvailabilityRequest') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(name_availability_request, (IO, bytes)): + _content = name_availability_request + else: + _json = self._serialize.body(name_availability_request, "NameAvailabilityRequest") request = build_execute_request( subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self.execute.metadata['url'], + content=_content, + template_url=self.execute.metadata["url"], headers=_headers, params=_params, ) @@ -130,22 +178,20 @@ def execute( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('NameAvailability', pipeline_response) + deserialized = self._deserialize("NameAvailability", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - execute.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/checkNameAvailability"} # type: ignore - + execute.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/checkNameAvailability"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/operations/_check_virtual_network_subnet_usage_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/operations/_check_virtual_network_subnet_usage_operations.py index 4da189bf0904..02f231913f74 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/operations/_check_virtual_network_subnet_usage_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/operations/_check_virtual_network_subnet_usage_operations.py @@ -6,11 +6,16 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Optional, TypeVar - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest @@ -19,54 +24,46 @@ from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_execute_request( - subscription_id: str, - location_name: str, - *, - json: Optional[_models.VirtualNetworkSubnetUsageParameter] = None, - content: Any = None, - **kwargs: Any -) -> HttpRequest: + +def build_execute_request(location_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', None)) # type: Optional[str] - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/locations/{locationName}/checkVirtualNetworkSubnetUsage") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/locations/{locationName}/checkVirtualNetworkSubnetUsage", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), - "locationName": _SERIALIZER.url("location_name", location_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "locationName": _SERIALIZER.url("location_name", location_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if content_type is not None: - _headers['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="POST", - url=_url, - params=_params, - headers=_headers, - json=json, - content=content, - **kwargs - ) + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + class CheckVirtualNetworkSubnetUsageOperations: """ @@ -87,47 +84,101 @@ def __init__(self, *args, **kwargs): self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace + @overload def execute( self, location_name: str, parameters: _models.VirtualNetworkSubnetUsageParameter, + *, + content_type: str = "application/json", **kwargs: Any ) -> _models.VirtualNetworkSubnetUsageResult: """Get virtual network subnet usage for a given vNet resource id. - :param location_name: The name of the location. + :param location_name: The name of the location. Required. :type location_name: str - :param parameters: The required parameters for creating or updating a server. + :param parameters: The required parameters for creating or updating a server. Required. :type parameters: ~azure.mgmt.rdbms.mysql_flexibleservers.models.VirtualNetworkSubnetUsageParameter + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: VirtualNetworkSubnetUsageResult or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql_flexibleservers.models.VirtualNetworkSubnetUsageResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def execute( + self, location_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.VirtualNetworkSubnetUsageResult: + """Get virtual network subnet usage for a given vNet resource id. + + :param location_name: The name of the location. Required. + :type location_name: str + :param parameters: The required parameters for creating or updating a server. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: VirtualNetworkSubnetUsageResult or the result of cls(response) + :rtype: ~azure.mgmt.rdbms.mysql_flexibleservers.models.VirtualNetworkSubnetUsageResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def execute( + self, location_name: str, parameters: Union[_models.VirtualNetworkSubnetUsageParameter, IO], **kwargs: Any + ) -> _models.VirtualNetworkSubnetUsageResult: + """Get virtual network subnet usage for a given vNet resource id. + + :param location_name: The name of the location. Required. + :type location_name: str + :param parameters: The required parameters for creating or updating a server. Is either a model + type or a IO type. Required. + :type parameters: + ~azure.mgmt.rdbms.mysql_flexibleservers.models.VirtualNetworkSubnetUsageParameter or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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: VirtualNetworkSubnetUsageResult, or the result of cls(response) + :return: VirtualNetworkSubnetUsageResult or the result of cls(response) :rtype: ~azure.mgmt.rdbms.mysql_flexibleservers.models.VirtualNetworkSubnetUsageResult - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[_models.VirtualNetworkSubnetUsageResult] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.VirtualNetworkSubnetUsageResult] - _json = self._serialize.body(parameters, 'VirtualNetworkSubnetUsageParameter') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "VirtualNetworkSubnetUsageParameter") request = build_execute_request( - subscription_id=self._config.subscription_id, location_name=location_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self.execute.metadata['url'], + content=_content, + template_url=self.execute.metadata["url"], headers=_headers, params=_params, ) @@ -135,22 +186,20 @@ def execute( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('VirtualNetworkSubnetUsageResult', pipeline_response) + deserialized = self._deserialize("VirtualNetworkSubnetUsageResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - execute.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/locations/{locationName}/checkVirtualNetworkSubnetUsage"} # type: ignore - + execute.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/locations/{locationName}/checkVirtualNetworkSubnetUsage"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/operations/_configurations_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/operations/_configurations_operations.py index aab1d855896e..0ac595d0c1c5 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/operations/_configurations_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/operations/_configurations_operations.py @@ -6,11 +6,17 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Iterable, Optional, TypeVar, Union, cast - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse @@ -22,148 +28,127 @@ from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_update_request_initial( - subscription_id: str, - resource_group_name: str, - server_name: str, - configuration_name: str, - *, - json: Optional[_models.Configuration] = None, - content: Any = None, - **kwargs: Any + +def build_update_request( + resource_group_name: str, server_name: str, configuration_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', None)) # type: Optional[str] - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/configurations/{configurationName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/configurations/{configurationName}", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), - "configurationName": _SERIALIZER.url("configuration_name", configuration_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), + "configurationName": _SERIALIZER.url("configuration_name", configuration_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _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') + _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, - json=json, - content=content, - **kwargs - ) + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) def build_get_request( - subscription_id: str, - resource_group_name: str, - server_name: str, - configuration_name: str, - **kwargs: Any + resource_group_name: str, server_name: str, configuration_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/configurations/{configurationName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/configurations/{configurationName}", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), - "configurationName": _SERIALIZER.url("configuration_name", configuration_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), + "configurationName": _SERIALIZER.url("configuration_name", configuration_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_batch_update_request_initial( - subscription_id: str, - resource_group_name: str, - server_name: str, - *, - json: Optional[_models.ConfigurationListForBatchUpdate] = None, - content: Any = None, - **kwargs: Any +def build_batch_update_request( + resource_group_name: str, server_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', None)) # type: Optional[str] - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/updateConfigurations") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/updateConfigurations", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _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') + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="POST", - url=_url, - params=_params, - headers=_headers, - json=json, - content=content, - **kwargs - ) + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) def build_list_by_server_request( - subscription_id: str, resource_group_name: str, server_name: str, + subscription_id: str, *, tags: Optional[str] = None, keyword: Optional[str] = None, @@ -174,40 +159,40 @@ def build_list_by_server_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/configurations") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/configurations", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if tags is not None: - _params['tags'] = _SERIALIZER.query("tags", tags, 'str') + _params["tags"] = _SERIALIZER.query("tags", tags, "str") if keyword is not None: - _params['keyword'] = _SERIALIZER.query("keyword", keyword, 'str') + _params["keyword"] = _SERIALIZER.query("keyword", keyword, "str") if page is not None: - _params['page'] = _SERIALIZER.query("page", page, 'int') + _params["page"] = _SERIALIZER.query("page", page, "int") if page_size is not None: - _params['pageSize'] = _SERIALIZER.query("page_size", page_size, 'int') + _params["pageSize"] = _SERIALIZER.query("page_size", page_size, "int") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) class ConfigurationsOperations: """ @@ -228,38 +213,47 @@ def __init__(self, *args, **kwargs): 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") - def _update_initial( self, resource_group_name: str, server_name: str, configuration_name: str, - parameters: _models.Configuration, + parameters: Union[_models.Configuration, IO], **kwargs: Any ) -> Optional[_models.Configuration]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[Optional[_models.Configuration]] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.Configuration]] - _json = self._serialize.body(parameters, 'Configuration') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Configuration") - request = build_update_request_initial( - subscription_id=self._config.subscription_id, + request = build_update_request( resource_group_name=resource_group_name, server_name=server_name, configuration_name=configuration_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._update_initial.metadata['url'], + content=_content, + template_url=self._update_initial.metadata["url"], headers=_headers, params=_params, ) @@ -267,10 +261,9 @@ def _update_initial( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202]: @@ -279,35 +272,80 @@ def _update_initial( deserialized = None if response.status_code == 200: - deserialized = self._deserialize('Configuration', pipeline_response) + deserialized = self._deserialize("Configuration", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/configurations/{configurationName}"} # type: ignore + _update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/configurations/{configurationName}"} # type: ignore - - @distributed_trace + @overload def begin_update( self, resource_group_name: str, server_name: str, configuration_name: str, parameters: _models.Configuration, + *, + content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.Configuration]: """Updates a configuration of a server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param configuration_name: The name of the server configuration. + :param configuration_name: The name of the server configuration. Required. :type configuration_name: str - :param parameters: The required parameters for updating a server configuration. + :param parameters: The required parameters for updating a server configuration. Required. :type parameters: ~azure.mgmt.rdbms.mysql_flexibleservers.models.Configuration + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + 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 Configuration or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql_flexibleservers.models.Configuration] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_update( + self, + resource_group_name: str, + server_name: str, + configuration_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.Configuration]: + """Updates a configuration of a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param configuration_name: The name of the server configuration. Required. + :type configuration_name: str + :param parameters: The required parameters for updating a server configuration. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :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 @@ -320,20 +358,56 @@ def begin_update( cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql_flexibleservers.models.Configuration] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_update( + self, + resource_group_name: str, + server_name: str, + configuration_name: str, + parameters: Union[_models.Configuration, IO], + **kwargs: Any + ) -> LROPoller[_models.Configuration]: + """Updates a configuration of a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param configuration_name: The name of the server configuration. Required. + :type configuration_name: str + :param parameters: The required parameters for updating a server configuration. Is either a + model type or a IO type. Required. + :type parameters: ~azure.mgmt.rdbms.mysql_flexibleservers.models.Configuration or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either Configuration or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql_flexibleservers.models.Configuration] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[_models.Configuration] - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Configuration] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = self._update_initial( # type: ignore resource_group_name=resource_group_name, @@ -342,80 +416,75 @@ def begin_update( parameters=parameters, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize('Configuration', pipeline_response) + deserialized = self._deserialize("Configuration", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - if polling is True: - polling_method = cast(PollingMethod, ARMPolling( - lro_delay, - - - **kwargs - )) # type: PollingMethod - elif polling is False: polling_method = cast(PollingMethod, NoPolling()) - else: polling_method = polling + polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/configurations/{configurationName}"} # type: ignore + begin_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/configurations/{configurationName}"} # type: ignore @distributed_trace def get( - self, - resource_group_name: str, - server_name: str, - configuration_name: str, - **kwargs: Any + self, resource_group_name: str, server_name: str, configuration_name: str, **kwargs: Any ) -> _models.Configuration: """Gets information about a configuration of server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param configuration_name: The name of the server configuration. + :param configuration_name: The name of the server configuration. Required. :type configuration_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Configuration, or the result of cls(response) + :return: Configuration or the result of cls(response) :rtype: ~azure.mgmt.rdbms.mysql_flexibleservers.models.Configuration - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.Configuration] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.Configuration] - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, configuration_name=configuration_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], headers=_headers, params=_params, ) @@ -423,55 +492,63 @@ def get( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('Configuration', pipeline_response) + deserialized = self._deserialize("Configuration", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/configurations/{configurationName}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/configurations/{configurationName}"} # type: ignore def _batch_update_initial( self, resource_group_name: str, server_name: str, - parameters: _models.ConfigurationListForBatchUpdate, + parameters: Union[_models.ConfigurationListForBatchUpdate, IO], **kwargs: Any ) -> Optional[_models.ConfigurationListResult]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[Optional[_models.ConfigurationListResult]] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.ConfigurationListResult]] - _json = self._serialize.body(parameters, 'ConfigurationListForBatchUpdate') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ConfigurationListForBatchUpdate") - request = build_batch_update_request_initial( - subscription_id=self._config.subscription_id, + request = build_batch_update_request( resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._batch_update_initial.metadata['url'], + content=_content, + template_url=self._batch_update_initial.metadata["url"], headers=_headers, params=_params, ) @@ -479,10 +556,9 @@ def _batch_update_initial( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202]: @@ -491,33 +567,38 @@ def _batch_update_initial( deserialized = None if response.status_code == 200: - deserialized = self._deserialize('ConfigurationListResult', pipeline_response) + deserialized = self._deserialize("ConfigurationListResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _batch_update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/updateConfigurations"} # type: ignore - + _batch_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/updateConfigurations"} # type: ignore - @distributed_trace + @overload def begin_batch_update( self, resource_group_name: str, server_name: str, parameters: _models.ConfigurationListForBatchUpdate, + *, + content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.ConfigurationListResult]: """Update a list of configurations in a given server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param parameters: The parameters for updating a list of server configuration. + :param parameters: The parameters for updating a list of server configuration. Required. :type parameters: ~azure.mgmt.rdbms.mysql_flexibleservers.models.ConfigurationListForBatchUpdate + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + 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 @@ -530,20 +611,91 @@ def begin_batch_update( cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql_flexibleservers.models.ConfigurationListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_batch_update( + self, + resource_group_name: str, + server_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.ConfigurationListResult]: + """Update a list of configurations in a given server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param parameters: The parameters for updating a list of server configuration. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :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 ConfigurationListResult or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql_flexibleservers.models.ConfigurationListResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_batch_update( + self, + resource_group_name: str, + server_name: str, + parameters: Union[_models.ConfigurationListForBatchUpdate, IO], + **kwargs: Any + ) -> LROPoller[_models.ConfigurationListResult]: + """Update a list of configurations in a given server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param parameters: The parameters for updating a list of server configuration. Is either a + model type or a IO type. Required. + :type parameters: + ~azure.mgmt.rdbms.mysql_flexibleservers.models.ConfigurationListForBatchUpdate or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either ConfigurationListResult or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql_flexibleservers.models.ConfigurationListResult] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[_models.ConfigurationListResult] - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.ConfigurationListResult] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = self._batch_update_initial( # type: ignore resource_group_name=resource_group_name, @@ -551,39 +703,37 @@ def begin_batch_update( parameters=parameters, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize('ConfigurationListResult', pipeline_response) + deserialized = self._deserialize("ConfigurationListResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - if polling is True: - polling_method = cast(PollingMethod, ARMPolling( - lro_delay, - lro_options={'final-state-via': 'azure-async-operation'}, - - **kwargs - )) # type: PollingMethod - elif polling is False: polling_method = cast(PollingMethod, NoPolling()) - else: polling_method = polling + polling_method = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **kwargs) + ) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_batch_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/updateConfigurations"} # type: ignore + begin_batch_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/updateConfigurations"} # type: ignore @distributed_trace def list_by_server( @@ -595,12 +745,13 @@ def list_by_server( page: Optional[int] = None, page_size: Optional[int] = None, **kwargs: Any - ) -> Iterable[_models.ConfigurationListResult]: + ) -> Iterable["_models.Configuration"]: """List all the configurations in a given server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str :param tags: The tags of the server configuration. Default value is None. :type tags: str @@ -611,35 +762,38 @@ def list_by_server( :param page_size: The pageSize of the server configuration. Default value is None. :type page_size: int :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ConfigurationListResult or the result of - cls(response) + :return: An iterator like instance of either Configuration or the result of cls(response) :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql_flexibleservers.models.ConfigurationListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql_flexibleservers.models.Configuration] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.ConfigurationListResult] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ConfigurationListResult] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_server_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, - api_version=api_version, + subscription_id=self._config.subscription_id, tags=tags, keyword=keyword, page=page, page_size=page_size, - template_url=self.list_by_server.metadata['url'], + api_version=api_version, + template_url=self.list_by_server.metadata["url"], headers=_headers, params=_params, ) @@ -647,19 +801,17 @@ def prepare_request(next_link=None): request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_by_server_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - server_name=server_name, - api_version=api_version, - tags=tags, - keyword=keyword, - page=page, - page_size=page_size, - template_url=next_link, - 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() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore @@ -676,10 +828,8 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -689,8 +839,6 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list_by_server.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/configurations"} # type: ignore + list_by_server.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/configurations"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/operations/_databases_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/operations/_databases_operations.py index c430225ea6f6..d5bcde3abd6c 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/operations/_databases_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/operations/_databases_operations.py @@ -6,11 +6,17 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Iterable, Optional, TypeVar, Union, cast - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse @@ -22,173 +28,153 @@ from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_create_or_update_request_initial( - subscription_id: str, - resource_group_name: str, - server_name: str, - database_name: str, - *, - json: Optional[_models.Database] = None, - content: Any = None, - **kwargs: Any + +def build_create_or_update_request( + resource_group_name: str, server_name: str, database_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', None)) # type: Optional[str] - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/databases/{databaseName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/databases/{databaseName}", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), - "databaseName": _SERIALIZER.url("database_name", database_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _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, - json=json, - content=content, - **kwargs - ) - - -def build_delete_request_initial( - subscription_id: str, - resource_group_name: str, - server_name: str, - database_name: str, - **kwargs: Any + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_request( + resource_group_name: str, server_name: str, database_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/databases/{databaseName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/databases/{databaseName}", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), - "databaseName": _SERIALIZER.url("database_name", database_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="DELETE", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) def build_get_request( - subscription_id: str, - resource_group_name: str, - server_name: str, - database_name: str, - **kwargs: Any + resource_group_name: str, server_name: str, database_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/databases/{databaseName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/databases/{databaseName}", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), - "databaseName": _SERIALIZER.url("database_name", database_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), + "databaseName": _SERIALIZER.url("database_name", database_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_list_by_server_request( - subscription_id: str, - resource_group_name: str, - server_name: str, - **kwargs: Any + resource_group_name: str, server_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/databases") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/databases", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) class DatabasesOperations: """ @@ -209,38 +195,47 @@ def __init__(self, *args, **kwargs): 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") - def _create_or_update_initial( self, resource_group_name: str, server_name: str, database_name: str, - parameters: _models.Database, + parameters: Union[_models.Database, IO], **kwargs: Any ) -> Optional[_models.Database]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[Optional[_models.Database]] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.Database]] - _json = self._serialize.body(parameters, 'Database') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Database") - request = build_create_or_update_request_initial( - subscription_id=self._config.subscription_id, + request = build_create_or_update_request( resource_group_name=resource_group_name, server_name=server_name, database_name=database_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._create_or_update_initial.metadata['url'], + content=_content, + template_url=self._create_or_update_initial.metadata["url"], headers=_headers, params=_params, ) @@ -248,10 +243,9 @@ def _create_or_update_initial( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 201, 202]: @@ -260,38 +254,118 @@ def _create_or_update_initial( deserialized = None if response.status_code == 200: - deserialized = self._deserialize('Database', pipeline_response) + deserialized = self._deserialize("Database", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('Database', pipeline_response) + deserialized = self._deserialize("Database", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _create_or_update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/databases/{databaseName}"} # type: ignore - + _create_or_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/databases/{databaseName}"} # type: ignore - @distributed_trace + @overload def begin_create_or_update( self, resource_group_name: str, server_name: str, database_name: str, parameters: _models.Database, + *, + content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.Database]: """Creates a new database or updates an existing database. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param database_name: The name of the database. + :param database_name: The name of the database. Required. :type database_name: str - :param parameters: The required parameters for creating or updating a database. + :param parameters: The required parameters for creating or updating a database. Required. :type parameters: ~azure.mgmt.rdbms.mysql_flexibleservers.models.Database + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + 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 Database or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql_flexibleservers.models.Database] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + database_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.Database]: + """Creates a new database or updates an existing database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param database_name: The name of the database. Required. + :type database_name: str + :param parameters: The required parameters for creating or updating a database. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :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 Database or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql_flexibleservers.models.Database] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + database_name: str, + parameters: Union[_models.Database, IO], + **kwargs: Any + ) -> LROPoller[_models.Database]: + """Creates a new database or updates an existing database. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param database_name: The name of the database. Required. + :type database_name: str + :param parameters: The required parameters for creating or updating a database. Is either a + model type or a IO type. Required. + :type parameters: ~azure.mgmt.rdbms.mysql_flexibleservers.models.Database or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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 @@ -302,20 +376,17 @@ def begin_create_or_update( Retry-After header is present. :return: An instance of LROPoller that returns either Database or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql_flexibleservers.models.Database] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[_models.Database] - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Database] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = self._create_or_update_initial( # type: ignore resource_group_name=resource_group_name, @@ -324,66 +395,60 @@ def begin_create_or_update( parameters=parameters, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize('Database', pipeline_response) + deserialized = self._deserialize("Database", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - if polling is True: - polling_method = cast(PollingMethod, ARMPolling( - lro_delay, - - - **kwargs - )) # type: PollingMethod - elif polling is False: polling_method = cast(PollingMethod, NoPolling()) - else: polling_method = polling + polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_create_or_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/databases/{databaseName}"} # type: ignore + begin_create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/databases/{databaseName}"} # type: ignore def _delete_initial( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - server_name: str, - database_name: str, - **kwargs: Any + self, resource_group_name: str, server_name: str, database_name: str, **kwargs: Any ) -> None: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] - - request = build_delete_request_initial( - subscription_id=self._config.subscription_id, + request = build_delete_request( resource_group_name=resource_group_name, server_name=server_name, database_name=database_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._delete_initial.metadata['url'], + template_url=self._delete_initial.metadata["url"], headers=_headers, params=_params, ) @@ -391,10 +456,9 @@ def _delete_initial( # pylint: disable=inconsistent-return-statements request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: @@ -404,24 +468,20 @@ def _delete_initial( # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - _delete_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/databases/{databaseName}"} # type: ignore - + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/databases/{databaseName}"} # type: ignore @distributed_trace - def begin_delete( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - server_name: str, - database_name: str, - **kwargs: Any + def begin_delete( + self, resource_group_name: str, server_name: str, database_name: str, **kwargs: Any ) -> LROPoller[None]: """Deletes a database. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param database_name: The name of the database. + :param database_name: The name of the database. Required. :type database_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. @@ -433,97 +493,87 @@ def begin_delete( # pylint: disable=inconsistent-return-statements Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = self._delete_initial( # type: ignore resource_group_name=resource_group_name, server_name=server_name, database_name=database_name, api_version=api_version, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - if polling is True: - polling_method = cast(PollingMethod, ARMPolling( - lro_delay, - - - **kwargs - )) # type: PollingMethod - elif polling is False: polling_method = cast(PollingMethod, NoPolling()) - else: polling_method = polling + polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_delete.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/databases/{databaseName}"} # type: ignore + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/databases/{databaseName}"} # type: ignore @distributed_trace - def get( - self, - resource_group_name: str, - server_name: str, - database_name: str, - **kwargs: Any - ) -> _models.Database: + def get(self, resource_group_name: str, server_name: str, database_name: str, **kwargs: Any) -> _models.Database: """Gets information about a database. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param database_name: The name of the database. + :param database_name: The name of the database. Required. :type database_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Database, or the result of cls(response) + :return: Database or the result of cls(response) :rtype: ~azure.mgmt.rdbms.mysql_flexibleservers.models.Database - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.Database] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.Database] - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, database_name=database_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], headers=_headers, params=_params, ) @@ -531,64 +581,61 @@ def get( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('Database', pipeline_response) + deserialized = self._deserialize("Database", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/databases/{databaseName}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/databases/{databaseName}"} # type: ignore @distributed_trace - def list_by_server( - self, - resource_group_name: str, - server_name: str, - **kwargs: Any - ) -> Iterable[_models.DatabaseListResult]: + def list_by_server(self, resource_group_name: str, server_name: str, **kwargs: Any) -> Iterable["_models.Database"]: """List all the databases in a given server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either DatabaseListResult or the result of cls(response) - :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql_flexibleservers.models.DatabaseListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Database or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql_flexibleservers.models.Database] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.DatabaseListResult] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.DatabaseListResult] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_server_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_server.metadata['url'], + template_url=self.list_by_server.metadata["url"], headers=_headers, params=_params, ) @@ -596,15 +643,17 @@ def prepare_request(next_link=None): request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_by_server_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - server_name=server_name, - api_version=api_version, - template_url=next_link, - 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() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore @@ -621,10 +670,8 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -634,8 +681,6 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list_by_server.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/databases"} # type: ignore + list_by_server.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/databases"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/operations/_firewall_rules_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/operations/_firewall_rules_operations.py index 62dfb8e053a4..e158a6c2b0fd 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/operations/_firewall_rules_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/operations/_firewall_rules_operations.py @@ -6,11 +6,17 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Iterable, Optional, TypeVar, Union, cast - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse @@ -22,173 +28,153 @@ from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_create_or_update_request_initial( - subscription_id: str, - resource_group_name: str, - server_name: str, - firewall_rule_name: str, - *, - json: Optional[_models.FirewallRule] = None, - content: Any = None, - **kwargs: Any + +def build_create_or_update_request( + resource_group_name: str, server_name: str, firewall_rule_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', None)) # type: Optional[str] - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/firewallRules/{firewallRuleName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/firewallRules/{firewallRuleName}", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), - "firewallRuleName": _SERIALIZER.url("firewall_rule_name", firewall_rule_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), + "firewallRuleName": _SERIALIZER.url("firewall_rule_name", firewall_rule_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _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, - json=json, - content=content, - **kwargs - ) - - -def build_delete_request_initial( - subscription_id: str, - resource_group_name: str, - server_name: str, - firewall_rule_name: str, - **kwargs: Any + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_request( + resource_group_name: str, server_name: str, firewall_rule_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/firewallRules/{firewallRuleName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/firewallRules/{firewallRuleName}", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), - "firewallRuleName": _SERIALIZER.url("firewall_rule_name", firewall_rule_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), + "firewallRuleName": _SERIALIZER.url("firewall_rule_name", firewall_rule_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="DELETE", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) def build_get_request( - subscription_id: str, - resource_group_name: str, - server_name: str, - firewall_rule_name: str, - **kwargs: Any + resource_group_name: str, server_name: str, firewall_rule_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/firewallRules/{firewallRuleName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/firewallRules/{firewallRuleName}", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), - "firewallRuleName": _SERIALIZER.url("firewall_rule_name", firewall_rule_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), + "firewallRuleName": _SERIALIZER.url("firewall_rule_name", firewall_rule_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_list_by_server_request( - subscription_id: str, - resource_group_name: str, - server_name: str, - **kwargs: Any + resource_group_name: str, server_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/firewallRules") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/firewallRules", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) class FirewallRulesOperations: """ @@ -209,38 +195,47 @@ def __init__(self, *args, **kwargs): 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") - def _create_or_update_initial( self, resource_group_name: str, server_name: str, firewall_rule_name: str, - parameters: _models.FirewallRule, + parameters: Union[_models.FirewallRule, IO], **kwargs: Any ) -> Optional[_models.FirewallRule]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[Optional[_models.FirewallRule]] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.FirewallRule]] - _json = self._serialize.body(parameters, 'FirewallRule') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "FirewallRule") - request = build_create_or_update_request_initial( - subscription_id=self._config.subscription_id, + request = build_create_or_update_request( resource_group_name=resource_group_name, server_name=server_name, firewall_rule_name=firewall_rule_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._create_or_update_initial.metadata['url'], + content=_content, + template_url=self._create_or_update_initial.metadata["url"], headers=_headers, params=_params, ) @@ -248,10 +243,9 @@ def _create_or_update_initial( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 201, 202]: @@ -260,38 +254,83 @@ def _create_or_update_initial( deserialized = None if response.status_code == 200: - deserialized = self._deserialize('FirewallRule', pipeline_response) + deserialized = self._deserialize("FirewallRule", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('FirewallRule', pipeline_response) + deserialized = self._deserialize("FirewallRule", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _create_or_update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/firewallRules/{firewallRuleName}"} # type: ignore - + _create_or_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/firewallRules/{firewallRuleName}"} # type: ignore - @distributed_trace + @overload def begin_create_or_update( self, resource_group_name: str, server_name: str, firewall_rule_name: str, parameters: _models.FirewallRule, + *, + content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.FirewallRule]: """Creates a new firewall rule or updates an existing firewall rule. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param firewall_rule_name: The name of the server firewall rule. + :param firewall_rule_name: The name of the server firewall rule. Required. :type firewall_rule_name: str - :param parameters: The required parameters for creating or updating a firewall rule. + :param parameters: The required parameters for creating or updating a firewall rule. Required. :type parameters: ~azure.mgmt.rdbms.mysql_flexibleservers.models.FirewallRule + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + 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 FirewallRule or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql_flexibleservers.models.FirewallRule] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + firewall_rule_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.FirewallRule]: + """Creates a new firewall rule or updates an existing firewall rule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param firewall_rule_name: The name of the server firewall rule. Required. + :type firewall_rule_name: str + :param parameters: The required parameters for creating or updating a firewall rule. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :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 @@ -304,20 +343,56 @@ def begin_create_or_update( cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql_flexibleservers.models.FirewallRule] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_or_update( + self, + resource_group_name: str, + server_name: str, + firewall_rule_name: str, + parameters: Union[_models.FirewallRule, IO], + **kwargs: Any + ) -> LROPoller[_models.FirewallRule]: + """Creates a new firewall rule or updates an existing firewall rule. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param firewall_rule_name: The name of the server firewall rule. Required. + :type firewall_rule_name: str + :param parameters: The required parameters for creating or updating a firewall rule. Is either + a model type or a IO type. Required. + :type parameters: ~azure.mgmt.rdbms.mysql_flexibleservers.models.FirewallRule or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either FirewallRule or the result of + cls(response) + :rtype: + ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql_flexibleservers.models.FirewallRule] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[_models.FirewallRule] - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.FirewallRule] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = self._create_or_update_initial( # type: ignore resource_group_name=resource_group_name, @@ -326,66 +401,60 @@ def begin_create_or_update( parameters=parameters, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize('FirewallRule', pipeline_response) + deserialized = self._deserialize("FirewallRule", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - if polling is True: - polling_method = cast(PollingMethod, ARMPolling( - lro_delay, - - - **kwargs - )) # type: PollingMethod - elif polling is False: polling_method = cast(PollingMethod, NoPolling()) - else: polling_method = polling + polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_create_or_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/firewallRules/{firewallRuleName}"} # type: ignore + begin_create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/firewallRules/{firewallRuleName}"} # type: ignore def _delete_initial( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - server_name: str, - firewall_rule_name: str, - **kwargs: Any + self, resource_group_name: str, server_name: str, firewall_rule_name: str, **kwargs: Any ) -> None: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] - - request = build_delete_request_initial( - subscription_id=self._config.subscription_id, + request = build_delete_request( resource_group_name=resource_group_name, server_name=server_name, firewall_rule_name=firewall_rule_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._delete_initial.metadata['url'], + template_url=self._delete_initial.metadata["url"], headers=_headers, params=_params, ) @@ -393,10 +462,9 @@ def _delete_initial( # pylint: disable=inconsistent-return-statements request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: @@ -406,24 +474,20 @@ def _delete_initial( # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - _delete_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/firewallRules/{firewallRuleName}"} # type: ignore - + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/firewallRules/{firewallRuleName}"} # type: ignore @distributed_trace - def begin_delete( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - server_name: str, - firewall_rule_name: str, - **kwargs: Any + def begin_delete( + self, resource_group_name: str, server_name: str, firewall_rule_name: str, **kwargs: Any ) -> LROPoller[None]: """Deletes a firewall rule. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param firewall_rule_name: The name of the server firewall rule. + :param firewall_rule_name: The name of the server firewall rule. Required. :type firewall_rule_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. @@ -435,97 +499,89 @@ def begin_delete( # pylint: disable=inconsistent-return-statements Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = self._delete_initial( # type: ignore resource_group_name=resource_group_name, server_name=server_name, firewall_rule_name=firewall_rule_name, api_version=api_version, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - if polling is True: - polling_method = cast(PollingMethod, ARMPolling( - lro_delay, - - - **kwargs - )) # type: PollingMethod - elif polling is False: polling_method = cast(PollingMethod, NoPolling()) - else: polling_method = polling + polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_delete.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/firewallRules/{firewallRuleName}"} # type: ignore + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/firewallRules/{firewallRuleName}"} # type: ignore @distributed_trace def get( - self, - resource_group_name: str, - server_name: str, - firewall_rule_name: str, - **kwargs: Any + self, resource_group_name: str, server_name: str, firewall_rule_name: str, **kwargs: Any ) -> _models.FirewallRule: """Gets information about a server firewall rule. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param firewall_rule_name: The name of the server firewall rule. + :param firewall_rule_name: The name of the server firewall rule. Required. :type firewall_rule_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: FirewallRule, or the result of cls(response) + :return: FirewallRule or the result of cls(response) :rtype: ~azure.mgmt.rdbms.mysql_flexibleservers.models.FirewallRule - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.FirewallRule] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.FirewallRule] - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, firewall_rule_name=firewall_rule_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], headers=_headers, params=_params, ) @@ -533,65 +589,64 @@ def get( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('FirewallRule', pipeline_response) + deserialized = self._deserialize("FirewallRule", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/firewallRules/{firewallRuleName}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/firewallRules/{firewallRuleName}"} # type: ignore @distributed_trace def list_by_server( - self, - resource_group_name: str, - server_name: str, - **kwargs: Any - ) -> Iterable[_models.FirewallRuleListResult]: + self, resource_group_name: str, server_name: str, **kwargs: Any + ) -> Iterable["_models.FirewallRule"]: """List all the firewall rules in a given server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either FirewallRuleListResult or the result of - cls(response) + :return: An iterator like instance of either FirewallRule or the result of cls(response) :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql_flexibleservers.models.FirewallRuleListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql_flexibleservers.models.FirewallRule] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.FirewallRuleListResult] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.FirewallRuleListResult] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_server_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_server.metadata['url'], + template_url=self.list_by_server.metadata["url"], headers=_headers, params=_params, ) @@ -599,15 +654,17 @@ def prepare_request(next_link=None): request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_by_server_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - server_name=server_name, - api_version=api_version, - template_url=next_link, - 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() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore @@ -624,10 +681,8 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -637,8 +692,6 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list_by_server.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/firewallRules"} # type: ignore + list_by_server.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/firewallRules"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/operations/_get_private_dns_zone_suffix_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/operations/_get_private_dns_zone_suffix_operations.py index 7b6d093d88a6..af41acc3c3b0 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/operations/_get_private_dns_zone_suffix_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/operations/_get_private_dns_zone_suffix_operations.py @@ -8,9 +8,14 @@ # -------------------------------------------------------------------------- from typing import Any, Callable, Dict, Optional, TypeVar -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest @@ -19,38 +24,34 @@ from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_execute_request( - **kwargs: Any -) -> HttpRequest: + +def build_execute_request(**kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop("template_url", "/providers/Microsoft.DBforMySQL/getPrivateDnsZoneSuffix") # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - return HttpRequest( - method="POST", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) class GetPrivateDnsZoneSuffixOperations: """ @@ -71,34 +72,32 @@ def __init__(self, *args, **kwargs): self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace - def execute( - self, - **kwargs: Any - ) -> _models.GetPrivateDnsZoneSuffixResponse: + def execute(self, **kwargs: Any) -> _models.GetPrivateDnsZoneSuffixResponse: """Get private DNS zone suffix in the cloud. :keyword callable cls: A custom type or function that will be passed the direct response - :return: GetPrivateDnsZoneSuffixResponse, or the result of cls(response) + :return: GetPrivateDnsZoneSuffixResponse or the result of cls(response) :rtype: ~azure.mgmt.rdbms.mysql_flexibleservers.models.GetPrivateDnsZoneSuffixResponse - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.GetPrivateDnsZoneSuffixResponse] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.GetPrivateDnsZoneSuffixResponse] - request = build_execute_request( api_version=api_version, - template_url=self.execute.metadata['url'], + template_url=self.execute.metadata["url"], headers=_headers, params=_params, ) @@ -106,22 +105,20 @@ def execute( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('GetPrivateDnsZoneSuffixResponse', pipeline_response) + deserialized = self._deserialize("GetPrivateDnsZoneSuffixResponse", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - execute.metadata = {'url': "/providers/Microsoft.DBforMySQL/getPrivateDnsZoneSuffix"} # type: ignore - + execute.metadata = {"url": "/providers/Microsoft.DBforMySQL/getPrivateDnsZoneSuffix"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/operations/_location_based_capabilities_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/operations/_location_based_capabilities_operations.py index 6deb6dd7be40..24dab3bcccb1 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/operations/_location_based_capabilities_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/operations/_location_based_capabilities_operations.py @@ -7,10 +7,16 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from typing import Any, Callable, Dict, Iterable, Optional, TypeVar - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse @@ -20,46 +26,43 @@ from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_list_request( - subscription_id: str, - location_name: str, - **kwargs: Any -) -> HttpRequest: + +def build_list_request(location_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/locations/{locationName}/capabilities") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/locations/{locationName}/capabilities", + ) # pylint: disable=line-too-long path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), - "locationName": _SERIALIZER.url("location_name", location_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "locationName": _SERIALIZER.url("location_name", location_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) class LocationBasedCapabilitiesOperations: """ @@ -80,42 +83,41 @@ def __init__(self, *args, **kwargs): self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace - def list( - self, - location_name: str, - **kwargs: Any - ) -> Iterable[_models.CapabilitiesListResult]: + def list(self, location_name: str, **kwargs: Any) -> Iterable["_models.CapabilityProperties"]: """Get capabilities at specified location in a given subscription. - :param location_name: The name of the location. + :param location_name: The name of the location. Required. :type location_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either CapabilitiesListResult or the result of + :return: An iterator like instance of either CapabilityProperties or the result of cls(response) :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql_flexibleservers.models.CapabilitiesListResult] - :raises: ~azure.core.exceptions.HttpResponseError + ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql_flexibleservers.models.CapabilityProperties] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.CapabilitiesListResult] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.CapabilitiesListResult] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( - subscription_id=self._config.subscription_id, location_name=location_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list.metadata['url'], + template_url=self.list.metadata["url"], headers=_headers, params=_params, ) @@ -123,14 +125,17 @@ def prepare_request(next_link=None): request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_request( - subscription_id=self._config.subscription_id, - location_name=location_name, - api_version=api_version, - template_url=next_link, - 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() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore @@ -147,10 +152,8 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -160,8 +163,6 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/locations/{locationName}/capabilities"} # type: ignore + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/locations/{locationName}/capabilities"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/operations/_log_files_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/operations/_log_files_operations.py index 79301b6107e9..3f9ad90ac33a 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/operations/_log_files_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/operations/_log_files_operations.py @@ -7,10 +7,16 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from typing import Any, Callable, Dict, Iterable, Optional, TypeVar - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse @@ -20,48 +26,48 @@ from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False + def build_list_by_server_request( - subscription_id: str, - resource_group_name: str, - server_name: str, - **kwargs: Any + resource_group_name: str, server_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/logFiles") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/logFiles", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) class LogFilesOperations: """ @@ -82,45 +88,43 @@ def __init__(self, *args, **kwargs): self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace - def list_by_server( - self, - resource_group_name: str, - server_name: str, - **kwargs: Any - ) -> Iterable[_models.LogFileListResult]: + def list_by_server(self, resource_group_name: str, server_name: str, **kwargs: Any) -> Iterable["_models.LogFile"]: """List all the server log files in a given server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either LogFileListResult or the result of cls(response) - :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql_flexibleservers.models.LogFileListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either LogFile or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql_flexibleservers.models.LogFile] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.LogFileListResult] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.LogFileListResult] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_server_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_server.metadata['url'], + template_url=self.list_by_server.metadata["url"], headers=_headers, params=_params, ) @@ -128,15 +132,17 @@ def prepare_request(next_link=None): request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_by_server_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - server_name=server_name, - api_version=api_version, - template_url=next_link, - 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() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore @@ -153,10 +159,8 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -166,8 +170,6 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list_by_server.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/logFiles"} # type: ignore + list_by_server.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/logFiles"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/operations/_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/operations/_operations.py index 8c67773edf95..e385995dce82 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/operations/_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/operations/_operations.py @@ -7,10 +7,16 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from typing import Any, Callable, Dict, Iterable, Optional, TypeVar - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse @@ -20,38 +26,34 @@ from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_list_request( - **kwargs: Any -) -> HttpRequest: + +def build_list_request(**kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop("template_url", "/providers/Microsoft.DBforMySQL/operations") # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) class Operations: """ @@ -72,36 +74,35 @@ def __init__(self, *args, **kwargs): self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace - def list( - self, - **kwargs: Any - ) -> Iterable[_models.OperationListResult]: + def list(self, **kwargs: Any) -> Iterable["_models.Operation"]: """Lists all of the available REST API operations. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either OperationListResult or the result of cls(response) - :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql_flexibleservers.models.OperationListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Operation or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql_flexibleservers.models.Operation] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.OperationListResult] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.OperationListResult] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( api_version=api_version, - template_url=self.list.metadata['url'], + template_url=self.list.metadata["url"], headers=_headers, params=_params, ) @@ -109,12 +110,17 @@ def prepare_request(next_link=None): request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_request( - api_version=api_version, - template_url=next_link, - 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() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore @@ -131,10 +137,8 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -144,8 +148,6 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/providers/Microsoft.DBforMySQL/operations"} # type: ignore + list.metadata = {"url": "/providers/Microsoft.DBforMySQL/operations"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/operations/_patch.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/operations/_patch.py index 0ad201a8c586..f7dd32510333 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/operations/_patch.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/operations/_patch.py @@ -10,6 +10,7 @@ __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. diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/operations/_replicas_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/operations/_replicas_operations.py index 178876da7ecd..7f6c6a84c151 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/operations/_replicas_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/operations/_replicas_operations.py @@ -7,10 +7,16 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from typing import Any, Callable, Dict, Iterable, Optional, TypeVar - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse @@ -20,48 +26,48 @@ from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False + def build_list_by_server_request( - subscription_id: str, - resource_group_name: str, - server_name: str, - **kwargs: Any + resource_group_name: str, server_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/replicas") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/replicas", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) class ReplicasOperations: """ @@ -82,45 +88,43 @@ def __init__(self, *args, **kwargs): self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") - @distributed_trace - def list_by_server( - self, - resource_group_name: str, - server_name: str, - **kwargs: Any - ) -> Iterable[_models.ServerListResult]: + def list_by_server(self, resource_group_name: str, server_name: str, **kwargs: Any) -> Iterable["_models.Server"]: """List all the replicas for a given server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ServerListResult or the result of cls(response) - :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql_flexibleservers.models.ServerListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Server or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql_flexibleservers.models.Server] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.ServerListResult] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ServerListResult] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_server_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_server.metadata['url'], + template_url=self.list_by_server.metadata["url"], headers=_headers, params=_params, ) @@ -128,15 +132,17 @@ def prepare_request(next_link=None): request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_by_server_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - server_name=server_name, - api_version=api_version, - template_url=next_link, - 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() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore @@ -153,10 +159,8 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -166,8 +170,6 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list_by_server.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/replicas"} # type: ignore + list_by_server.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/replicas"} # type: ignore diff --git a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/operations/_servers_operations.py b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/operations/_servers_operations.py index e7d31cca6a1c..b46ff31f1a34 100644 --- a/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/operations/_servers_operations.py +++ b/sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mysql_flexibleservers/operations/_servers_operations.py @@ -6,11 +6,17 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Iterable, Optional, TypeVar, Union, cast - -from msrest import Serializer - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse @@ -22,399 +28,336 @@ from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models +from .._serialization import Serializer from .._vendor import _convert_request, _format_url_section -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_create_request_initial( - subscription_id: str, - resource_group_name: str, - server_name: str, - *, - json: Optional[_models.Server] = None, - content: Any = None, - **kwargs: Any + +def build_create_request( + resource_group_name: str, server_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', None)) # type: Optional[str] - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _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, - json=json, - content=content, - **kwargs - ) - - -def build_update_request_initial( - subscription_id: str, - resource_group_name: str, - server_name: str, - *, - json: Optional[_models.ServerForUpdate] = None, - content: Any = None, - **kwargs: Any + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_update_request( + resource_group_name: str, server_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', None)) # type: Optional[str] - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _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, - json=json, - content=content, - **kwargs - ) - - -def build_delete_request_initial( - subscription_id: str, - resource_group_name: str, - server_name: str, - **kwargs: Any + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_request( + resource_group_name: str, server_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="DELETE", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) - - -def build_get_request( - subscription_id: str, - resource_group_name: str, - server_name: str, - **kwargs: Any -) -> HttpRequest: + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_request(resource_group_name: str, server_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="GET", - 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( - subscription_id: str, - resource_group_name: str, - **kwargs: Any -) -> HttpRequest: +def build_list_by_resource_group_request(resource_group_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers", + ) # 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), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_list_request( - subscription_id: str, - **kwargs: Any -) -> HttpRequest: +def build_list_request(subscription_id: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/flexibleServers") path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str', min_length=1), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="GET", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) - - -def build_failover_request_initial( - subscription_id: str, - resource_group_name: str, - server_name: str, - **kwargs: Any + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_failover_request( + resource_group_name: str, server_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/failover") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/failover", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="POST", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) - - -def build_restart_request_initial( - subscription_id: str, - resource_group_name: str, - server_name: str, - *, - json: Optional[_models.ServerRestartParameter] = None, - content: Any = None, - **kwargs: Any + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_restart_request( + resource_group_name: str, server_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', None)) # type: Optional[str] - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/restart") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/restart", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers if content_type is not None: - _headers['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="POST", - url=_url, - params=_params, - headers=_headers, - json=json, - content=content, - **kwargs - ) - - -def build_start_request_initial( - subscription_id: str, - resource_group_name: str, - server_name: str, - **kwargs: Any -) -> HttpRequest: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_start_request(resource_group_name: str, server_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/start") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/start", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') - - return HttpRequest( - method="POST", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) - - -def build_stop_request_initial( - subscription_id: str, - resource_group_name: str, - server_name: str, - **kwargs: Any -) -> HttpRequest: + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_stop_request(resource_group_name: str, server_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - accept = _headers.pop('Accept', "application/json") + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-12-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/stop") # pylint: disable=line-too-long + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/stop", + ) # 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), - "serverName": _SERIALIZER.url("server_name", server_name, 'str'), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "serverName": _SERIALIZER.url("server_name", server_name, "str"), } _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - return HttpRequest( - method="POST", - url=_url, - params=_params, - headers=_headers, - **kwargs - ) class ServersOperations: """ @@ -435,36 +378,41 @@ def __init__(self, *args, **kwargs): 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") - def _create_initial( - self, - resource_group_name: str, - server_name: str, - parameters: _models.Server, - **kwargs: Any + self, resource_group_name: str, server_name: str, parameters: Union[_models.Server, IO], **kwargs: Any ) -> Optional[_models.Server]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[Optional[_models.Server]] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.Server]] - _json = self._serialize.body(parameters, 'Server') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Server") - request = build_create_request_initial( - subscription_id=self._config.subscription_id, + request = build_create_request( resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._create_initial.metadata['url'], + content=_content, + template_url=self._create_initial.metadata["url"], headers=_headers, params=_params, ) @@ -472,10 +420,9 @@ def _create_initial( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 201, 202]: @@ -484,36 +431,108 @@ def _create_initial( deserialized = None if response.status_code == 200: - deserialized = self._deserialize('Server', pipeline_response) + deserialized = self._deserialize("Server", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('Server', pipeline_response) + deserialized = self._deserialize("Server", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _create_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}"} # type: ignore - + _create_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}"} # type: ignore - @distributed_trace + @overload def begin_create( self, resource_group_name: str, server_name: str, parameters: _models.Server, + *, + content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.Server]: """Creates a new server or updates an existing server. The update action will overwrite the existing server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param parameters: The required parameters for creating or updating a server. + :param parameters: The required parameters for creating or updating a server. Required. :type parameters: ~azure.mgmt.rdbms.mysql_flexibleservers.models.Server + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + 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 Server or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql_flexibleservers.models.Server] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create( + self, + resource_group_name: str, + server_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.Server]: + """Creates a new server or updates an existing server. The update action will overwrite the + existing server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param parameters: The required parameters for creating or updating a server. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :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 Server or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql_flexibleservers.models.Server] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create( + self, resource_group_name: str, server_name: str, parameters: Union[_models.Server, IO], **kwargs: Any + ) -> LROPoller[_models.Server]: + """Creates a new server or updates an existing server. The update action will overwrite the + existing server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param parameters: The required parameters for creating or updating a server. Is either a model + type or a IO type. Required. + :type parameters: ~azure.mgmt.rdbms.mysql_flexibleservers.models.Server or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/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 @@ -524,20 +543,17 @@ def begin_create( Retry-After header is present. :return: An instance of LROPoller that returns either Server or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql_flexibleservers.models.Server] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[_models.Server] - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Server] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = self._create_initial( # type: ignore resource_group_name=resource_group_name, @@ -545,69 +561,71 @@ def begin_create( parameters=parameters, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize('Server', pipeline_response) + deserialized = self._deserialize("Server", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - if polling is True: - polling_method = cast(PollingMethod, ARMPolling( - lro_delay, - - - **kwargs - )) # type: PollingMethod - elif polling is False: polling_method = cast(PollingMethod, NoPolling()) - else: polling_method = polling + polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_create.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}"} # type: ignore + begin_create.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}"} # type: ignore def _update_initial( - self, - resource_group_name: str, - server_name: str, - parameters: _models.ServerForUpdate, - **kwargs: Any + self, resource_group_name: str, server_name: str, parameters: Union[_models.ServerForUpdate, IO], **kwargs: Any ) -> Optional[_models.Server]: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[Optional[_models.Server]] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.Server]] - _json = self._serialize.body(parameters, 'ServerForUpdate') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ServerForUpdate") - request = build_update_request_initial( - subscription_id=self._config.subscription_id, + request = build_update_request( resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._update_initial.metadata['url'], + content=_content, + template_url=self._update_initial.metadata["url"], headers=_headers, params=_params, ) @@ -615,10 +633,9 @@ def _update_initial( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202]: @@ -627,33 +644,38 @@ def _update_initial( deserialized = None if response.status_code == 200: - deserialized = self._deserialize('Server', pipeline_response) + deserialized = self._deserialize("Server", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _update_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}"} # type: ignore - + _update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}"} # type: ignore - @distributed_trace + @overload def begin_update( self, resource_group_name: str, server_name: str, parameters: _models.ServerForUpdate, + *, + content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.Server]: """Updates an existing server. The request body can contain one to many of the properties present in the normal server definition. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param parameters: The required parameters for updating a server. + :param parameters: The required parameters for updating a server. Required. :type parameters: ~azure.mgmt.rdbms.mysql_flexibleservers.models.ServerForUpdate + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + 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 @@ -664,20 +686,84 @@ def begin_update( Retry-After header is present. :return: An instance of LROPoller that returns either Server or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql_flexibleservers.models.Server] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_update( + self, + resource_group_name: str, + server_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.Server]: + """Updates an existing server. The request body can contain one to many of the properties present + in the normal server definition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param parameters: The required parameters for updating a server. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :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 Server or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql_flexibleservers.models.Server] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_update( + self, resource_group_name: str, server_name: str, parameters: Union[_models.ServerForUpdate, IO], **kwargs: Any + ) -> LROPoller[_models.Server]: + """Updates an existing server. The request body can contain one to many of the properties present + in the normal server definition. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param parameters: The required parameters for updating a server. Is either a model type or a + IO type. Required. + :type parameters: ~azure.mgmt.rdbms.mysql_flexibleservers.models.ServerForUpdate or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either Server or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.rdbms.mysql_flexibleservers.models.Server] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[_models.Server] - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Server] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = self._update_initial( # type: ignore resource_group_name=resource_group_name, @@ -685,64 +771,59 @@ def begin_update( parameters=parameters, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize('Server', pipeline_response) + deserialized = self._deserialize("Server", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - if polling is True: - polling_method = cast(PollingMethod, ARMPolling( - lro_delay, - - - **kwargs - )) # type: PollingMethod - elif polling is False: polling_method = cast(PollingMethod, NoPolling()) - else: polling_method = polling + polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}"} # type: ignore + begin_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}"} # type: ignore def _delete_initial( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - server_name: str, - **kwargs: Any + self, resource_group_name: str, server_name: str, **kwargs: Any ) -> None: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] - - request = build_delete_request_initial( - subscription_id=self._config.subscription_id, + request = build_delete_request( resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._delete_initial.metadata['url'], + template_url=self._delete_initial.metadata["url"], headers=_headers, params=_params, ) @@ -750,10 +831,9 @@ def _delete_initial( # pylint: disable=inconsistent-return-statements request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: @@ -763,21 +843,16 @@ def _delete_initial( # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - _delete_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}"} # type: ignore - + _delete_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}"} # type: ignore @distributed_trace - def begin_delete( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - server_name: str, - **kwargs: Any - ) -> LROPoller[None]: + def begin_delete(self, resource_group_name: str, server_name: str, **kwargs: Any) -> LROPoller[None]: """Deletes a server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_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. @@ -789,92 +864,83 @@ def begin_delete( # pylint: disable=inconsistent-return-statements Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = self._delete_initial( # type: ignore resource_group_name=resource_group_name, server_name=server_name, api_version=api_version, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - if polling is True: - polling_method = cast(PollingMethod, ARMPolling( - lro_delay, - - - **kwargs - )) # type: PollingMethod - elif polling is False: polling_method = cast(PollingMethod, NoPolling()) - else: polling_method = polling + polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_delete.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}"} # type: ignore + begin_delete.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}"} # type: ignore @distributed_trace - def get( - self, - resource_group_name: str, - server_name: str, - **kwargs: Any - ) -> _models.Server: + def get(self, resource_group_name: str, server_name: str, **kwargs: Any) -> _models.Server: """Gets information about a server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Server, or the result of cls(response) + :return: Server or the result of cls(response) :rtype: ~azure.mgmt.rdbms.mysql_flexibleservers.models.Server - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.Server] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.Server] - request = build_get_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata['url'], + template_url=self.get.metadata["url"], headers=_headers, params=_params, ) @@ -882,60 +948,58 @@ def get( request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) - deserialized = self._deserialize('Server', pipeline_response) + deserialized = self._deserialize("Server", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}"} # type: ignore - + get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}"} # type: ignore @distributed_trace - def list_by_resource_group( - self, - resource_group_name: str, - **kwargs: Any - ) -> Iterable[_models.ServerListResult]: + def list_by_resource_group(self, resource_group_name: str, **kwargs: Any) -> Iterable["_models.Server"]: """List all the servers in a given 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 ServerListResult or the result of cls(response) - :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql_flexibleservers.models.ServerListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Server or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql_flexibleservers.models.Server] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.ServerListResult] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ServerListResult] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_by_resource_group_request( - subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata['url'], + template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) @@ -943,14 +1007,17 @@ def prepare_request(next_link=None): request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_by_resource_group_request( - subscription_id=self._config.subscription_id, - resource_group_name=resource_group_name, - api_version=api_version, - template_url=next_link, - 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() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore @@ -967,10 +1034,8 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -980,42 +1045,40 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list_by_resource_group.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers"} # type: ignore + list_by_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers"} # type: ignore @distributed_trace - def list( - self, - **kwargs: Any - ) -> Iterable[_models.ServerListResult]: + def list(self, **kwargs: Any) -> Iterable["_models.Server"]: """List all the servers in a given subscription. :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ServerListResult or the result of cls(response) - :rtype: - ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql_flexibleservers.models.ServerListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Server or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.rdbms.mysql_flexibleservers.models.Server] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[_models.ServerListResult] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.ServerListResult] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) + def prepare_request(next_link=None): if not next_link: - + request = build_list_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list.metadata['url'], + template_url=self.list.metadata["url"], headers=_headers, params=_params, ) @@ -1023,13 +1086,17 @@ def prepare_request(next_link=None): request.url = self._client.format_url(request.url) # type: ignore else: - - request = build_list_request( - subscription_id=self._config.subscription_id, - api_version=api_version, - template_url=next_link, - 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() + } + ) + _next_request_params["api-version"] = self._config.api_version + request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore @@ -1046,10 +1113,8 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -1059,36 +1124,33 @@ def get_next(next_link=None): return pipeline_response + return ItemPaged(get_next, extract_data) - return ItemPaged( - get_next, extract_data - ) - list.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/flexibleServers"} # type: ignore + list.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/flexibleServers"} # type: ignore def _failover_initial( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - server_name: str, - **kwargs: Any + self, resource_group_name: str, server_name: str, **kwargs: Any ) -> None: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] - - request = build_failover_request_initial( - subscription_id=self._config.subscription_id, + request = build_failover_request( resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._failover_initial.metadata['url'], + template_url=self._failover_initial.metadata["url"], headers=_headers, params=_params, ) @@ -1096,10 +1158,9 @@ def _failover_initial( # pylint: disable=inconsistent-return-statements request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202]: @@ -1109,21 +1170,16 @@ def _failover_initial( # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - _failover_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/failover"} # type: ignore - + _failover_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/failover"} # type: ignore @distributed_trace - def begin_failover( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - server_name: str, - **kwargs: Any - ) -> LROPoller[None]: + def begin_failover(self, resource_group_name: str, server_name: str, **kwargs: Any) -> LROPoller[None]: """Manual failover a server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_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. @@ -1135,85 +1191,88 @@ def begin_failover( # pylint: disable=inconsistent-return-statements Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = self._failover_initial( # type: ignore resource_group_name=resource_group_name, server_name=server_name, api_version=api_version, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - if polling is True: - polling_method = cast(PollingMethod, ARMPolling( - lro_delay, - - - **kwargs - )) # type: PollingMethod - elif polling is False: polling_method = cast(PollingMethod, NoPolling()) - else: polling_method = polling + polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_failover.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/failover"} # type: ignore + begin_failover.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/failover"} # type: ignore def _restart_initial( # pylint: disable=inconsistent-return-statements self, resource_group_name: str, server_name: str, - parameters: _models.ServerRestartParameter, + parameters: Union[_models.ServerRestartParameter, IO], **kwargs: Any ) -> None: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[None] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[None] - _json = self._serialize.body(parameters, 'ServerRestartParameter') + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "ServerRestartParameter") - request = build_restart_request_initial( - subscription_id=self._config.subscription_id, + request = build_restart_request( resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, content_type=content_type, json=_json, - template_url=self._restart_initial.metadata['url'], + content=_content, + template_url=self._restart_initial.metadata["url"], headers=_headers, params=_params, ) @@ -1221,10 +1280,9 @@ def _restart_initial( # pylint: disable=inconsistent-return-statements request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202]: @@ -1234,25 +1292,30 @@ def _restart_initial( # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - _restart_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/restart"} # type: ignore + _restart_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/restart"} # type: ignore - - @distributed_trace - def begin_restart( # pylint: disable=inconsistent-return-statements + @overload + def begin_restart( self, resource_group_name: str, server_name: str, parameters: _models.ServerRestartParameter, + *, + content_type: str = "application/json", **kwargs: Any ) -> LROPoller[None]: """Restarts a server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_name: str - :param parameters: The required parameters for restarting a server. + :param parameters: The required parameters for restarting a server. Required. :type parameters: ~azure.mgmt.rdbms.mysql_flexibleservers.models.ServerRestartParameter + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + 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 @@ -1263,20 +1326,86 @@ def begin_restart( # pylint: disable=inconsistent-return-statements Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_restart( + self, + resource_group_name: str, + server_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[None]: + """Restarts a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param parameters: The required parameters for restarting a server. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :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: + """ + + @distributed_trace + def begin_restart( + self, + resource_group_name: str, + server_name: str, + parameters: Union[_models.ServerRestartParameter, IO], + **kwargs: Any + ) -> LROPoller[None]: + """Restarts a server. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param server_name: The name of the server. Required. + :type server_name: str + :param parameters: The required parameters for restarting a server. Is either a model type or a + IO type. Required. + :type parameters: ~azure.mgmt.rdbms.mysql_flexibleservers.models.ServerRestartParameter or IO + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :keyword callable cls: A custom type or function that will be passed the direct response + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either None or the result of cls(response) + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json")) # type: Optional[str] - cls = kwargs.pop('cls', None) # type: ClsType[None] - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = self._restart_initial( # type: ignore resource_group_name=resource_group_name, @@ -1284,62 +1413,57 @@ def begin_restart( # pylint: disable=inconsistent-return-statements parameters=parameters, api_version=api_version, content_type=content_type, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - if polling is True: - polling_method = cast(PollingMethod, ARMPolling( - lro_delay, - - - **kwargs - )) # type: PollingMethod - elif polling is False: polling_method = cast(PollingMethod, NoPolling()) - else: polling_method = polling + polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_restart.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/restart"} # type: ignore + begin_restart.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/restart"} # type: ignore def _start_initial( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - server_name: str, - **kwargs: Any + self, resource_group_name: str, server_name: str, **kwargs: Any ) -> None: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] - - request = build_start_request_initial( - subscription_id=self._config.subscription_id, + request = build_start_request( resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._start_initial.metadata['url'], + template_url=self._start_initial.metadata["url"], headers=_headers, params=_params, ) @@ -1347,10 +1471,9 @@ def _start_initial( # pylint: disable=inconsistent-return-statements request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202]: @@ -1360,21 +1483,16 @@ def _start_initial( # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - _start_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/start"} # type: ignore - + _start_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/start"} # type: ignore @distributed_trace - def begin_start( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - server_name: str, - **kwargs: Any - ) -> LROPoller[None]: + def begin_start(self, resource_group_name: str, server_name: str, **kwargs: Any) -> LROPoller[None]: """Starts a server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_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. @@ -1386,80 +1504,72 @@ def begin_start( # pylint: disable=inconsistent-return-statements Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = self._start_initial( # type: ignore resource_group_name=resource_group_name, server_name=server_name, api_version=api_version, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - if polling is True: - polling_method = cast(PollingMethod, ARMPolling( - lro_delay, - - - **kwargs - )) # type: PollingMethod - elif polling is False: polling_method = cast(PollingMethod, NoPolling()) - else: polling_method = polling + polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_start.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/start"} # type: ignore + begin_start.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/start"} # type: ignore def _stop_initial( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - server_name: str, - **kwargs: Any + self, resource_group_name: str, server_name: str, **kwargs: Any ) -> None: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {}) or {}) + error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] - - request = build_stop_request_initial( - subscription_id=self._config.subscription_id, + request = build_stop_request( resource_group_name=resource_group_name, server_name=server_name, + subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self._stop_initial.metadata['url'], + template_url=self._stop_initial.metadata["url"], headers=_headers, params=_params, ) @@ -1467,10 +1577,9 @@ def _stop_initial( # pylint: disable=inconsistent-return-statements request.url = self._client.format_url(request.url) # type: ignore pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) + response = pipeline_response.http_response if response.status_code not in [200, 202]: @@ -1480,21 +1589,16 @@ def _stop_initial( # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - _stop_initial.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/stop"} # type: ignore - + _stop_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/stop"} # type: ignore @distributed_trace - def begin_stop( # pylint: disable=inconsistent-return-statements - self, - resource_group_name: str, - server_name: str, - **kwargs: Any - ) -> LROPoller[None]: + def begin_stop(self, resource_group_name: str, server_name: str, **kwargs: Any) -> LROPoller[None]: """Stops a server. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param server_name: The name of the server. + :param server_name: The name of the server. Required. :type server_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. @@ -1506,52 +1610,45 @@ def begin_stop( # pylint: disable=inconsistent-return-statements Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop('api_version', _params.pop('api-version', "2021-12-01-preview")) # type: str - cls = kwargs.pop('cls', None) # type: ClsType[None] - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version)) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: raw_result = self._stop_initial( # type: ignore resource_group_name=resource_group_name, server_name=server_name, api_version=api_version, - cls=lambda x,y,z: x, + cls=lambda x, y, z: x, headers=_headers, params=_params, **kwargs ) - kwargs.pop('error_map', None) + kwargs.pop("error_map", None) - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - if polling is True: - polling_method = cast(PollingMethod, ARMPolling( - lro_delay, - - - **kwargs - )) # type: PollingMethod - elif polling is False: polling_method = cast(PollingMethod, NoPolling()) - else: polling_method = polling + polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_stop.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/stop"} # type: ignore + begin_stop.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/stop"} # type: ignore